text:
Q: How to fully emulate the behavior of static class variables of other languages in Python It is well established that Python does not have "static class variables" in the same sense as in other languages. Instead, it has class attributes, which are similar, but very different.
For example, a class attribute (a variable defined inside of a class definition) can be "overridden" by an instance attribute of the same name:
class A():
    i = 1

assert A.i == 1
a = A()
assert a.i == 1
a.i = 2 # has A.i been updated to 2 as well?
assert A.i == 2 # ERROR: no, it hasn't
assert a.i == 2 # A.i and a.i are two different variables
del a.i
assert a.i == 1 # If a.i doesn't exist, falls back in A.i

In actuality, there is no "overriding" going on - the class dictionary just comes later in the attribute lookup order than the instance dictionary.
This behavior can be partially overcome using the property decorator:
class A():
    _i = 1
    @property
    def i(self):
        return type(self)._i
    @i.setter
    def i(self,value):
        type(self)._i = value

Now, the property will remain "in sync" between the multiple instances:
a1 = A()
a2 = A()
a1.i = 2
assert a1.i == a2.i # i attribute remained in sync

However, the "gotcha" here is that you cannot access or set the property via the class itself:
assert A.i == a.i # ERROR
type(A.i) # class 'property'
A.i = 10 # if I try to set via the class...
assert a.i == 10 # it appears to have worked!
a.i = 5 # but...
assert A.i == a.i # ERROR! It didn't work.
type(A.i) # int - setting the property via the class actually overwrote it

This difficulty can be overcome using a full-fledged descriptor (of which property is only one type):
class MyProperty():
    def __init__(self,name):
        self.name = name
    def __get__(self,inst,cls):
        return getattr(cls,self.name)
    def __set__(self,inst,value):
        setattr(type(inst),self.name,value)
    def __delete__(self,inst):
        delattr(type(inst),self.name)

class A():
    i = MyProperty('i')

Now, getting and setting the attribute via the class and via the instance all work, and deleting via the instance also works:
a = A()
A.i = 5 # Can set via the class
assert a.i == A.i
a.i = 10
assert a.i == A.i # Still in sync!
del a.i
assert A.i # Error, as expected
A.i = 2
assert a.i == 2

However, there is still a problem when you try to delete via the class:
del A.i # The MyProperty descriptor has been deleted
A.i = 2
a.i = 4
assert A.i == a.i # ERROR!

How can full emulation of "static variables" be achieved in Python?

A: I present the (Python 3) solution below for informational purposes only. I am not endorsing it as a "good solution". I have my doubts as to whether emulating the static variable behavior of other languages in Python is ever actually necessary. However, regardless as to whether it is actually useful, creating the code below helped me further understand how Python works, so it might help others as well.
The metaclass I have created below attempts to emulate "static variable" behavior of other languages. It's pretty complicated, but it basically works by replacing the normal getter, setter, and deleter with versions which check to see if the attribute being requested is a "static variable". A catalog of the "static variables" is stored in the StaticVarMeta.statics attribute. If the requested attribute is not a "static variable", the class will fall back on the default attribute get/set/delete behavior. If it IS a "static variable", it attempted to resolve the attribute request using a substitute resolution order (which I have dubbed the __sro__, or "static resolution order").
I am sure there are simpler ways to accomplish this, and look forward to seeing other answers.
from functools import wraps

class StaticVarsMeta(type):
    '''A metaclass for creating classes that emulate the "static variable" behavior
    of other languages. I do not advise actually using this for anything!!!

    Behavior is intended to be similar to classes that use __slots__. However, "normal"
    attributes and __statics___ can coexist (unlike with __slots__).

    Example usage:

        class MyBaseClass(metaclass = StaticVarsMeta):
            __statics__ = {'a','b','c'}
            i = 1 # regular attribute

        class MyParentClass(MyBaseClass):
            __statics__ = {'d','e','f'}
            j = 2 # regular attribute
            d, e, f = 3, 4, 5 # Static vars
            a, b, c = 6, 7, 8 # Static vars (inherited from MyBaseClass, defined here)

        class MyChildClass(MyParentClass):
            __statics__ = {'a','b','c'}
            j = 2 # regular attribute (redefines j from MyParentClass)
            d, e, f = 9, 10, 11 # Static vars (inherited from MyParentClass, redefined here)
            a, b, c = 12, 14, 14 # Static vars (overriding previous definition in MyParentClass here)'''
    statics = {}
    def __new__(mcls, name, bases, namespace):
        # Get the class object
        cls = super().__new__(mcls, name, bases, namespace)
        # Establish the "statics resolution order"
        cls.__sro__ = tuple(c for c in cls.__mro__ if isinstance(c,mcls))

        # Replace class getter, setter, and deleter for instance attributes
        cls.__getattribute__ = StaticVarsMeta.__inst_getattribute__(cls, cls.__getattribute__)
        cls.__setattr__ = StaticVarsMeta.__inst_setattr__(cls, cls.__setattr__)
        cls.__delattr__ = StaticVarsMeta.__inst_delattr__(cls, cls.__delattr__)
        # Store the list of static variables for the class object
        # This list is permanent and cannot be changed, similar to __slots__
        try:
            mcls.statics[cls] = getattr(cls,'__statics__')
        except AttributeError:
            mcls.statics[cls] = namespace['__statics__'] = set() # No static vars provided
        # Check and make sure the statics var names are strings
        if any(not isinstance(static,str) for static in mcls.statics[cls]):
            typ = dict(zip((not isinstance(static,str) for static in mcls.statics[cls]), map(type,mcls.statics[cls])))[True].__name__
            raise TypeError('__statics__ items must be strings, not {0}'.format(typ))
        # Move any previously existing, not overridden statics to the static var parent class(es)
        if len(cls.__sro__) > 1:
            for attr,value in namespace.items():
                if attr not in StaticVarsMeta.statics[cls] and attr != ['__statics__']:
                    for c in cls.__sro__[1:]:
                        if attr in StaticVarsMeta.statics[c]:
                            setattr(c,attr,value)
                            delattr(cls,attr)
        return cls
    def __inst_getattribute__(self, orig_getattribute):
        '''Replaces the class __getattribute__'''
        @wraps(orig_getattribute)
        def wrapper(self, attr):
            if StaticVarsMeta.is_static(type(self),attr):
                return StaticVarsMeta.__getstatic__(type(self),attr)
            else:
                return orig_getattribute(self, attr)
        return wrapper
    def __inst_setattr__(self, orig_setattribute):
        '''Replaces the class __setattr__'''
        @wraps(orig_setattribute)
        def wrapper(self, attr, value):
            if StaticVarsMeta.is_static(type(self),attr):
                StaticVarsMeta.__setstatic__(type(self),attr, value)
            else:
                orig_setattribute(self, attr, value)
        return wrapper
    def __inst_delattr__(self, orig_delattribute):
        '''Replaces the class __delattr__'''
        @wraps(orig_delattribute)
        def wrapper(self, attr):
            if StaticVarsMeta.is_static(type(self),attr):
                StaticVarsMeta.__delstatic__(type(self),attr)
            else:
                orig_delattribute(self, attr)
        return wrapper
    def __getstatic__(cls,attr):
        '''Static variable getter'''
        for c in cls.__sro__:
            if attr in StaticVarsMeta.statics[c]:
                try:
                    return getattr(c,attr)
                except AttributeError:
                    pass
        raise AttributeError(cls.__name__ + " object has no attribute '{0}'".format(attr))
    def __setstatic__(cls,attr,value):
        '''Static variable setter'''
        for c in cls.__sro__:
            if attr in StaticVarsMeta.statics[c]:
                setattr(c,attr,value)
                break
    def __delstatic__(cls,attr):
        '''Static variable deleter'''
        for c in cls.__sro__:
            if attr in StaticVarsMeta.statics[c]:
                try:
                    delattr(c,attr)
                    break
                except AttributeError:
                    pass
        raise AttributeError(cls.__name__ + " object has no attribute '{0}'".format(attr))
    def __delattr__(cls,attr):
        '''Prevent __sro__ attribute from deletion'''
        if attr == '__sro__':
            raise AttributeError('readonly attribute')
        super().__delattr__(attr)
    def is_static(cls,attr):
        '''Returns True if an attribute is a static variable of any class in the __sro__'''
        if any(attr in StaticVarsMeta.statics[c] for c in cls.__sro__):
            return True
        return False

A: Your example with MyProperty is not working the way you show it.  I suspect a copy/paste error.

Here is a simpler solution using one Static descriptor and one StaticType metaclass:
from types import FunctionType

class Static:
    def __init__(self, value, doc=None):
        self.deleted = False
        self.value = value
        self.__doc__ = doc
    def __get__(self, inst, cls=None):
        if self.deleted:
            raise AttributeError('Attribute not set')
        return self.value
    def __set__(self, inst, value):
        self.deleted = False
        self.value = value
    def __delete__(self, inst):
        self.deleted = True

class StaticType(type):
    def __delattr__(cls, name):
        obj = cls.__dict__.get(name)
        if isinstance(obj, Static):
            obj.__delete__(name)
        else:
            super(StaticType, cls).__delattr__(name)
    def __getattribute__(cls, *args):
        obj = super(StaticType, cls).__getattribute__(*args)
        if isinstance(obj, Static):
            obj = obj.__get__(cls, cls.__class__)
        return obj
    def __setattr__(cls, name, val):
        # check if object already exists
        obj = cls.__dict__.get(name)
        if isinstance(obj, Static):
            obj.__set__(name, val)
        else:
            super(StaticType, cls).__setattr__(name, val)

and in use:
class MyStatic(metaclass=StaticType):
    """
    Testing static vars
    """
    a = Static(9)
    b = Static(12)
    c = 3

class YourStatic(MyStatic):
    d = Static('woo hoo')
    e = Static('doo wop')

and some tests:
ms1 = MyStatic()
ms2 = MyStatic()
ms3 = MyStatic()
assert ms1.a == ms2.a == ms3.a == MyStatic.a
assert ms1.b == ms2.b == ms3.b == MyStatic.b
assert ms1.c == ms2.c == ms3.c == MyStatic.c
ms1.a = 77
assert ms1.a == ms2.a == ms3.a == MyStatic.a
ms2.b = 99
assert ms1.b == ms2.b == ms3.b == MyStatic.b
MyStatic.a = 101
assert ms1.a == ms2.a == ms3.a == MyStatic.a
MyStatic.b = 139
assert ms1.b == ms2.b == ms3.b == MyStatic.b
del MyStatic.b
for inst in (ms1, ms2, ms3):
    try:
        getattr(inst, 'b')
    except AttributeError:
        pass
    else:
        print('AttributeError not raised on %r' % attr)
ms1.c = 13
ms2.c = 17
ms3.c = 19
assert ms1.c == 13
assert ms2.c == 17
assert ms3.c == 19
MyStatic.c = 43
assert ms1.c == 13
assert ms2.c == 17
assert ms3.c == 19

ys1 = YourStatic()
ys2 = YourStatic()
ys3 = YourStatic()
MyStatic.b = 'burgler'
assert ys1.a == ys2.a == ys3.a == YourStatic.a == MyStatic.a
assert ys1.b == ys2.b == ys3.b == YourStatic.b == MyStatic.b
assert ys1.d == ys2.d == ys3.d == YourStatic.d
assert ys1.e == ys2.e == ys3.e == YourStatic.e
ys1.a = 'blah'
assert ys1.a == ys2.a == ys3.a == YourStatic.a == MyStatic.a
ys2.b = 'kelp'
assert ys1.b == ys2.b == ys3.b == YourStatic.b == MyStatic.b
ys1.d = 'fee'
assert ys1.d == ys2.d == ys3.d == YourStatic.d
ys2.e = 'fie'
assert ys1.e == ys2.e == ys3.e == YourStatic.e
MyStatic.a = 'aargh'
assert ys1.a == ys2.a == ys3.a == YourStatic.a == MyStatic.a


text:
Q: Move down when tab key pressed I'm trying to move the focus to the next field/button but it doesn't seem to want to work. Here is what I currently have:
    @Override
public boolean dispatchKeyEvent(KeyEvent event) {
    if (event.getKeyCode() == KeyEvent.KEYCODE_TAB)
    {
        //move down here once I figure it out..
        mEmailvalue.getNextFocusDownId();
        return true;

       }
    return super.dispatchKeyEvent(event);
}

A: Try this:
public boolean dispatchKeyEvent(KeyEvent event) {
    if (event.getKeyCode() == KeyEvent.KEYCODE_TAB && event.getAction()==KeyEvent.ACTION_DOWN) {
        View currentFocus = getCurrentFocus();
        if (currentFocus!=null) {
            View next = currentFocus.focusSearch(View.FOCUS_DOWN);
            if (next!=null) {
                next.requestFocus();
            }
        }
        return true;
    }
    return super.dispatchKeyEvent(event);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: ANOVA versus nonlinear fit I have a data set which looks something like this (not real data):
conc   Resp
0      5
0.1    18
0.2    20
0.3    23
0.4    24
0.5    24.5
0      5
0.1    17
..     ..

which happens to fit perfectly to the Michaelis-Menten equation:

Resp = max_value  *  conc / (conc_value_at_half_max + conc)

Even though it is something else entirely importantly, the response increases quickly with "conc" and then reaches a ceiling or max value of sorts.
Anyway, I want to know how low I can go in "conc" before the value of "Resp" is not significantly lower than the max value.
Using a simple ANOVA accomplices this nicely, but I was thinking: "should I not be exploiting the fact that the structure of the data is so nicely explained by a known equation?" Is there such a way?
I am using minitab for this because it is easier, but would work in R all the time.

A: I think you should rethink the question.
Why would it possibly matter to find the highest concentration where the response is far enough below the maximum plateau to give a P value less than some arbitrary threshold?
If you added more concentrations, or collected replicate values, or obtained cleaner (smaller experimental error) data, then you'd reach a different conclusion about the largest concentration that gives a response "significantly" less than the plateau. So the answer to that question is partly determined by details of the experimental design that you can change. The answer tells you nothing fundamental about the system.
As with most questions in statistics, I urge you to set aside the word "significant" and try to articulate the question you want answered in scientific terms.

A: You could model it using nonlinear least squares regression, then use the modeled values and SE of the fit to determine the conc level that is "different" than the max. Once you fit the model, you could brute force search progressively lower thresholds until you reach a conc where Resp differs by a pre-specified alpha value from the max value and the estimated error around that.
So, fit a nls, then write a for loop to calculate the p values for, say, a t-test comparison, and search that for the critical conc value you're looking for.


text:
Q: Laravel: Access route in controller constructor In my laravel application I need to access the Route in every controller's __construct().
class SomeController extends Controller
{
    public function __construct(Route $route)
    {
        parent::__construct();

        /**
         * Middleware(s)
         */
        $this->middleware('auth');

        /**
         * Extracting current controller & action from the namespace
         */
        list($controller, $method) = @explode("@", $route->getActionName());

        /**
         * Assigning values to private variables
         */
        $this->controller = preg_replace('/.*\\\/', '', $controller);
        $this->action     = preg_replace('/.*\\\/', '', $method);
    }
}

If I run this code then it works without any error. However, when I run php artisan route:list it gives me Illuminate\Contracts\Container\BindingResolutionException  : Unresolvable dependency resolving [Parameter #0 [ <required> $methods ]] in class Illuminate\Routing\Route.
If I change my code as follows and run the same command then it shows the list of routes..
class SomeController extends Controller
{
    public function __construct()
    {
        parent::__construct();

        /**
         * Middleware(s)
         */
        $this->middleware('auth');

        /**
         * Extracting current controller & action from the namespace
         */
        // list($controller, $method) = @explode("@", $route->getActionName());

        /**
         * Assigning values to private variables
         */
        // $this->controller = preg_replace('/.*\\\/', '', $controller);
        // $this->action     = preg_replace('/.*\\\/', '', $method);
    }
}

I need the controller and action name on every render to show the active links.
How to fix this..?


text:
Q: Fourier transform in all but one axis I'm seeing this equality that I'm having a a bit of trouble reproducing. If we have a couple of Functions defined as
$$G(\vec x,y) = (-\nabla^2)^{-1}F(\vec x,y)$$
where the inverse Laplacian has the Fourier transform:
$$(-\nabla^2)^{-1} \rightarrow (\vec q^2 + k^2),$$
where $\vec q$ is the wavevector in the $\vec x$ subspace, and $k$ is the wavevector in the $y$ direction. I have to show that Fourier transforming in the $x$ subspace gives:
$$G(q,y) = \frac{1}{2|q|}\int_{-\infty}^\infty dy' e^{-|q| |y-y'|}F(q,y')$$
I have tried to either start with $-\nabla^2G(x,y) = F(x,y)$, and plug in the definition of the fourier transform, or to start with $G(q,y) = \int e^{i k y}G(q,k)$ and use the full Fourier transform definition, but I can't get the integral over the auxiliary variable $y'$. Any hints?
Thanks!

A: To avoid confusing notation, we let $g(q,y)$ to be the Fourier transform of $G(x,y)$ in the $x$ variables (with $y$ fixed), and similarly with $f$.
Taking Fourier transforms of $-\nabla^2G =F$ gives
$$
(|q|^2 - \partial_y^2) g(q,y)= f(q,y),\quad \text{or}\quad \partial_y^2 g(q,y)= |q|^2 g(q,y)- f(q,y),
$$
which is an ODE in $y$ for each fixed $q$. Note that the function $u(q,t)=A(q)e^{-|q||y|}$ solves the homogeneous equation and has good decay as $y\to\pm\infty$ (there's a hiccup at $y=0$ that will come into play in a bit*); now to solve the inhomogeneous problem we use the variation of parameters/Duhamel's formula:
\begin{equation}\tag{1}
v(q,t)= \int_{-\infty}^{\infty} A(q)e^{-|q||y-y'|}f(y')\, dy'.
\end{equation}
It's easy to check, by breaking up the integral into the $\int_{-\infty}^y$ and $\int_y^\infty$ parts,
\begin{equation}
\begin{split}
\partial_yv(q,y) &= \int_{-\infty}^{\infty} |q|A(q)e^{|q||y-y'|}f(q,y')\, dy',\\ \partial_y^2 v(q,y) &= -2|q| A(q)f(q,y) + \int_{-\infty}^\infty |q|^2A(q)e^{-|q||y-y'|}f(q,y')\, dy'.
\end{split}
\end{equation}
Therefore, the choice of $A(q)=\frac{1}{2|q|}$ gives
$$
\partial_y^2 v(q,y)= |q|^2 v(q,y) - f(q,y).
$$
By uniqueness for the ODE, we see $g(q,y)=v(q,y)$, and combined with $(1)$, is exactly the identity we want.
*: Perhaps the right way to phrase this is that the function $u$ is the fundamental solution of the operator $-\partial_y^2+|q|^2$, so we're not really solving the homogeneous equation, but rather the equation with a Dirac delta as the forcing term; then the "Duhamel formula" is simply the fact that the convolution satisfies $f*\delta_y = f(y)$.


text:
Q: JAVA - where to print out an integer, outside of while loop? import java.util.*;

public class Example {

    public static void main(String[] args) {

        Scanner beri = new Scanner(System.in);

        long vish = 16;
        long shir = 29;
        long n = 3;

        long del1 = 0;
        long del2 = 0;
        long stranica1 = 0;
        long stranica2 = 0;

        long ostanek1 = 0;
        long ostanek2 = 0;
        long ostala_shir = 0;
        long plosce_shir = 0;
        long ostala_vish = 0;
        long plosce_vish = 0;
        long ploscice = 0;
        long del_dva = 0;
        long del_n = 0;

        long i = n;

        while (i <= n) {

            del_dva = 2;
            del_n = i;
            stranica2 = (long)Math.pow(del_dva, del_n);

            if (vish % stranica2 == 0 && shir % stranica2 != 0) {

                ostanek2 = vish % stranica2;
                ostala_vish = vish - ostanek2;
                plosce_vish = ostala_vish / stranica2;

                ostanek1 = shir % stranica1;
                ostala_shir = shir - ostanek1;
                plosce_shir = ostala_shir / stranica2;
                shir = ostanek1;

                ploscice = plosce_shir*plosce_vish;

            }
            i--;

        }
    }
}

The variables are in my language, but that doesn't affect my question.
Don't mind the initialization part, the variables aren't in english.
My question is:  where in my program must I print out the result. I have already tried with for loop, but for example the first time the program goes through the loop, the result is 6, then the next time the result it 4, then the next time 0 and the next time 16 ..
It prints out in this form: (the initial numbers are vish= 16, shir = 29, n =3)

*

*6

*4

*0

*16

.. what I would like to achieve is that it prints out 26 .. which in fact is (6+4+0+16)
.. and also sometimes java reports Exception in thread main java.lang.ArithmeticException: /by zero

A: You print it out after all calculation to get the right result are done.
In your case you have calculation of stranica2 which can be null. You should check make a check
if (stranica !=0) { continue ;}
The problem with your solution is that there is no end for i. i starts equal to n and goes down, the check in the while loop is also for numbers smaller than n, which means that you are having an infinite loop.

A: Calculate the sum like sum += value; in the loop and when the loop ends print the sum
int sum = 0;
for(int i = 0; i < count; i++) {
// calculate value here

...

// now add the value in sum just before loop ends
sum += value
}

System.out.prinln("Total is " + sum);

and for java.lang.ArithmeticException ... This is because you are dividing some number by zero. In your example it is
if (vish % stranica2 == 0 && shir % stranica2 != 0) {

   ostanek2 = vish % stranica2;  // here ostanek2 = 0
   ostala_vish = vish - ostanek2;
   plosce_vish = ostala_vish / stranica2; // so here ostala_vish is divided by zero

   ostanek1 = shir % stranica1;
   ostala_shir = shir - ostanek1;
   plosce_shir = ostala_shir / stranica2;
   shir = ostanek1;

   ploscice = plosce_shir*plosce_vish;

 }

A: Corrected code:
import java.util.*;
public class Example {

    public static void main(String[] args) {
        // TODO code application logic here
        Scanner beri = new Scanner(System.in);

        long vish = 16;
        long shir = 29;
        long n = 3;

        long del1 = 0;
        long del2 = 0;
        long stranica1 = 0;
        long stranica2 = 0;

        long ostanek1 = 0;
        long ostanek2 = 0;
        long ostala_shir = 0;
        long plosce_shir = 0;
        long ostala_vish = 0;
        long plosce_vish = 0;
        long ploscice = 0;
        long del_dva = 0;
        long del_n = 0;

        long i = n;

        //declare and initialize the following variable named sum
        long sum = 0;

        //don't use i<=n since this is a decrementing loop. Use i >= 0 instead
        while (i >= 0) {

            del_dva = 2;
            del_n = i;
            stranica2 = (long) Math.pow(del_dva, del_n);

            if (vish % stranica2 == 0 && shir % stranica2 != 0) {

                ostanek2 = vish % stranica2;
                ostala_vish = vish - ostanek2;
                plosce_vish = ostala_vish / stranica2;

                ostanek1 = shir % stranica2; // you made a mistake here.
                //If you write stranica1, then stranica1 = 0,
                //and that's why you get the divide by zero exception
                ostala_shir = shir - ostanek1;
                plosce_shir = ostala_shir / stranica2;
                shir = ostanek1;

                ploscice = plosce_shir * plosce_vish;

            }

            //Do the following to get the sum of ploscice
            sum = sum + ploscice;
            i--;

        }
        //println should be outside the while loop. Same applies for for loop
        System.out.println("The sum is = " + sum);
    }

}

Although, I pretty much explained everything inside my code through inline comments, I'm going to go through the major problems in your code again.
Firstly:
Why did you use i < = n in while loop condition? You're decrementing the value of i, so this means it will become i = 3, then i = 2, then i = 1 , then i = 0, then i = -1 and so on, making it an infinite loop.
Use i >= 0 instead. Thus the loop will end at i = 0
Secondly:
Since you're decrementing the value of i, so when it becomes i = -1, then stravica2 value becomes 0. Hence, you get the divide by 0 exception because you're trying to get a modulus operation by dividing by stravica2 inside your if condition
Thirdly:
You want to get the sum of ploscice after the while loop ends. However, you didn't declare any variable to hold the sum of ploscice.
So you need to declare a long variable named sum, initialize it to 0 before the while loop, then get the sum each time inside the loop by sum = sum + ploscice. Then print the sum outside the while loop.
Should get you the result:
10

Because, the ploscice values after each iteration in the loop are:

*

*6

*4

*0

*0 (not 16)

Result is 10.
Last but not the least:
Why did you do this?
ostanek1 = shir % stranica1;

Isn't stranica1 equals 0? How come you'll get ostanek1 value? It will give you that divide by zero exception.
Fix it to this:
ostanek1 = shir % stranica2;


text:
Q: Error Code: 1815 Internal error: JSON wrapper: unexpected type in procedures This is the procedure that i have written it gives
 Error Code: 1815 Internal error: JSON wrapper: unexpected type
 when else case executes in this query
but it works fine when I change null into {}.
**SELECT CASE
WHEN (select count(*) from user_attendance a where a.user_id =userId order by a.user_attn_id desc )!=0 then (select a.bays from user_attendance a where a.user_id =userId order by a.user_attn_id desc limit 1) ELSE null END) );**

As well as it works when I run it alone as
**insert into user_attendance(user_id,bays,modified_at,modified_by) values(16,(SELECT CASE
  WHEN (select count(*)  from user_attendance a where a.user_id =1 order by a.user_attn_id desc )!=0 then  (select a.bays  from user_attendance a where user_id =1 order by a.user_attn_id desc limit 1)
  ELSE null
END),now(),16);**

I don't why its showing such type of behavior
DROP PROCEDURE `a`.`getTechnicianAttendance`;

DELIMITER $$

 CREATE PROCEDURE getTechnicianAttendance()
BEGIN
DECLARE users_count  INTEGER DEFAULT 0;
DECLARE finished INTEGER DEFAULT 0;

SELECT count(*) into users_count
FROM user_attendance
WHERE date = current_date();

IF users_count = 0 THEN

    Begin
    DECLARE userId INTEGER DEFAULT 0;
    DECLARE user_id_cursor CURSOR FOR
    select users.user_id from users left outer join user_roles on user_roles.user_id = users.user_id where user_roles.role_id = (select role_id from roles  where roles.role_name = 'Technician');

    DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;

    open  user_id_cursor;

    user_ids: LOOP
    FETCH user_id_cursor INTO userId;

    IF finished = 1 THEN
    LEAVE user_ids;
    END IF;

    insert into `autoscope`.`user_attendance` (user_id,
      date,
      bays
       )
    values (
      userId,
      current_date(),
           (SELECT CASE
   WHEN (select count(*)  from user_attendance a where a.user_id =userId order by a.user_attn_id desc )!=0 then   (select a.bays  from user_attendance a where a.user_id =userId order by a.user_attn_id desc limit 1)
   ELSE null
 END)
      );

     END LOOP user_ids;

    CLOSE user_id_cursor;
    End;
    END IF;

END $$


text: Q: MMT is an application layer in OSI model or in IP/TCP model? In all papers related to Mpeg media transport, it is written that it is an application layer transport protocols.I was wondering if it is an application layer protocol in OSI model or in IP/TCP model?


text: Q: How to update an excel file keeping the file open using java? Is there any possibility of having an excel file open and simultaneously when you run a java application to update the same excel file which is open and the changes need to be updated.I tried all the possible ways but I am not figuring out how to update data to an open excel file.


text:
Q: Multiple Line Label in AChartEngine based BarChart I'm writing an application for Android which contains Bar Charts, The Bar Chart is built by using the AChartEngine API. The X axis label is quite long and overlaps the other labels, I was wondering if it is possible to have a line break in the label or have a multiple line label. I tried going through the API documentation but i found no answers and Google proves to be no better.

A: I dont think you can break xlable directly but i tried to rotate the lables so that they fit the page
renderer.setXLabelsAngle(45f);

A: I was able to do a line break using getTimeChartView. By using \n in format parameter of getTimeChartView, but I am not sure how you can get the same with BarCharts.
mChartView = ChartFactory.getTimeChartView(this, dataset, mRenderer,"HH:mm \n dd-MM");

I am still looking for how to have multiple line labels.

A: I was able to get a multiline label with custom text label.
renderer.ShowCustomTextGrid = true;
renderer.AddXTextLabel (0, "first line \n  second line");


text:
Q: get first occurred only in an array i have an arrayX of three elements , and i'm using $.inArray() to search for this three element in another arrayY ... and returning the location for each X element in Y
X = [1,2,3] ;
y = [1,5,6,1,6,9,3,2] ;

But there is duplication in y, 1 occurred twice in y[0] and y[3]
The real example is here http://jsfiddle.net/minagabriel/kHG9K/
How do I get the first 1 occupancy and skip the others?
I'm pushing the location of 1,2,3 in an array with the first occurred of each one

A: This works fine without jQuery and $.inArray:
x = [1,2,3] ;
y = [1,5,6,1,6,9,3,2] ;

var z = {};

for (var i = 0; i < x.length; i++)
    for (var j = 0; j < y.length; j++)
        if (x[i] == y[j]) {
            z[x[i]] = j;
            break;
        }

console.log(z);

z is an object containing elements from x as keys and its' positions as values.
UPDATE. Applying this to your example, here is the working solution: http://jsfiddle.net/kHG9K/19/

A: var x = [1,2,3];
var firstOccurrences = [];
var y = [1,5,6,1,6,9,3,2];

for (var i = 0, len = x.length; i < len; i++) {
    firstOccurrences.push(y.indexOf(x[i]));
}

console.log(firstOccurrences);

Edit: as noted below, indexOf() isn't reliable in older versions of IE. Here's a more idiomatic jQuery approach:

var x = [1,2,3];
var y = [1,5,6,1,6,9,3,2];

var firstOccurrences = $.map(x, function(item) { return $.inArray(item, y); });

A: jsFiddle: http://jsfiddle.net/kHG9K/16/
var x = [1,2,3] ;
var y = [1,5,6,1,6,9,3,2] ;

function firstOccurence()
{
    for ( var a in x )
    {
       return $.inArray( x[a] , y );
    }
}

alert( firstOccurence() );

A: http://jsfiddle.net/kHG9K/18/
I just remove the item from the array once it has been found.
    if (start >= 0) {
        alert(y[i] + " " + "found it" + " " + " location" + z);
        y[i] = null;
    }

NOTE: That's not the right way to loop through an array. Use for(index;index<length;index++) to avoid quirks.

A: Fiddle link: click here
You have to use :
$.inArray( value, array [, fromIndex] )
In your case, to get the index of value 1 from y array, you can simply use:
$.inArray('1', y)
To check each value of x, if exists in y, and to save each index in an third array z:
var x = [1,2,3], y = [1,5,6,1,6,9,3,2], z = new Array(), i;
for(i = 0; i < x.length; i++) {
    var indexInY = $.inArray(x[i], y); // You get index -1 if the value is not found.
    z.push(indexInY);
    alert("Does x[" + i + "] with value = " + x[i] +
                          " exist in y array? " +
                          ((indexInY != -1) ? "Yes at position " + indexInY + "." : "No.")
                         );
}
alert("Indexes of x elements in y: [" + z + "]");

// Results:
// Does x[0] with value = 1 exist in y array? Yes at position 0.
// Does x[1] with value = 2 exist in y array? Yes at position 7.
// Does x[2] with value = 3 exist in y array? Yes at position 6.
//
// Indexes of x elements in y: [0,7,6]

Note that you will receive index -1 if the value you are looking wasn't found in the array.

Fiddle link: click here


text:
Q: SQL: select all rows if parameter is null, else only select matching rows I have a variable coming into a stored procedure. This variable can either have a value or be null.

*

*If the variable is null, I need to select all the rows in the table (some with NULL values, some with actual data).

*If the variable is not null, I only need to select the rows where the variable matches a column.

I created this conditional statement to help explain what I would like to achieve:
if

@status is null, select all the rows (rows with NULL for table.status, and rows with actual data for table.status)

else

select the rows where @status equals table.status

This is what I came up with (well one of them):
WHERE
   book.book_nme LIKE @search_input AND
   book.book_desc LIKE @search_input AND
   (book.author LIKE ISNULL(@author, book.author)) AND
   (bookStatus.status_desc LIKE ISNULL(@status, bookStatus.status_desc))

The only problem is that if bookStatus.status_desc is NULL, then it will not select that row (when @status is null)
I'm so confused, I tried looking up Coalesce too which seemed to prioritize the values, but ... I don't know what to do.
Should I just create a huge CASE in the stored procedure and have two select statements?

A: WHERE  book.book_nme LIKE @search_input AND
book.book_desc LIKE @search_input AND
(@author IS NULL OR book.author LIKE @author) AND
(@status IS NULL OR bookStatus.status_desc LIKE @status) ...

Update
Added both conditions, for @author and @status

A: If you think it about your description it breaks down as:

*

*Return all rows when @status is null

*Otherwise return rows that match @status.

You can express the last line of your sql to match this like this:
(@status is null OR bookStatus.status_desc LIKE @status)

A: I always use this:
WHERE fieldname = ISNULL(@parameter, fieldname)
Hope this helps
Roger

A: where(field1 like isnull(@parameter,field1))
If the paramater is null will retrieve all data from field1
like
select field from table1
This works on sybase.


text:
Q: SDL_GetWindowSurface with SDL_CreateRenderer Im programming a game with SDL2 in C++.
I want to use SDL_GetWindowSurface and SDL_CreateRenderer in this game, if I use only one of them, its works, but if I try to use both of them, the game crashes.
I think that this two functions don´t work if both are active.
Can this be the problem?

A:
I think that this two functions don´t work if both are active.
Can this be the problem?

Yup, exactly as the SDL_GetWindowSurface() declaration comment indicates:
/**
 *  \brief Get the SDL surface associated with the window.
 *
 *  \return The window's framebuffer surface, or NULL on error.
 *
 *  A new surface will be created with the optimal format for the window,
 *  if necessary. This surface will be freed when the window is destroyed.
 *
 *  \note You may not combine this with 3D or the rendering API on this window.
 *
 *  \sa SDL_UpdateWindowSurface()
 *  \sa SDL_UpdateWindowSurfaceRects()
 */
extern DECLSPEC SDL_Surface * SDLCALL SDL_GetWindowSurface(SDL_Window * window);

Quoting for emphasis:

You may not combine this with 3D or the rendering API on this window.

A: surface = SDL_GetWindowSurface(window);
renderer = SDL_CreateSoftwareRenderer(surface);
if (!renderer) {
    SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Render creation for surface fail : %s\n",SDL_GetError());
    return 1;
}


text:
Q: Semi-direct product group proof.
Suppose $\alpha \colon A \to  \operatorname{Aut}(N)$ is a homomorphism and $A_0 \leq A$ is a subgroup.  Prove that $N \rtimes_\alpha A_0$ is a subgroup of $N \rtimes_\alpha A$.  Note that this makes sense because $N \times A_0$ is naturally a subset of $N \times A$.

I'm really having a hard time exactly understanding this problem. Any advice would be helpful. My definition/visualization of a semidirect product group is shaky I think so any help there would be awesome too. Thanks!

A: We need to show that if $(n_1,a_1)$ and $(n_2,a_2)$ are in $N \times A_0$, then
$$
(n_1,a_1) *_\alpha (n_2,a_2) \in N \times A_0
$$
By definition of the multiplication $*_\alpha$ on $N \rtimes_\alpha A$, we have
$$
(n_1,a_1) *_\alpha (n_2,a_2) = (n_1 \alpha(a_1)(n_2),a_1a_2)
$$
The first element is definitely in $N$.  The second element is in $A_0$ since $A_0$ is a subgroup of $A$.
We also need to show that for every $(n,a)$ in $N\times A_0$, the $*_\alpha$-inverse of $(n,a)$ is in $N\times A_0$.  Let the $*_\alpha$-inverse be called $(n',a')$.  By the definition of $*_\alpha$-multiplication it is clear that $a' = a^{-1}$.  This in in $A_0$ because, again, $A_0$ is a subgroup.
We then need to find $n'$ such that
$$
    n \alpha(a^{-1})(n') = e
$$
Solving,
$$\begin{aligned}
    \alpha(a^{-1})(n') &= n^{-1} \\
\iff \alpha(a)\left(\alpha(a^{-1})(n')\right) &= \alpha(a)\left(n^{-1}\right)\\
\end{aligned}$$
Now $\alpha$ is a homomorphism, so $\alpha(a)\mathbin{\circ}\alpha(b) = \alpha(ab)$.  In particular,
$$
    \alpha(a)\mathbin{\circ}\alpha(a^{-1}) = \alpha(aa^{-1}) = \alpha(e) = \text{identity function on $N$}
$$
Therefore,
$
    n' =  \alpha(a)\left(n^{-1}\right)
$ and
$$
    (n,a)^{*_\alpha-1} = (\alpha(a)\left(n^{-1}\right),a^{-1}) \in N \times A_0
$$


text:
Q: change url #firstPage with htaccess I use the fullpage plugin (from https://alvarotrigo.com/fullPage/ ) in wordpress but I want to delete #firstPage in the url but use the buttons so I can't use the noAnchor (https://alvarotrigo.com/fullPage/examples/noAnchor.html). can I rewrite the URL with htaccess? something like this
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php/#firstPage$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

http://www.example.com/#firstPage/1

A: If you don't want anchors in the URL, don't use anchors in the fullPage.js initialisation.
Then bind the moveTo method to your menu elements.


text:
Q: POSIXct formatting in R? I'm trying to convert characters into a POSIXct format using lubridate's parse date_time function.
This is my code:
df$TimeClosed <- parse_date_time(df$TimeClosed, 'mdy HMSp')

Most of my variables are in this format : 09/12/2017 11:08:51 AM
but there are some that are like this : 7/6/19 15:37
and because of that, they are failing to parse.
Any suggestions on how I can fix this so all date/times are in POSIX and in the same format?
Thanks,

A: parse_date_time can take a vector of formats and will try them one by one in order until one matches.
library (lubridate)

x <- c("09/12/2017 11:08:51 AM", "7/6/19 15:37")
parse_date_time(x, c("dmYHMSp", "dmyHM"))
## [1] "2017-12-09 11:08:51 UTC" "2019-06-07 15:37:00 UTC"


text:
Q: Consider $H=\Bbb{Z}_{30}$ and $G=\Bbb{Z}_{15}$ as additive abelian groups. Show that ${\rm Aut}(H) \cong {\rm Aut}(G)$. Consider $H = \mathbb{Z}_{30}$ and $G = \mathbb{Z}_{15}$ as additive abelian groups. Then how do I show that ${\rm Aut}(H) \cong {\rm Aut}(G)$?
By the Chinese remainder theorem, I know that $\mathbb{Z}_{30} \cong \mathbb{Z}_{2} \times \mathbb{Z}_{15}$. Intuitively I know that the only automorphism of $\mathbb{Z}_{2}$ is the identity automorphism, so we can construct a bijective map between $\psi : {\rm Aut}(G) \rightarrow {\rm Aut}(H)$. By $\psi(\phi) = \phi^{*}$, where $\phi^{*}((a,b)) = (a, \phi(b))$, which is an isomorphism. (Here we consider  $\mathbb{Z}_{30} \cong \mathbb{Z}_{2} \times \mathbb{Z}_{15}$.)
Is the definition of this map sufficient to claim that ${\rm Aut}(G) \cong {\rm Aut}(H)$? Also, how does one in general find the automorphism group of $\bigoplus_{k=1}^{r} \mathbb{Z}_{n_{k}}$, where the $n_{k}$'s are not necessarily coprime.

A: Hint: $${\rm Aut}(\Bbb Z_n)\cong U(n),$$
where $U(n)$ is the group of units modulo $n$.

A: For your first question, we have $\Bbb Z_{30}^×\cong(\Bbb Z_2\times\Bbb Z_{15})^×\cong\Bbb Z_2^×\times\Bbb Z_{15}^×\cong\Bbb Z_{15}^×$.
And $\operatorname {Aut}(\Bbb Z_n)\cong\Bbb Z_n^×$.


text:
Q: Laravel Nested Query i'm having hard time getting the right query for this in laravel.
I have table Exams.
id | exam_name
---|------------
1  | First Exam
2  | Second Exam
3  | Third Exam

And Students score table
id  | exam_id | score
----|---------|-------
1   | 1       | 15
2   | 1       | 12
3   | 1       | 10
4   | 2       | 7
5   | 2       | 16
6   | 2       | 13

And i want to get the average scores for all exams that looks like
exam_name   | average_score
------------|--------------
First Exam  | 12.33
Second Exam | 12
Third Exam  | 0 or NULL

I have tried left join but it returns multiple rows per exam.
I can also think of using nested Query but don't know how it works in Laravel.

A: DB::table('exams')
   ->leftJoin('student_score','exam_id','=','exams.id')
   ->select('exam_name', DB::raw('AVG(score) as average_score'))
   ->groupBy('exam_name')->get();

You can get the AVG score by using above query.
Hope this helps.

A: Do the left join with Students table :
select e.exam_name, avg(s.score) avg_score
from Exams e
left join Students  s on s.exam_id = e.id
group by e.exam_name;

You can also use subquery with correlation approach
select *,
       (select avg(s.score) from Students where e.exam_id = id) avg_score
from Exams e;

A: You don't need to join tables at all. You can solve this with plain laravel.
// in your controller
$exams = Exam::with('students')->get();

// in your view you should replace this with blade
foreach ($exams as $exam) {
    $exam->students->avg('score'); // Average score for each exam
}

Your exam model should have:
public function students()
{
    return $this->hasMany(student::class);
}

and your students class must have the inverse relation:
public function exam() {
    return $this->belongsTo(exam::class);
}


text:
Q: How can I improve the write performance of Apache Drill I'm using CTAS statement to create a parquet file from a csv in Apache Drill.
I've tried multiple experiments changing various configuration parameters, even trying to write to tmpfs.
My tests always take the same amount of time. I'm not IO bound. I may be CPU bound, consistently one java thread is at 100% most of the time.
Experiments tried:
store.parquet.compression=none
store.parquet.page-size=8192
planner.slice_target=10000
store.parquet.block-size=104857600
store.text.estimated_row_size_bytes=4k

I've reached the conclusion that perhaps Drill is single threaded for writing, can anybody confirm this?
With a 12 core server I have plenty of headroom available that is not being utilised.
Is it possible to run multiple drillbits on a single server?
Update:
It appears that the performance is the same whether the CTAS output format is csv or parquet, so the limitation appears to the ability Drill to write data in general.
Update 2:
Switching from using a csv file as input to the CTAS statement without a header, using a statement of the form:
CREATE TABLE  (col1, col2, col3, ...) AS SELECT columns[0], columns[1], column[2] from filename;
to using a CSV file with header, ie changing the statement to something like:
CREATE TABLE  (name1, name2, name3, ...) AS SELECT name1, name2, name3 from filename;
Where name1, name2 etc are defined in the header line made a significant difference in performance, from a consistent 13 minutes to execute overall process to 9 minutes.

A: You cannot run multiple drillibits on a single server.
Yes, In my observation also drill uses lots of Process power many times the CPU usage goes to 300-400% when we're computing on large set of data & i think it uses single thread for parquet file.


text:
Q: Hide specific payment method based on total weight in Woocommerce In woocommerce I would like to hide a "Cash on delivery" payment method for a specific total weight.
For example if cart total weight is up to 15 kilos, "Cash on delivery" payment method on checkout.
Any help is appreciated.

A: The following simple code will hide "COD" payment method if cart total weight is up to 15 Kg.
I assume that the weight unit set in Woocommerce is Kg (kilos).
The code:
add_filter( 'woocommerce_available_payment_gateways', 'hide_payment_gateways_based_on_weight', 11, 1 );
function hide_payment_gateways_based_on_weight( $available_gateways ) {
    if ( is_admin() ) return $available_gateways; // Only on frontend

    $total_weight = WC()->cart->get_cart_contents_weight();

    if( $total_weight >= 15 && isset($available_gateways['cod']) )
        unset($available_gateways['cod']); // unset 'cod'

    return $available_gateways;
}

Code goes in functions.php file of your active child theme (or active theme). Tested and work.


text:
Q: How to avoid corrupted downloads via Android DownloadManager? Here's the code i'm using:
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setTitle("Download: " + name);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
request.setDestinationInExternalPublicDir(DIRECTORY_DOWNLOADS, name);
request.setMimeType("application/octet-stream");
return dl_manager.enqueue(request);

I run this code in an android emulator via Android Studio, have it download a file over 50mb, then use the AS Device File Explorer to download the file and compare it to what i have local. Result: Various bytes are different in the downloaded version.
Why would this happen?

A: As of now, it appears that the emulator is at fault. Running the app on a physical phone hasn't resulted in any corrupted downloads at all.


text:
Q: tensorflow TypeError: cannot unpack non-iterable float object I am using tensorflow V2.2 and run into TyepError when I do model.evaluate. Can someone advise what the issues may be? A screenshot of the execution and error message is shown below.

A: Actually, if you don't have metric='accuracy' in the model.compile, don't try to extract it in model.evaluate.
So, you can change:

loss, acc= model.evaluate(df, df_y, verbose=0)

to

loss = model.evaluate(df, df_y, verbose=0)

A: you need to define a metric when you compile the model model.compile('adam', 'binary_crossentropy', metrics='accuracy')
in this way during evaluation, loss and accuracy are returned


text:
Q: select2 not working inside bootstrap tab I'm using bootstrap tab,I have two tabs(tab1,tab2), both tab contains a select2 dropdown. The first one works fine but the select2 dropdown in tab2 is not working.Here is my code.
HTML

Tab1

Tab2

    <input type="hidden" id="test1"/>

    <input type="hidden" id="test2"/>

JS
myapp.controller('myctrl',function(){
    var test1 =$('#test1');
    $(test1).select2({
       data:[{'id':1,'text':'None'},{'id':2,'text':'High'},{'id':3,'text':'Medium'},{'id':4,'text':'Low'}],
    multiple: false,
    });

 var test2 =$('#test2');
 $(test2).select2({
 data:[{'id':1,'text':'None'},{'id':2,'text':'High'},{'id':3,'text':'Medium'},{'id':4,'text':'Low'}],
  multiple: false,
 });
})

please help me.

A: you shouldn't combine jquery and angularjs in this way.
Check out Bootstrap UI directives: http://angular-ui.github.io/bootstrap/#/tabs


text:
Q: How can we know if a pair of particles are entangled? I'm struggling to find any information on how to check if a pair of particles are entangled.
I've found lots of information on how to entangle particles, but I'm wondering how to check entanglement on any given pair of particles, since any measurement of the quantum system will collapse the system to the state which was the result of the measurement.
The only way I can think of is measuring one particle and then by the definition/concept of entanglement you will know the result of a measurement of the other particle if they are entangled. Is this the only way to know if a pair of particles are entangled?
Any help is appreciated!
Thanks!

A:
any measurement of the quantum system will collapse the system to the state which was the result of the measurement

This is correct, but irrelevant. It is possible to make entangled measurements (like, say, Bell state measurements) where all of the basis states are entangled, and the wavefunction collapse will send the system to an entangled state (and, just as importantly, tell you which entangled state you have).
More generally, what you're looking for is something called an entanglement witness: these are observables which, when measured can unambiguously certify that the states produced by a given preparation procedure are entangled.
That said, it's important to note that your conception of entanglement,

measuring one particle and then by the definition/concept of entanglement you will know the result of a measurement of the other particle

is blurry and ultimately inaccurate. Entanglement refers to a broad class of bipartite states that show correlations between measurement outcomes on the two systems (and which, moreover, can produce results for certain metrics of correlation that are impossible for classical systems), but the naive "if A is spin up then B is spin down" is too restrictive and fails to meaningfully demarcate the line between entanglement and classical correlations.


text:
Q: logo hyperlink doesn't work I want to have a logo inside of my website with a hyperlink linked to youtube inside of it I did this for more website's I build earlier but somehow this doesn't work in this website maybe it has something to do with layers?
Note: I'll just send my whole website, it isn't too big and I don't mind copying because I'm a student and do this to educate :)
HTML code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<link rel="stylesheet" href="css/style.css" type="text/css"/>
<title>Test Website</title>
<meta name="" content="">

Test Website

slideshow

naturepictures

homepage

homepage

contact

slideshow

naturepictures

homepage

homepage

contact

slideshow

naturepictures

homepage

homepage

contact

Contentpage

            Picture slideshow

Pictures

CSS code:
*{
    margin: 0 auto 0 auto;
    text-align: left;
    color: #ffffff;
}

body{
    margin: 0;
    text-align: left;
    font-size: 13px;
    font-family: arial, helvetica, sens-serif;
    color: #ffffff;
    width: 1200px;
    height: auto;
    background: #fdf7e3;
}

header {
    position: fixed;
    width: 100%;
    top: 0;
    background: rgba(0,0,0,0.8);
    z-index: 10;
}

h1{
    color: black;
    text-align: center;
}

.hide
{
    position: fixed;
    width: 100%;
    top: 0;
    background: rgba(255,255,255,1);
    z-index:5;
    height: 123px;
}
.headertext{
    margin-top: 15px;
    text-align: center;
    color: white;
}

#title{
    font-size: 20px;
    margin: -10px 0 30px 0;
    width: 100%;
    height: 70px;
    border-top: 2px solid #000000;
    border-bottom: 2px solid #000000;
}

#menubar{
    margin-top: 10px;
    float: left;
    clear: both;
    width: 100%;
    height: 20px;
    list-style: none;
    border-bottom: 2px solid #010000;
}

#menubar ul{
    list-style: none;
    margin-top: -20px;
    text-align: center;
}

#menubar ul li{
    list-style: none;
    display: inline;
    padding-right: 80px;
}

#menubar ul li a{
    color: #ffffff;
    text-decoration: none;
    font-size: 20px;
    font-weight: bold;
}

#menubar ul li a:hover{
    border-bottom: 2px solid #ffffff;
}

#container{
    width: 1200px;
    height: 1400px;
}

#rightmenu{
    position: fixed;
    margin-top: 23px;
    margin-left: 1280px;
    padding-top: 20px;
    float: left;
    width: 160px;
    height: 530px;
    list-style: none;
    background: rgba(0,0,0,0.8);
    color: #ffffff;
    border-bottom-left-radius: 10px;
    border-bottom-right-radius: 10px;
}

#rightmenu ul li{
    display: block;
    padding-bottom: 50px;
}

#rightmenu ul li a{
    font-weight: bold;
    text-decoration: none;
    color: #ffffff;
    font-size: 15px;
    text-align: center;
    margin-left: -15px;
}

#rightmenu ul li a:hover{
    border-bottom: 2px solid #ffffff;
    transition: opacity .5s ease-in;
    opacity: 1;
}

#righttriangle1 {
   width: 0;
   height: 0;
   border-right: 25px solid rgba(0,0,0,0.8);
   border-top: 34px solid transparent;
   border-bottom: 34px solid transparent;
   margin-top: -410px;
   margin-right: 160px;
}

#righttriangle2 {
    width: 0;
    height: 0;
    border-right: 25px solid rgba(0,0,0,0.8);
    border-top: 34px solid transparent;
    border-bottom: 34px solid transparent;
    margin-right: 160px;
}

#righttriangle3 {
   width: 0;
   height: 0;
   border-right: 25px solid rgba(0,0,0,0.8);
   border-top: 34px solid transparent;
   border-bottom: 34px solid transparent;
   margin-right: 160px;
}

#righttriangle4 {
   width: 0;
   height: 0;
   border-right: 25px solid rgba(0,0,0,0.8);
   border-top: 34px solid transparent;
   border-bottom: 34px solid transparent;
   margin-right: 160px;
}

#righttriangle5 {
   width: 0;
   height: 0;
   border-right: 25px solid rgba(0,0,0,0.8);
   border-top: 34px solid transparent;
   border-bottom: 34px solid transparent;
   margin-right: 160px;
}

#youtubelogo{

}

#leftmenu{
    position: fixed;
    margin-top: 23px;
    margin-left: 50px;
    padding-top: 20px;
    float: left;
    width: 160px;
    height: 450px;
    list-style: none;
    background: rgba(0,0,0,0.8);
    color: #ffffff;
    border-left: 2px solid #010000;
    border-right: 2px solid #010000;
}

#leftmenu ul li{
    display: block;
    padding-bottom: 50px;
}

#leftmenu ul li a{
    font-weight: bold;
    text-decoration: none;
    color: #ffffff;
    font-size: 15px;
    margin-left: -15px;
}

#leftmenu ul li a:hover{
    border-bottom: 2px solid #ffffff;
    transition: opacity .5s ease-in;
    opacity: 1;
}

#lefttriangle{
    margin-top: 112px;
    margin-left: -1px;
    width: 0px;
    height: 0;
    border-top: 80px solid rgba(0,0,0,0.8);
    border-left: 82px solid transparent;
    border-right: 82px solid transparent;
}

#content{
    margin-top: 100px;
    margin-left: 100px;
    width: 1000px;
    padding-top: 50px;
    padding-left: 160px;
    color: #000000;
    font-weight: bold;
    text-align: center;
    font-size: 15px;
    margin-left: 80px;
}

#naturepictures{
    color: black;
    top: 1200px;
    width: 80px;
    height: 300px;
    text-align: center;
    margin-left: 440px;
}

.naturepicture{
    height: 400px;
    width: 600px;
}

.slider{
    margin-top: 20px;
    width: 600px;
    height: 400px;
    overflow: hidden;
    margin: auto;
    border-radius: 10px;
    vertical-align: middle;
}

.shadow{
    background-image:url(../images/shadow.png);
    background-repeat: no-repeat;
    background-position: top;
    width: 850px;
    height: 144px;
    vertical-align: middle;
    margin-top: -50px;
}

.slider img{
    width: 600px;
    height: 400px;
    display: none;
}

Thanks in advance and I hope you can get a solution fast! (It will probably be something stupidly easy :p)

A: You can't make a
 element the direct child of a
 element. You'll need to wrap the
 inside of a
 element first.
Try this instead

slideshow

naturepictures

homepage

homepage

contact

A: Can you uopload a screenshot?
Safari, Firefox, Chrome and IE approves your code.

Here's a Screenshot.

A: It is working fine after updating.If you logo related problem then copy and paste the below code instead the previous code!

check your image format from the images folder like .gif,.png etc


text:
Q: .htaccess rewrite rule to redirect all pages from one domain to another EXCEPT for one specific URL? I've looked through at least 50 different questions and posts on here on this topic, and tried everything and anything and still can't figure out how to do this.
I need to redirect all pages/URLs from domain1.com to domain2.com EXCEPT FOR a specific URL like domain1.com/paypal/ipn (to prevent Paypal IPN notifications from being broken... long story).
How do I pull that off/write that in terms of RewriteRules and RewriteConds...?
I've literally tried everything and I can easily get the domain1.com to domain2.com redirect:
    RewriteCond %{HTTP_HOST} ^(www\.)?domain1\.com$ [NC]
    RewriteRule (.*) https://www.domain2.com%{REQUEST_URI} [R=301,L]

But that other requirement, to ignore and skip a specific URL from ever being redirected in any way, nothing works so far...
Anyone?

A: To exclude a specific page from the redirection you could use the following :
RewriteCond %{REQUEST_URI} !/paypal/ipn [NC]
RewriteCond %{HTTP_HOST} ^(www\.)?domain1\.com$ [NC]
RewriteRule (.*) https://www.domain2.com%{REQUEST_URI} [R=301,L]

If there are multiple pages or URIs to exclude, you can either use RewriteCond with OR flag or use a regex based pattern in the rule
Multiple conditions :
RewriteCond %{REQUEST_URI} !/paypal/ipn [NC,OR]
RewriteCond %{REQUEST_URI} !/foo/bar [NC]
RewriteCond %{HTTP_HOST} ^(www\.)?domain1\.com$ [NC]
RewriteRule (.*) https://www.domain2.com%{REQUEST_URI} [R=301,L]

Regex based pattern :
RewriteCond %{HTTP_HOST} ^(www\.)?domain1\.com$ [NC]
RewriteRule !(page1|page2) https://www.domain2.com%{REQUEST_URI} [R=301,L]

Make sure to clear your browser cache before testing this new 301 reditect.


text:
Q: Upload a txt file to jenkins build job as build parameter Need some help to know about uploading a test case file to Jenkins Build job as build parameter is it possible?
I am aware of following options

*

*Parametric build where we can specify the source code path at run time

*Copy files into the job's workspace before building

but both the options we have to give the path i am looking at option where we can upload files to Jenkins build job (similar to attaching files to email).
Is it possible?

A: If looking for an interactive solution:

*

*Have a set of check-boxes as parameters, each representing a different test-case

*Let the developer check the required tests when running the build

If you plan to run this as an unattended job:

*

*Let the developer edit a parameters-file in a known location
and specify the required tests in this parameters-file

*The build-job will read this parameters-file when it runs,
and will act up-on it

A: Config File Provider Plugin for Jenkins "Adds the ability to provide configuration files (i.e., settings.xml for maven, XML, groovy, custom files, etc.) loaded through the Jenkins UI which will be copied to the job's workspace."
https://wiki.jenkins.io/display/JENKINS/Config+File+Provider+Plugin
In the Jenkins Build Environment section check option Provide Configuration files.
Then you can "Make globally configured files available in your local workspace. All files configured via the config-file-provider plugin are available and can be referenced."

A: AFAIK, there is no plugin for such a capability. I suggest you stick to your original idea of using the file parameter or write your own plugin.


text:
Q: Template loading first before constructor in Ionic 2 App I am working on an ionic 2 app. I'm trying to invoke a service in my component and try to access it in the template. But the issue I'm facing is that the template is loading first and then the promise output in my component is succeeding. So I get undefined error from the template if I try to access any 'req_obj' values. How do I make sure that the promise gets resolved first and then my template waits to get the output?
My service:
loadTruckdetail(id)
{
if (this.truckListdetail) {
  return Promise.resolve(this.truckListdetail);
}

return new Promise(resolve => {
  this.http.get('http://demo.truckjee.com/api/trucks/' + id + '?api_token='+this.userToken)
    .map(res => {
      return res.json().truck;
    })
    .subscribe(truck => {
      this.truckListdetail = truck;
      resolve(this.truckListdetail);
      console.log(this.truckListdetail);
      console.log(this.truckListdetail.id);
    });
});
}

My component:
import { Component, OnInit, Injectable } from '@angular/core';
import { ionicBootstrap, Platform, Nav } from 'ionic-angular';
import { FormBuilder, FormGroup } from '@angular/forms';
import { NavController, NavParams, LoadingController  } from 'ionic-angular';
import {Dashboardparam} from '../../providers/user-data/user-data';
import {Api} from '../../providers/api/api';
import {Authentication} from '../../providers/authentication/authentication';
import { HomePage } from '../home/home';

@Component({
  templateUrl: 'build/pages/requirement-show/requirement-show.html',
  providers: [Api]
})
@Injectable()
export class RequirementShowPage {
  myForm: FormGroup;
  req_obj: any;
  my_trucks: any;
  bids: any;
  cargo_details: any;
  payment_details: any;
  is_valid: number;

constructor(private builder: FormBuilder, private Auth: Authentication, public nav: NavController, private api: Api, navParams: NavParams, public loadingCtrl: LoadingController) {
  api.loadDetail(navParams.get('id'))
  .then( requirementValue => {
    this.req_obj = requirementValue;
console.log(req_obj);
  });
}
}

JSON response from the api:
{"message":"success","requirement":{"id":42,"status":0,"no_of_trucks":1,"user_id":11,"source":"Vadakkencherry, Kerala 678683, India","source_locality":"Vadakkencherry","source_district":"Palakkad","source_state":"Kerala","destination":"Chennai, Tamil Nadu, India","destination_locality":"Chennai","destination_district":"Chennai","destination_state":"Tamil Nadu","date_required":"Sep 26, 2016","date_delivery":"Sep 26, 2016","transit_time":1,"cargo_details":{},"payment_details":{},"valid_till":"2016-09-26 22:28:59","created_at":"2016-09-26 16:28:59","updated_at":"2016-09-26 16:28:59","expected_cost":"22500","created_by":11,"truck_types":[{"id":45,"requirement_id":42,"model_id":36,"created_at":"2016-09-26 16:28:59","updated_at":"2016-09-26 16:28:59"}],"bids":[]},"trucks":[{"id":6,"truck_id":"TR106","truck_number":"TN-52-J-9330","owner_id":7,"model_id":36,"description_id":269,"status":"0","short_form":"TN52 J9330","imei":"0358511020724179","current_locality":"Panniyankara","current_district":"Palakkad","current_state":"Kerala","current_lat":"10.5895666666666","current_long":"76.4524366666666","gps_updated_location":"NH544, Panniyankara, Kerala 678686, India","gps_last_updated":"2016-09-26 21:10:29","gps_updated_speed":"0","rc":"","insurance":"","pollution":"","np":"","authorization":"","created_at":"2016-06-03 18:34:03","created_by":1}]}

A: You can use *ngIf directive to "protect" your template, for example:
<div *ngIf="req_obj">
    {{req_obj.message}}
</div>

This way, div will be displayed only after value is assigned to req_obj. While it's value is undefined, there will be a comment inside your template, something like this:
<!--
    template bindings={ "ng-reflect-ng-if": null }
-->


text:
Q: Laravel - Check if username already exists before submitting form with jQuery AJAX I've made a registration form with a lot of fields. Since when I submit data and the validator redirects back with errors some inputs are empty and the user has to lose time refilling them, I want to implement some front-end validations.
I'm stuck on checking if an username is already used on submit button press becasuse I'm not expert about AJAX.
In the AuthController I've created a function that returns a Json containing a response in relation of existence or not of the username in the database.
class UserAuthController extends Controller
{
    public function isUserNameInUse( $username )
    {
        if (Auth::where('username', $username) != null){
            return [ 'is_used' => 1 ];
        }

            return [ 'is_used' => 0 ];
    }
}

In the routes.php there are these lines:
Route::group([ 'as' => 'api', 'prefix' => 'api', 'namespace' => 'Api'], function () {

     Route::group([ 'as' => 'auth', 'prefix' => 'auth'], function () {
          Route::any('/is_username_in_use/{username}', [
            'as' => 'isUserNameInUse',
            'uses' => 'UserAuthController@isUserNameInUse']);

    });

});

The view is like that (only a piece of the form):
<form action="{{ route('web.company.postSignup') }}" method="post" id="signup-form" class="form-horizontal">
            {!! csrf_field() !!}
            @include( 'errors.handler' )

                            <label for="username">
                                {{ _('Username*') }} </label>
                            <input type="text" class="form-control" name="username" id="username"
                                   value="{{ Input::old('username') }}" required>

                            <label for="password">
                                {{ _('Password*') }}
                            </label>

                            <input type="password" class="form-control" name="password" id="password"
                                   value="{{ Input::old('password') }}" onchange="form.confirmPassword.pattern = this.value;"
                                   required>

                            <label for="confirmPassword">
                                {{ _('Confirm Password*') }}
                            </label>

                            <input type="password" class="form-control" name="confirmPassword" id="confirmPassword" required>
                            <button class="btn btn-warning" id="submit-btn" type="submit">{{ _('Sign Up') }}</button>

</form>

This is the script, for now I've only tried to log the response of the controller, but it prints anything.
$(document).ready(function () {
    $('form#signup-form').submit(function () {
         var input_username = $('input[name=username]').val();
         console.log(input_username);

        $.getJSON('/api/auth/is_username_in_use/' + input_username, function (json) {

            console.log(json);

            });
            return false;
        });

    });

A: There is no need to make an explicit check if user name is in use. You may skip this part and instead, when you storing your user's data validate them accordingly.
An example of this might be
public function store(Request $request)
{
    $this->validate($request, [
        'username' => 'required|unique:users',
        'password' => 'required|confirmed'
    ]);

    // process your logic
}

This way, if validation failed, you'll get a json response object containing error messages.

Note, this will work if you're on Laravel 5. If you are on 4.* refer to documentation for validation part.

A: You should change return [ 'is_used' => 0 ]; into return Response::json([ 'is_used' => 0 ]); and add use Response; to the top of your controller.


text:
Q: An array and list of list properties I have an array of the objects. Every single object has another list. How to get the whole list of properties from the list? So as you can see there is a StatioItem array. Each stationItem owns a list of sensorItem objects. I want to get a list of id properties. How to do it?

[StationItem {
    id = 114;
    stationId = 114;
    cityName = Wrocław;
    addressStreet = ul. Bartnicza;
    sensors = List<SensorItem> <0x6000001bb840> (
        [0] SensorItem {
            id = 642;
            stationId = 642;
            param = ParamItem {
                paramName = dwutlenek azotu;
                paramFormula = NO2;
                paramCode = NO2;
                idParam = 6;
            };
        },
        [1] SensorItem {
            id = 644;
            stationId = 644;
            param = ParamItem {
                paramName = ozon;
                paramFormula = O3;
                paramCode = O3;
                idParam = 5;
            };
        }
    );
}, StationItem {
    id = 70;
    stationId = 70;
    cityName = Oława;
    addressStreet = ul. Żołnierzy AK 9;
    sensors = List<SensorItem> <0x6000001b7840> (
        [0] SensorItem {
            id = 397;
            stationId = 397;
            param = ParamItem {
                paramName = dwutlenek azotu;
                paramFormula = NO2;
                paramCode = NO2;
                idParam = 6;
            };
        },
        [1] SensorItem {
            id = 400;
            stationId = 400;
            param = ParamItem {
                paramName = pył zawieszony PM10;
                paramFormula = PM10;
                paramCode = PM10;
                idParam = 3;
            };
        },
        [2] SensorItem {
            id = 20214;
            stationId = 20214;
            param = ParamItem {
                paramName = ozon;
                paramFormula = O3;
                paramCode = O3;
                idParam = 5;
            };
        }
    );
}]

A: What do we need to do:
Iterate the array, for each station found, iterate over its sensor array. For each sensor found, keep only its id.
let ids = stations.map{ aStation in aStation.sensors.map{ $0.id } }.flatMap{ $0 }

With Sample:
struct StationItem {
    let id: Int
    let sensors: [SensorItem]
}

struct SensorItem {
    let id: Int
}

let stations: [StationItem] = [StationItem(id: 114, sensors: [SensorItem(id: 642),
                                                              SensorItem(id: 644)]),
                               StationItem(id: 70, sensors: [SensorItem(id: 397),
                                                             SensorItem(id: 400),
                                                             SensorItem(id: 2014)])]


text:
Q: How to I read in Array formParams using Javalin's swagger/OpenAPI user interface? The current annotation I'm using is as follows:
@OpenApi(
    summary = "Update Camera",
    tags = ["Camera"],
    formParams = [
        OpenApiFormParam(name = "groupIds", type = List::class, required = true)
    ]
)

Swagger correctly identifies groupIds as being an array parameter, but when I run this line of code
fun updateCamera(context: Context) {
    val groupIds = context.formParams("groupIds")
    ...
}

I just get a in the form ["GroupId1,GroupId2,GroupId3"] with one string entry where each input groupId is separated by a comma. I would like a list with a separate entry for each input groupId as follows ["GroupId1", "GroupId2", "GroupId3"].
I could just split the string by commas, but I would prefer not to do this in the case that a groupId is input that contains a comma. How do I ensure that the array has been properly transformed into the correct JSON format?


text:
Q: Увеличение высоты поля ввода Подскажите, возможно ли в textarea или input-е сделать так, чтобы при достижении правого борта (то есть границы поля), после того, как идет перенос на следующую строку текст не съезжал вверх, а вместо этого увеличивалась Высота поля?
Возможна ли такое реализовать без js, а если не возможно, то подскажите в какую сторону копать)

A: Без JS нельзя, но можно вместо инпута использовать обычный элемент и стилизовать его под инпут:

.input{
  border:1px solid #ccc;
  border-color: #666 #ccc #ccc #666;
  box-shadow: 1px 1px 5px #ccc inset;
  padding: 10px;
}

Введите текст здесь


text:
Q: C++ static pointer to pointer to value I am really new to C++ and don't quite understand how to use pointers right. I have a dll that I want to inject into a program. I know that at the address "program.exe + 0x29D2CC" points to is another pointer to a struct I called entList in this struct there are multiple instances of my class ent. So I am trying to get the first object of the entList (I know for sure that the first object is valid).
In previous projects I was able to do it like this:
entList* entityList = *(entList**)address;

But here it doesn't work. Then I tried to use this function I also used in other projects.
uintptr_t mem::FindDMAAddy(uintptr_t ptr, std::vector<unsigned int> offsets) {
    uintptr_t addr = ptr;
    for (unsigned int i = 0; i < offsets.size(); ++i) {
        addr = *(uintptr_t*)addr;
        addr += offsets[i];
    }
    return addr;
}

entList* entityList = (entList*)mem::FindDMAAddy(moduleBase, { 0x29D2CC, 0x0 });

Using this my injector gives me the error "the remote code wasn't able to load the module".
I searched about this in the internet but since I am new to this I didn't know what to search for exactly and didn't find anything that helped me. Can anyone tell me how I can get the entList* or what method I could use to get objects that are at the end of a pointer chain?


text:
Q: Two divs crossed I would do something like this:

I did in this way ( http://jsfiddle.net/K5KjY/ ):
CSS:
#container{

    width: 970px;
    margin: 0px auto;
}

#backdrop-slider img{
    position: fixed; /* <---- Problem should be here! */
    left: 0;
    right: 0;
    margin: 0px;
    width: 100%;
    height: 200px;
}

#content{
    margin-top: 250px;
    width: 100%
}

HTML:

TITLE

            Link 1
            Link 2
            Link 3

But, in this way, if I scroll down I'll get this:

I would that "backdrop-slider" goes up while scrolling down

A: Add z-index:-1; for the background image. (or positive index for the content)
http://jsfiddle.net/K5KjY/4/
Also, if you want the div to disappear when scrolling use position:absolute; instead of fixed.


text:
Q: How to read external file in python? i need to be able to save and get usernames and passwords from an external file. this is what i have done so far however it constantly says that username or password is incorrect even when i enter it correctly. does anyone know how to fix this problem.
this is my current code
import time
print("Welcome...")
welcome = input("Do you have an acount? y/n: ")
if welcome == "n":
    while True:
        username  = input("Enter a username:")
        password  = input("Enter a password:")
        password1 = input("Confirm password:")
        if password == password1:
            file = open("gcsetask.txt", "a")
            file.write(username + ":" + password)
            file.write('\n')
            file.close()
            welcome = "y"
            time.sleep(0.4)
            print("now lets login")
            break
        print("Passwords do NOT match!")

if welcome == "y":
    while True:
        login1 = input("Enter username:")
        login2 = input("Enter Password:")
        file = open("gcsetask.txt", "r")
        data = file.readlines()
        file.close()
        if data == (login1 + ":" + login2):
            print("Welcome")
            break
        print("Incorrect username or password.")

A: Three methods to read a file

*

*read() It returns the read bytes in form of a string.
fileObject.read()
You can also define, how many bytes to read by
`fileObject.read([n]) //If n is not define, it will read the whole file`

*readline([n]) It reads the line and return in the form of string, It only read single line
fileObject.readline([n])

*readlines() It reads all the lines of the file and return each line a string element in a list
fileObject.readlines()
Hope it helps

A: When you use file.readlines(), the function returns a list of all lines in the file. Thus, when you define data as:
data = file.readlines()

if you print(data), you get something similar to:
['user:pass\n'] # note the the \n at the end

Then, in the following line:
if data == (login1+":"+login2):

you're trying to compare a string (login1+":"+login2) with a list, which is always False because they have different type.
Changing the condition to:
if login1+":"+login2 in data:

should fix this problem (but you'll have a different one, see below).

About the trailing \n:
file.readlines() splits the lines in a list, but does not remove the newline character. This will cause your test to still fail always, because you don't account for it in the test.
Possible solutions are:
1) include the \n in the string you search:
if '{}:{}\n'.format(login1,login2) in data:

2) read the whole file and use splitlines instead, which will remove the newline characters
data = file.read().splitlines()

A: I have changed the code to look at each line of that file. Allowing multiple users.
import time
print("Welcome...")
welcome = input("Do you have an acount? y/n: ")
if welcome == "n":
    while True:
        username  = input("Enter a username:")
        password  = input("Enter a password:")
        password1 = input("Confirm password:")
        if password == password1:
            file = open("gcsetask.txt", "a")
            file.write(username+":"+password)
            file.write('\n')
            file.close()
            welcome = "y"
            time.sleep(0.4)
            print("now lets login")
            break
        print("Passwords do NOT match!")

if welcome == "y":
    while True:
        login1 = input("Enter username:")
        login2 = input("Enter Password:")
        file = open("gcsetask.txt", "r")

        data = file.readlines()
        file.close()
        for line in data:
            if line == (login1+":"+login2+"\n"):
                print("Welcome")
                break
        else:
            print("Incorrect username or password.")

A: The function readlines() saves each line in a string inside a list.
If a file contains-
first line
second line
readlines() gives: ['first line','second line']
Try accessing them using index such as data[0] and data[1]

A: The readlines method returns the list of lines which you need to iterate on it to find the appropriate login information.
data = file.readlines()
login_info = f"{login1}:{login2}\n"
if login_info in data:
    print("Welcome")
    break

And also you can remove \n from the end of each line using splitlines.
data = file.read().splitlines()
login_info = f"{login1}:{login2}"
if login_info in data:
    print("Welcome")
    break

And another alternative is remove \n from parsed lines manually.
data = [line.rstrip('\n') for line in file.readlines()]
login_info = f"{login1}:{login2}"
if login_info in data:
    print("Welcome")
    break


text:
Q: Prove that $\inf\left\{t\ge 0:Y_t=y\right\}$ is a stopping time Let

*

*$(\Omega,\mathcal A,\operatorname P)$ be a probability space

*$(\mathcal F_t)_{t\ge 0}$ be a filtration on $(\Omega,\mathcal A)$

*$(Y_t)_{t\ge 0}$ be a real-valued $\mathcal F$-adapted continuous stochastic process on $(\Omega,\mathcal A,\operatorname P)$

*$y\in\mathbb R$

Question:

*

*How can we show that $$\tau:=\inf\left\{t\ge 0:Y_t=y\right\}$$ is an $\mathcal F$-stopping time?

*Do we need the continuity of $Y$? Or is it sufficent, if this property holds only $\operatorname P$-almost surely? What about ($\operatorname P$-almost sure) right-continuity?

I'll try to give an answer to 1. by myself. Step 1:

*

*Let $T\ge 0$ and $$\omega\in\left\{\sup_{t\in[0\:T]}Y_t\ge y\right\}$$

*$Y$ is continuous $\Rightarrow$ $\exists t_{\text{max}}\in[0,T]$ with $$Y_{t_{\text{max}}}(\omega)=\sup_{t\in[0,\:T]}Y_t(\omega)\in[y,\infty)$$ and $$y\in\left[Y_0(\omega),Y_{t_{\text{max}}(\omega)}\right]$$ and hence $\exists t\in[0,T]$ with $$Y_t(\omega)=y$$ by the intermediate value theorem

Step 2:

*

*Let $T\ge 0$ and $$\omega\in\left\{\tau_y\le T\right\}=\left\{\exists t\in[0,T]:Y_t=y\right\}$$

*It's obvious that then $$\omega\in\left\{\sup_{t\in[0\:T]}Y_t\ge y\right\}$$

Step 3:

*

*We have shown that $$\left\{\tau_y\le T\right\}=\left\{\sup_{t\in[0\:T]}Y_t\ge y\right\}$$ for all $T\ge 0$

*Since $Y$ is continuous, $$\sup_{t\in[0\:T]}Y_t=\sup_{t\in[0\:T]\cap\mathbb Q}Y_t$$ and since $Y$ is $\mathcal F$-adapted, $$\left\{\sup_{t\in[0\:T]\cap\mathbb Q}Y_t\ge y\right\}\in\mathcal F_T$$

*Thus, we're done

Is the proof correct? If so, I think that at least this proof won't work unless $Y$ is continuous. However, it should work in the case of $\operatorname P$-almost sure continuity too, if we assume that $\mathcal F$ is $\operatorname P$-complete, right?


text:
Q: Jquery .next() Bootstrap data-provide Solved
My script as far is:

<?php echo $this->getLang('UI', 49);?>

             <input type="text" id="HackType_Search" name="inputType" placeholder="Type" class=" input-xlarge ajaxStatusIndicatorInput" style="margin-bottom:0px;" data-provide="typeahead" data-items="4" rel="tooltip" title="Choose the type of the file which mostly fits." required>

When I do an ajax-call to my website to verify the data that was entered, I want to give this  the class statusSuccessMini. That indicates everything is correct.
Doing the call and getting results is working allright, but the interesting part is, that this:
 $.each($.parseJSON(data), function(idx, data) {

    if(data.bool === 'true' && data.name) {
        $('input[name='+data.name+']').next('.add-on').addClass('statusSuccessMini');
        $('input[name='+data.name+']').next('.add-on').html('.add-on');
    }
    else {
        $('input[name='+data.name+']').next('.add-on').addClass('statusWarningMini');
        i++;
    }
});

Will only work if there's no data-provide like this data-provide="typeahead" data-items="4" given.
This works:

<?php echo $this->getLang('UI', 49);?>

        <input type="text" id="HackType_Search" name="inputType" placeholder="Type" class=" input-xlarge ajaxStatusIndicatorInput" style="margin-bottom:0px;" rel="tooltip" title="Choose the type of the file which mostly fits." required>

I checked all the data, they work and I can find the input but when I try to find the span with .next() it only gets it when there's no data-provide given.
I hope you can help me, any suggestion is appreciated :)
Edit: FF Code Inspector showed me this:

<input id="Game_Search" class="input-xlarge ajaxStatusIndicatorInput" type="text" required="" title="" rel="tooltip" style="margin-bottom:0px;" data-items="4" data-provide="typeahead" placeholder="Game" name="inputGameID" data-original-title="Choose the game the file works with."></input>

So the Bootstrap Typeahead is inserting a list into the DOM...

A: Try
$('input[name= + data.name + ']').parent().find('.add-on').addClass('statusWarningMini');

See Documentation: .parent() / .find()
Here's a working Demo (via jsfiddle)


text:
Q: Google map polyline-draws-extra-line I'm using google map javascript polyline drawing using the below code
var flightPath = new google.maps.Polyline({
                path: BeatPath,
                geodesic: true,
                strokeColor: '#0077ff',
                strokeOpacity: 1.0,
                strokeWeight: 5
            });

            flightPath.setMap(map);

It drawing the path correctly but adding extra line to the starting point how to remove that ? in the screenshot you can see the result , marked in red is wrong , marked in green is correct , how to avoid the unwanted line ?

A: List of array not in a descending order , this has been fixed by changing the list order by timestamp


text:
Q: How to fix an application-defined or object-defined error This macro works for me on my computer but it's giving me a headache when I ask my colleague to run it.
Any suggestions on why this is giving me trouble?
The macro works fine on my computer, but on my co-worker's computer, the Run-time error '1004' pops up... application-defined or object-defined error.  Debug brings me to the bottom of the script, just below 'resize each section on the summary page.
Thanks!
Sub Resize_Template()

'count records on pipeline tab
Dim pipe As Integer
With Sheets("Pipeline - Underwriting Data D")
pipe = .Range("A" & .Rows.Count).End(xlUp).Row - 1
End With
'count records on Lead tab
Dim Lead As Integer
With Sheets("Lead Data")
Lead = .Range("A" & .Rows.Count).End(xlUp).Row - 1
End With
'count records on approved tab
Dim App As Integer
With Sheets("Approved Closing Data Draw")
App = .Range("A" & .Rows.Count).End(xlUp).Row - 1
End With
'count records on mods tab
Dim Mods As Integer
With Sheets("Modifications")
Mods = .Range("A" & .Rows.Count).End(xlUp).Row - 1
End With
'resize each section on the summary page
Sheets("Weekly Pipeline Template").Range("App_Close_btm").Resize(App - 2).EntireRow.Insert
Sheets("Weekly Pipeline Template").Range("Modifications_btm").Resize(Mods - 2).EntireRow.Insert
Sheets("Weekly Pipeline Template").Range("UW_btm").Resize(pipe - 2).EntireRow.Insert
'Lead section does not need to be resized at this time
End Sub


text:
Q: How do I update an angularjs page after a scope update? I have written a directive that captures keyboard events, and on certain keys I update some objects in the scope. The idea is to move up and down an array and display the selected row details. The problem is the page is not updated until I do another action that updates the page. How can I force this?
Here's the directive:
LogApp.directive("keyCapture", [function(){
    var scopeInit;
    return{
        link: function(scope, element, attrs, controller){
            scopeInit = scope
            element.on('keydown', function(e){
                scopeInit[attrs.keyCapture].apply(null, [e]);
            });
        }
    }
}]);

Bound the template like this:

The controller method:
$scope.movePreview = function(e){
    if ($scope.events.length === 0)
        return;
    // Find the element
    if (e.keyCode === 38 || e.keyCode === 40){
        console.log("Pressed %s", e.keyCode);
        var offset = 0;
        if (e.keyCode === 38 && $scope.previewIndex > 0)
            offset = -1;
        else if (e.keyCode === 40 && $scope.previewIndex < $scope.events.length -1 )
            offset = 1;

        $scope.previewIndex += offset;
        var eventId = $scope.events[$scope.previewIndex].uuid;
        $scope.showEvent(eventId);
        e.preventDefault();
    }
};

$scope.showEvent(eventId) will take the item with given ID and display it in another part of the page. Part that is not update until another action is performed, like clicking a button. Is it possible to force the page update?
Here's a fiddle that reproduces: http://jsfiddle.net/gM2KF/1/
If you click on the button, the counter is updated. If you press any key, nothing shows. But you click again on the button, you see the counter has been updated by the keyboard event, but didn't show.

A: If you are listening to non-angular events:
element.on('keydown', function(e){
    scopeInit[attrs.keyCapture].apply(null, [e]);
});

Then, to update the scope, you need to call scope.$apply:
element.on('keydown', function(e){
    scopeInit[attrs.keyCapture].apply(null, [e]);
    scope.$apply();
});

This will kick off an angular $digest cycle and allow changes to bind.

A: Just wrap the $scope changes in $scope.$apply();
While your code could be altogether cleaner, this ought to make it work:
$scope.movePreview = function(e){
  $scope.$apply(function() {
    if ($scope.events.length === 0)
        return;
    // Find the element
    if (e.keyCode === 38 || e.keyCode === 40){
        console.log("Pressed %s", e.keyCode);
        var offset = 0;
        if (e.keyCode === 38 && $scope.previewIndex > 0)
            offset = -1;
        else if (e.keyCode === 40 && $scope.previewIndex < $scope.events.length -1 )
            offset = 1;

        $scope.previewIndex += offset;
        var eventId = $scope.events[$scope.previewIndex].uuid;
        $scope.showEvent(eventId);
        e.preventDefault();
    }
  });
};

A: This is a single example that prints out events based on your example:
HTML

Pressed: {{previewIndex}}

JS
var app = angular.module('App', []);

function MyCtrl($scope) {
    $scope.movePreview = function(e){
        $scope.previewIndex = e.keyCode;
};

}
app.$inject = ['$scope'];
app.directive("keyCapture", [function(){
    var scopeInit;
    return{
        link: function(scope, element, attrs, controller){

             element.bind('keydown', function (e) {
                scope.$apply(function(){scope.movePreview(e);});
            });
        }
    }
}]);

Demo Fiddle
We call movePreview method on each key event.


text:
Q: Getting UserId of current user Blazor webassembly So I am writing a Blazor webassembly application, with asp.ner core Identity. I need to get the ID of the current user, not the username that the methods in Identy give.
The method
Context. User.identity.name
gives the username but I need the ID for a fk in a model/table.
I can't use the username as usernames might change.
I have searched the net, however I keep seeing just the username returned.
Any assistance will be greatly appreciated.

A: In Startup.cs, add the following line in ConfigureServices
services.AddHttpContextAccessor();

In your Blazor component, add the following lines on the top of the file
@using System.Security.Claims
@inject IHttpContextAccessor HttpContextAccessor

In your method, add the following lines to get the UserId
var principal = HttpContextAccessor.HttpContext.User;
var loggedInUserId = principal.FindFirstValue(ClaimTypes.NameIdentifier);

A: Not an answer, just a tip on using breakpoints to find the answer.  My site is Blazor Server, so it's very possible that things are different-- in my case, Brian Parker's solution didn't work for me, so I did the following:
var user = (await AuthenticationStateProvider.GetAuthenticationStateAsync()).User;
if (true) {} // or any other code here, breakpoint this line

If you set a breakpoint right after retrieving the user, run the app and hover the user variable in the code when it breaks, it will pop up the complete object.  By hovering various fields, you can investigate.  I found that the claim type strings were big long things like "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"
So the answer that worked for me was:
var user = (await AuthenticationStateProvider.GetAuthenticationStateAsync()).User;
string userId = user.FindFirst(c => c.Type.Contains("nameidentifier"))?.Value;

My point is that when the docs are complicated, or when the technology is changing fast so that one day's right answer is the next day's wrong lead, you can achieve a lot just by using VS to dig around.
Hope that helps someone. :D

A: I use this with the boiler plate Identity Server:
@page "/claims"
@inject AuthenticationStateProvider AuthenticationStateProvider

ClaimsPrincipal Data

@_authMessage

@if (_claims.Count() > 0)
{

        @foreach (var claim in _claims)
        {

                @claim.Type
                @claim.Value

        }

}

@_userId

@code {
    private string _authMessage;
    private string _userId;
    private IEnumerable<Claim> _claims = Enumerable.Empty<Claim>();

    protected override async Task OnParametersSetAsync()
    {
        await GetClaimsPrincipalData();
        await base.OnParametersSetAsync();
    }

    private async Task GetClaimsPrincipalData()
    {
        var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
        var user = authState.User;

        if (user.Identity.IsAuthenticated)
        {
            _authMessage = $"{user.Identity.Name} is authenticated.";
            _claims = user.Claims;
            _userId = $"User Id: {user.FindFirst(c => c.Type == "sub")?.Value}";
        }
        else
        {
            _authMessage = "The user is NOT authenticated.";
        }
    }
}


text:
Q: How to find out parameter name for maven commands? I just imported a maven project (someone else's work) in eclipse where m2e plugin is installed. I was asked to create/run maven configuration based on readme.txt file.
I entered following command to Goals field after creating new Maven run configuration as the instruction said. Running the command was successful.
compile test -Dtest=HelloWorldTest -Dfoo=bar

My question is why I have to provide -Dtest as a parameter that points to a Java class (HelloWorldTest) that would be executed. Where it is specified? I could not find it neither from the class nor pom.xml file.

A: First of all, I have noticed you have run two phases of build cycle i.e. compile and test. Actually you just need to run 'test' phase which is after phase 'validate' and 'compile'.
For more details about maven build cycle you can go to
https://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html
In the phase 'test', maven tries to run all of tests those classes who name ends with 'Test' by default. When the command line argument -Dtest is specified, maven would just run the test class specified in your case it is 'HelloWorldTest'. BTW the principle of 'convention over configuration' is used by default when using Maven.


text:
Q: Can I not use the pronoun "You" in the instructions? When I write about the need to do something, the my translator translates:

First YOU need to perform the following steps.

But I do not appeal to a specific person, but I speak of necessity in general. Why is the pronoun 'YOU' used here, and is it possible to remove it and write how?:

First, need to perform the following steps.

or should I write?:

First, it is necessary to perform the following steps.

What is the best way to write instructions when I do not address a particular person?
Thanks in advance for any answer/comment!

A: It's fine to use you when writing advice. instructions etc. in a fairly informal tone, as though you (the writer) are addressing the reader personally.
Your second version doesn't work. The third one is fine, but its tone is more formal.
Another way would be to say The following steps should be performed.


text:
Q: How to override Joomla System Messages - message.php template Joomla by default renders its system messages (errors, notices etc.) in
libraries/joomla/document/html/renderer/message.php.
For my own template, I would like to customize the way these messages are displayed. However it does not seem to be possible in the traditional way, using template overrides.
Is anyone here aware of a way to accomplish something like this?

A: For Joomla! 1.7 - 2.5
You need copy libraries/joomla/document/html/renderer/message.php in to templates/YOUR_TEMPLATE/html/message.php
Then in index.php of YOUR_TEMPLATE you need to include the file (as it is not automatically included like other overrides):
// Message overwrite
require_once JPATH_ROOT .'/templates/'. $this->template .'/html/message.php';

Now you can safety overwrite the JDocumentRendererMessage::render() function there ;)
For Joomla! 3.x
You just need make html/message.php file in YOUR_TEMPLATE. This file should contain function renderMessage(). Check the isis default template, as example.

A: Templates overrides only work with the MVC - i.e. views and module chrome.
Without hacking the core all you can do is control what HTML tags are wrapped around the <jdoc:include type="message" /> tag in the template and the CSS defined for the elements of the message block.

A: A more elegant way to include your override in the template directory is to include the file in a system plugin:
public function onAfterInitialise() {
    $app = JFactory::getApplication();
    if ($app->isSite()) {
        $template = $app->getTemplate();
        if (!class_exists('JDocumentRendererMessage') && file_exists(JPATH_THEMES . '/' . $template . '/html/message.php')) {
            require_once JPATH_THEMES . '/' . $template . '/html/message.php';
        }
    }
    return true;
}

A: http://extensions.joomla.org/extensions/style-a-design/popups-a-iframes/26551
OR
http://extensions.panchsoft.com/product/1-popup-system-messages.html
Use this extension for default messages for Joomla.


text:
Q: Finding glfw library file in xcode in OSX? So I'm trying to build a program using OpenGL and GLFW. The only errors I'm getting are:
Undefined symbols for architecture x86_64:
  "_glewInit", referenced from:
      _main in main.o
  "_glfwCreateWindow", referenced from:
      _main in main.o
  "_glfwGetKey", referenced from:
      _main in main.o
  "_glfwInit", referenced from:
      _main in main.o
  "_glfwMakeContextCurrent", referenced from:
      _main in main.o
  "_glfwPollEvents", referenced from:
      _main in main.o
  "_glfwSetInputMode", referenced from:
      _main in main.o
  "_glfwSwapBuffers", referenced from:
      _main in main.o
  "_glfwTerminate", referenced from:
      _main in main.o
  "_glfwWindowHint", referenced from:
      _main in main.o
  "_glfwWindowShouldClose", referenced from:
      _main in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

So obviously this is a linking error. After doing some research, I think I found my error. It seems like I need to add the GLFW library (libglfw.dylib) and the Cocoa and OpenGL libraries. My problem is that I can't find libglfw.dylib - or anything glfw for that matter - under the "Link Binary With Libraries" section. I found OpenGL.framework and Cocoa.framework, but I can't find the glfw one. I tried going through the whole cmake process (cmake > make > sudo make install) for glfw but it didn't show up. I then tried installing using brew and that didn't work either. I can't figure out why I can't find this file. Any ideas? This is my first time doing anything with GLFW and one of my first projects doing any coding on OSX. If I'm forgetting any information you need to help let me know and I'll get it to you all as fast as I can.

A: First of all, using GLEW on OS X is 100% pointless (OpenGL extensions are all handled statically at link-time on this platform). You should add some code to your project that does something along the lines of:
#ifndef __APPLE__
  // GLEW-specific code here
#endif

Also, .dylib is for dynamically linking - there's not much point in doing that on OS X. GLFW is not distributed in the form of a Framework, you'll have to compile it yourself. You can still use a dynamic linking version of GLFW if you wish, but you'd wind up having to package the library in your .app bundle. I would advise you just use the static version and avoid all of that.
Have you reviewed the OS X section of the GLFW compilation instructions?


text:
Q: Adding voids underneath analog signal for improved impedance matching Using a snapshot of an eval board design below as an example, voids are added to the ground plane on layer 2 (green) right underneath the analog signal path on layer 1 (yellow). This causes the analog traces to reference the ground plane on layer 3 instead. I understand that this increases trace width, hence improved impedance matching and decreased signal loss at the trace-to-pad junctions.
What is the best way to determine the minimum width of the voids that guarantees that the signals do not reference layer 2? I assume this is based on the trace widths and the layer separations.

A: The "best" way is to build a board and measure the impedance. Another "best" way is to simulate it with some form of EM simulation software. The "quick" way is to use a rule of thumb like 5 tracewidths on either side (for microstrip). So, if your trace is 10 mils, keep all copper on layer 2 at 50 mils or more away.
However, that looks more like coplanar waveguide than microstrip...