text:
Q: How to change Bootstrap tabs fade OUT speed? I am trying to change the speed of a fade effect in Bootstrap. I found this answer using css:

@import url('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css');

.fade {
   opacity: 0;
   -webkit-transition: opacity 1.5s linear;
      -moz-transition: opacity 1.5s linear;
       -ms-transition: opacity 1.5s linear;
        -o-transition: opacity 1.5s linear;
           transition: opacity 1.5s linear;
 }

  <button class="btn active" data-toggle="tab" href="#one">One</button>
  <button class="btn" data-toggle="tab" href="#two">Two</button>
  <button class="btn" data-toggle="tab" href="#three">Three</button>

This is the One

This is the Two

This is the Three

...but this only affects the fade-in time. The fade-out stays the same. Any suggestions?

A: There is no fade-out time, the class that makes the element visible just gets removed.
To make it fade-out, you have to make sure the item doesn't get removed from the dom (HTML document), but rather make it invisible so it can fade.
Here is an example, adjust to your wishes:

@import url('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css');

.tab-content {
  position:relative;
}

.tab-content>.tab-pane {
  /* in order to make sure the elements are nicely in position
     use position:absolute; */
  position:absolute;
  top:0;
}

.fade {
   opacity: 0;
   -webkit-transition: opacity 1.5s linear;
      -moz-transition: opacity 1.5s linear;
       -ms-transition: opacity 1.5s linear;
        -o-transition: opacity 1.5s linear;
           transition: opacity 1.5s linear;
 }

.tab-content>.tab-pane:not(.in) {
  /* display:none; is the default behaviour, make that display:block; */
  display:block;
  /* make the opacity 0, that is what the transition responds to! */
  opacity:0;
}

  <button class="btn active" data-toggle="tab" href="#one">One</button>
  <button class="btn" data-toggle="tab" href="#two">Two</button>
  <button class="btn" data-toggle="tab" href="#three">Three</button>

This is the One

This is the Two

This is the Three

A: The issue is that when an item is not active, it's display property is set to display:none, and therefore is being hidden before any animation can be applied. If you position everything using absolute position to overlap, then you can leave the display as display:block and just change the opacity:

@import url('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css');

.fade {
   opacity: 0;
   -webkit-transition: opacity 1.5s linear;
      -moz-transition: opacity 1.5s linear;
       -ms-transition: opacity 1.5s linear;
        -o-transition: opacity 1.5s linear;
           transition: opacity 1.5s linear;
 }
.tab-content {
    position:relative;
}
.tab-content>.tab-pane {
   top: 0;
   position:absolute;
   display:block;
 }
.tab-content>.tab-pane:not(.active) {
    opacity: 0;
 }

  <button class="btn active" data-toggle="tab" href="#one">One</button>
  <button class="btn" data-toggle="tab" href="#two">Two</button>
  <button class="btn" data-toggle="tab" href="#three">Three</button>

This is the One

This is the Two

This is the Three

A: If you simply want to avoid having the fade affect, or need the tabs to appear more quickly remove the fade class.
// Original

This is the One

This is the Two

This is the Three

// Updated

This is the One

This is the Two

This is the Three

The fade class is only applied to the first pane, then when the button is clicked then Jquery removes the active class and fade class and applies it to the corresponding pane.


text:
Q: Wave equation $u_{xx}+u_{xt}- u_{tt}=0$ Does anybody know how we can solve the equation $u_{xx}+  u_{xt}-  u_{tt}=0$ with $u(x,0):=g(x)$ and $u_t(x,0):=h(x)?$ I mean it is known how to do this for the wave equation see here but I don't know how to do this in the more general case with the mixed term in it.

A: I would try a solution of type $F(z)=F(x-ct)$, or $G(w)=G(x+ct)$. For $F$ this gives
$$
u_{xx}=F''(z)\\
u_{xt}=-cF''(z)\\
u_{tt}=c^2F''(z)
$$
so
$$
(1-c-c^2)F''(z)=0\implies c_{1,2}=\frac{1\pm\sqrt{5}}{2}.
$$
So $F(x-c_it)$ is a solution for every choice of $F$.
Same reasoning for $G$.

A: We are dealing with the wave equation $u_{xx}+u_{tt}-u_{tt}=0$. Notice that it has a mixed term. So we cannot use d'Alembert's formula here. (The formula assumes a difference of squares when "factoring" the derivatives.) Here, we have to "factor" the derivatives manually.
Note that we can rewrite our wave equation as $$\left( \frac{\partial^2}{\partial x^2} + \frac{\partial}{\partial x}\frac{\partial}{\partial t} - \frac{\partial^2}{\partial t^2}\right)u=0.$$ And "factoring" out the derivatives (using the quadratic formula to help) gives $$\left(\frac{\partial}{\partial x}+\frac{1-\sqrt{5}}2 \frac{\partial}{\partial t} \right)\left(\frac{\partial}{\partial x}+ \frac{1+\sqrt{5}}2 \frac{\partial}{\partial t} \right)u=0.$$
Now set $\frac{\partial}{\partial \xi}:=\frac{\partial}{\partial x}+\frac{1-\sqrt{5}}2 \frac{\partial}{\partial t}$ and $\frac{\partial}{\partial \eta}:=\frac{\partial}{\partial x}+\frac{1-\sqrt{5}}2 \frac{\partial}{\partial t}$. Then the wave equation becomes the Canonical form $$\frac{\partial}{\partial \xi}\frac{\partial}{\partial \eta}u=0$$ or $u_{\xi \eta}=0$. Furthermore, the chain rules of $\frac{\partial}{\partial \xi}=\frac{\partial}{\partial x}\frac{dx}{d\xi}+\frac{\partial}{\partial t}\frac{dt}{d\xi}$ and $\frac{\partial}{\partial \eta}=\frac{\partial}{\partial x}\frac{dx}{d\eta}+\frac{\partial}{\partial t}\frac{dt}{d\eta}$ imply $$\frac{dx}{d\xi}=1, \quad \frac{dx}{d\eta}=1, \quad \frac{dt}{d\xi}=\frac{1-\sqrt{5}}2, \quad \frac{dt}{d\eta}=\frac{1+\sqrt{5}}2.$$ Thus, we  obtain $$x=\xi+\eta, \quad t=\frac{1-\sqrt{5}}2\xi+\frac{1+\sqrt{5}}2\eta,$$ which means we can use these to perform change of variables.
Can you finish the rest from here?

A: Hint: note that your equation can be expressed as follows:
$$(D^2_x + D_x D_t  - D^2_t)\, u = (D_x- \varphi^- D_t)  (D_x - \varphi^+ D_t) u  = 0, $$ where $\varphi^{\pm} = (-1 \pm \sqrt{5})/2$ are the two solutions of $s^2+s-1=0$. What if we now define $v := (D_x - (-1+\sqrt{5})D_t/2) u$? Can you solve 1st order PDEs?
Cheers!

Of course, you will have noticed that $-\varphi^- = \varphi$ is the so-called golden ratio, satisfying $\varphi = 1 + \varphi^{-1}$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Two opposing categorical variables and moving from univariate to multivariate linear regression My knowledge of statistics is described as "working" or more accurately a very immature "work in progress" so please excuse me if this question is extremely simple.
I am currently writing my masters thesis and as part of my thesis I was provided with output from univariate and multivariate regressions investigating the relationship between 1 dependent variable (A measure of someone's attitude) and approximately 15 independent variables, many of which are categorical with some being continuous.
Two of these independent variables ask effectively opposing questions
Var_1: "Does your practice provide any monitoring services?"
Var_2: "Does your practice provide monitoring service X?" - Where service X is in most cases the bare minimum service provided, and it would be expected that those who respond no to the first  question will respond yes to the first question. Summary statistics describing the responses to these two questions more or less confirms this.
I have very limited formal knowledge of statistics however what I have observed in the univariate analysis is that both have p values below 0.025 but skyrocket to well over 0.3 and 0.6 in multivariate regression.
Would I be correct in saying that as the two variables are obviously antagonistic and dependent on one another, this explains why they lose statistical significance in the multivariate analysis?


text:
Q: Determining dimension of a sum of subspaces in terms of a parameter Problem: Consider the linear subspaces \begin{align*} U = \text{span} \left\{ (1,0,1,0), (1,a,0,a)\right\} \quad \text{and} \quad W = \text{span}\left\{(-1, a, a^2, 0), (0,1,0,-1)\right\} \end{align*} in $\mathbb{R}^4$. Determine $\dim(U^{\bot} + W)$ in terms of the parameter $a \in \mathbb{R}$, where $U^{\bot}$ denotes the orthogonal complement of $U$ with respect to the standard innerproduct on $\mathbb{R}^4$.
Attempt at solution: In general, we have the equation $\dim(U + W) + \dim(U \cap W) = \dim(U) + \dim(W)$.
In this case, we have $\dim(U) = 2, \dim(W) = 2$ and $\dim(U^{\bot}) = 2$ (since $U^{\bot} \oplus U = \mathbb{R}^4)$.
So $\dim(U^{\bot} + W) = 4 - \dim(U^{\bot} \cap W)$.
Now, $U^{\bot}$ consists of all the vectors $(x,y,z,u) \in \mathbb{R}^4$ such that $\langle (x,y,z,u), (1,0,1,0) \rangle = 0$ and $\langle (x,y,z,u), (1, a, 0, a) \rangle = 0$. This leads to the system of equations \begin{align*} \begin{cases} x+z &= 0 \\ x+ay + au &= 0 \end{cases} \end{align*}
The subspace $W$ consists of all vectors $(x,y,z,u)$ such that \begin{align*} (x,y,z,u) = \lambda_1 (-1, a, a^2, 0) + \lambda_2 (0,1,0,-1). \end{align*}
This leads to the system \begin{align*} \begin{cases} x &= - \lambda_1 \\ y &= \lambda_1 + \lambda_2 \\ z &= \lambda_1 a^2 \\ u &= - \lambda_2 \end{cases} \end{align*}
Now, I was wondering what the intersection is of $W$ and $U^{\bot}$, i.e. how I can determine $U^{\bot} \cap W$. Should I just substitute the expressions for $x,y,z,u$ into the first system? And then solve for $\lambda_1$ and $\lambda_2$?

A: $U^\bot\cap W$ is a subspace of $W$ and it certainly contains the vector $(0,1,0,-1)$. (Since this vector belongs to $W$ and it is orthogonal to both vectors generating $U$.) So $U^\bot\cap W$ can be either 1-dimensional or 2-dimensional. (In the first case, it is generated by $(0,1,0,-1)$. In the second case it is equal to $W$.)
So now it suffices to find out for which value of $a$ the vector $(-1,a,a^2,0)$ belongs to $U^\bot$. If it does, $\dim(U^\bot\cap W)=2$. If it does not, $\dim(U^\bot\cap W)=1$.


text:
Q: How to exclude the VENV in Docker PUSH I have a basic Python script that I would like to containerize. As part of the script, I am to pip install az.cli which is almost 500 mb in size. Locally, it works all right. When I docker build it, and docker run it, it works just as how it's supposed to work. The issue is when I want to docker push it (to dockerhub for now).
It's packaging the entire project with the venv, that's ~550 mb. I'd like to avoid that, if possible. I added the venv directory in the .dockerignore file, but that doesn't seem to help. I know it's pushing the whole container to dockerhub, so I guess, esentially, is there a way to build/run the docker application without the essence az.cli baked in?
FYI: I am new to Docker, so what I am asking may not make sense.


text:
Q: Solution of a first order linear homogeneous ODE with non-constant coefficients I was trying to show that if $A:\mathbb{R} \rightarrow \mathbb{R}^{nxn} \text{ } $  has a eigen pair $(\lambda(t),v) \text{ }$ with $v$ constant, then $x(t)=e^{\lambda t}v$ is a solution of the system $\dot{x} = A(t)x$
Since $$x'(t) = e^{\lambda(t) t}v(\lambda'(t)t+\lambda(t))$$
Then $$\dot{x} = A(t)x \Leftrightarrow e^{\lambda(t) t}v(\lambda'(t)t+\lambda(t)) = A(t)e^{\lambda(t)t}v$$
$$\Leftrightarrow v(\lambda'(t)t+\lambda(t)) = A(t)v$$
$$\Leftrightarrow v(\lambda'(t)t+\lambda(t)) = \lambda(t)v$$
$$\Leftrightarrow v\lambda'(t)t = 0$$
And because $v$ is an eigenvector of A we now that $v\neq0$.
Then  $x(t)=e^{\lambda t}v$ is a solution of $\dot{x} = A(t)x \text{ }$ whenever $\lambda'(t)t=0$
This is where I got stuck.
Thanks in advance!

UPDATE:
As mentioned in the comments, following the same reasoning as above, it can be shown that $x(t)=e^{\int_{t_0}^{t}\lambda(s)ds}v$, with $\lambda(t_0) = 0$ is a solution of $\dot{x} = A(t)x$

A: What you are trying to prove is not true. Consider for example the case $n=1$ with $A(t) = t$, $\lambda(t) = t$ and $v = 1$. Then $x(t) = e^{t^2}$, so that
$$\dot{x}(t) = 2te^{t^2} \neq te^{t^2} = A(t)x.$$
EDIT: Also notice the formula given by user8268 in the comments.


text:
Q: Constructing an LL(1) grammar with substituion, factoring and left recursion removal Using any of the techniques (substitution, factoring, left-recursion removal),
construct an LL(1) grammar accepting the same language as G.
G over Σ = {0, 1, 2}:
    S → Y | 1X
    X → 1X | 0
    Y → Y0 | 1X1 | 2X2

I did this so far:
X is left recursive so:
X -> 1F | 0F
F -> 1F | e

What else would i need to do to construct an LL(1), could i factor Y?

A: First, X is not left recursive, as its RHS doesn't begin with X. Rather it's tail-recursive and it's all right. However Y -> Y0 tells you that Y is left-recursive. In this case you do the following:
S -> Y | 1X
X -> 1X | 0
Y -> 1X1F | 2X2F
F -> 0F | e

You may also want to add and epsilon rule to X as well making it
X -> 1X | 0 | e

just to make sure you'll never end up with infinite sentences.


text:
Q: Definition mx.core:BitmapAsset could not be found. (with ant and FlashDevelop) I saw this question:
mx.core::BitmapAsset could not be found
and the answer did not help.
I am compiling the code with ant and FlashDevelop and getting the error: Definition mx.core:BitmapAsset
If I compile normally in FlashDevelop without ant it works alright(no error).
I tried doing what they suggested in the answer and some other site and it did not work.
Namely:
I changed this xml field to true:
<static-link-runtime-shared-libraries>true</static-link-runtime-shared-libraries>
And attempted to import BitmapAsset from framework.swc
Please help me resolve this.

A: Either link to the flex library swc, or create your own mx.core.BitmapAsset that implements all the Interfaces BitmapAsset implements.


text:
Q: Encontrar numero faltante en el array Tengo que encontrar que números del 1 al 10 faltan en el array llamado _valores, hice otro array para comparar, pero no logro hacer que diga cuales faltan.
public static void main(String[] args) {

    int [] _valores = {5, 8, 4, 6, 2, 9};

    int [] _total = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    int numerosfaltantes = 0;

    for (int i = 0; i < _valores.length; i++) {

        numerosfaltantes = _valores[i];

        for (int j = 0; j < _total.length; j++) {

            if (numerosfaltantes != _total[j] ) {

                numerosfaltantes = _valores[i];

                System.out.println(""+numerosfaltantes);
            }
        }
    }
}

A: Te dejo una solución espero que te sirva!
public class NumerosFaltantes {

    public static int [] domain = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    public static void printNumerosFaltantes(int[] values) {
        for (int i = 0; i < domain.length; i++) {
            boolean isNumeroFaltante = true;

            for (int j = 0; j < values.length; j++) {
                if (values[j] == domain[i]) {
                    isNumeroFaltante = false;
                }
            }

            if (isNumeroFaltante) {
                System.out.println("Falta el número " + domain[i]);
            }
        }
    }

    public static void main(String[] args) {
        // TODO code application logic here
        int[] values = {5, 8, 4, 6, 2, 9};
        NumerosFaltantes.printNumerosFaltantes(values);
    }
}

Debes recorrer todo el dominio de valores contra el array a buscar los numeros faltantes. Es decir, cada valor posible entre 1 y 10 debes buscarlo en tu array _valores por lo tanto los for deben ser al reves. la variable booleana isNumeroFaltante asume que el numero no se encuentra en el array y en caso de encontrarlo setea el valor en falso. Cuando se termina de recorrer el array de valores si no se encontro el numero se imprime el numero faltante.
Espero que se entienda y que te sirva.
Saludos!


text:
Q: What type-conversions are happening? #include "stdio.h"

int main()
{
    int x = -13701;
    unsigned int y = 3;
    signed short z = x / y;

    printf("z = %d\n", z);

    return 0;
}

I would expect the answer to be -4567.  I am getting "z = 17278".
Why does a promotion of these numbers result in 17278?
I executed this in Code Pad.

A: Short answer: the division first promotes x to unsigned. Only then the result is cast back to a signed short.
Long answer: read this SO thread.

A: The problems comes from the unsigned int y. Indeed, x/y becomes unsigned. It works with :
#include "stdio.h"

int main()
{
    int x = -13701;
    signed int y = 3;
    signed short z = x / y;

    printf("z = %d\n", z);

    return 0;
}

A: The hidden type conversions are:
signed short z = (signed short) (((unsigned int) x) / y);

When you mix signed and unsigned types the unsigned ones win. x is converted to unsigned int, divided by 3, and then that result is down-converted to (signed) short. With 32-bit integers:
(unsigned) -13701         == (unsigned) 0xFFFFCA7B // Bit pattern
(unsigned) 0xFFFFCA7B     == (unsigned) 4294953595 // Re-interpret as unsigned
(unsigned) 4294953595 / 3 == (unsigned) 1431651198 // Divide by 3
(unsigned) 1431651198     == (unsigned) 0x5555437E // Bit pattern of that result
(short) 0x5555437E        == (short) 0x437E        // Strip high 16 bits
(short) 0x437E            == (short) 17278         // Re-interpret as short

By the way, the signed keyword is unnecessary. signed short is a longer way of saying short. The only type that needs an explicit signed is char. char can be signed or unsigned depending on the platform; all other types are always signed by default.

A: Every time you mix "large" signed and unsigned values in additive and multiplicative arithmetic operations, unsigned type "wins" and the evaluation is performed in the domain of the unsigned type ("large" means int and larger). If your original signed value was negative, it first will be converted to positive unsigned value in accordance with the rules of signed-to-unsigned conversions. In your case -13701 will turn into UINT_MAX + 1 - 13701 and the result will be used as the dividend.
Note that the result of signed-to-unsigned conversion on a typical 32-bit int platform will result in unsigned value 4294953595. After division by 3 you'll get 1431651198. This value is too large to be forced into a short object on a platform with 16-bit short type. An attempt to do that results in implementation-defined behavior. So, if the properties of your platform are the same as in my assumptions, then your code produces implementation-defined behavior. Formally speaking, the "meaningless" 17278 value you are getting is nothing more than a specific manifestation of that implementation-defined behavior. It is possible, that if you compiled your code with overflow checking enabled (if your compiler supports them), it would trap on the assignment.


text:
Q: Ruby array access position in array @product

returns a single record.  By relationship this product belongs to a slot
@slot = Slot.where(['id = ?', @product.slot_id]).first

what needs to be accessed is the position x in the array of all @slots = Slot.order('id asc').all so that I can identify or iterate over the following n slots as per ruby array Class:
arr[x, n]

A: I am not sure I understand the question there are many methods of accessing the index for an Array e.g.
 alphabet = ('a'..'z').to_a
 alphabet[0]
 #=> "a"
 alphabet.values_at(2,3,12)
 #=> ["c","d","m"]
 alphabet.index('r')
 #=> 17
 alphabet.fetch(15)
 #=> "p"

There are many more such as #at, #find_index, even #rindex which will look for the last occurance. If you need to iterate index's you can use each_index or each_with_index. Since your question does not truely explain the scenario all I can do is explain how to deal with Array indices. For a more pertinent answer please update your question to show both data and expected results.
Here is what I can gather from your question
@product = Product.find(some_id)
@slot = @product.slot
@slots = Slot.where("id > ?", @slot.id) #return all slots after the @product.slot

A: If want to get the Slot for a given Product you can just do this:
slot = @product.slot

assuming you have your relationships well defined.


text:
Q: Editview below Listview lossing focus I have a fragment with Editview below a listview but when I clicked of the editview and soft keyboard appear the Editview losses fucus. I searched and tried all the answers in Stack Overflow but non worked. Below is fragment XML.

A: Sorry for not adding the xml. I was able to sort it out by just adding the below code inside OnCreateView
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE|WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);


text:
Q: Using SMOTE on training data I have an unbalanced dataset and I want to use SMOTE. I am working with Azure ML. I have read many examples in the Microsoft Doku page. I am wondering why the SMOTE is set before the SPLIT DATA function and not after the SPLIT DATA on the 70% dataset for training. All the examples I have seen are before the SPLIT DATA function. Is that the right usage of SMOTE?
Here an example from Microsoft:
https://imaginemedia.blob.core.windows.net/content/Lab%20PDF%20-%20Churn%20Prevention%20and%20Intervention-db9732e3e8c6.pdf


text:
Q: Perform trim function on the selected cells in VBA I am trying to figure out if there is a way I could run a simple function (TRIM to remove duplicate space characters) in an Excel macro so it is performed directly on the cell and so I don't have to create an extra column with the function that TRIMs the previous column.
It should work on selected column or just selected cells
Sub trim()

 ActiveCell.FormulaR1C1 = "=trim(R1C1)"

End Sub

A: While there is a native VBA Trim function, it only removes spaces from the left and right ends. It does not also change double spaces between words to a single space. To do that, you can use the WorksheetFunction object and the worksheet's TRIM function.
Sub myTrim()
    dim rng as range
    for each rng in Selection
        'use only one of these
        rng = Trim(rng.Value)
        rng = WorksheetFunction.Trim(rng.Value)
    next rng
End Sub

See How to avoid using Select in Excel VBA macros for more boilerplate on running code against the Application.Selection property.
For quick full column trimming, a Range.TextToColumns method works very well.
Sub myTrim2()
    Dim col As Range
    For Each col In Selection.Columns
        col.TextToColumns DataType:=xlFixedWidth, FieldInfo:=Array(0, 1)
    Next col
End Sub

This latter method does not remove internal double spaces; only leading and trailing spaces.
It is not a good idea to name your procedures and/pr functions the same as existing functions unless you intentionally want to overwrite the functionality.

A: Give this a try:
Sub TrimAndFit()
    Dim r As Range

    With Application.WorksheetFunction
    For Each r In Intersect(Selection, ActiveSheet.UsedRange)
        r.Value = .Trim(r.Value)
    Next r
    End With
End Sub

This will work on all Selected cells.  We use Intersect() to improve performance.

A: Try:
Private Sub Worksheet_Change(ByVal Target as Range)

Target.Value = Trim(Target.Value)

End Sub

This will change any cell you change in the sheet to a trimmed version of the cell value.

A: just try with immediate window

?Application.Trim(" teaspoon     ")

teaspoon

?WorksheetFunction.Trim("  teas   poon   ")

teas poon

?Trim("  tea    spoon   ")

tea    spoon

A: Will not this do the trick?
Selection.Replace What:=" ", Replacement:="", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False

Would this be slower than the intersect?


text: Q: Behavior of the giant component of an Erdos-Renyi graph near p = 1/n what is the behavior of an Erdos-Renyi random graph with p = (1 + f(n))/n with $f(n)=o(1)$? If $f(n)=0$ then it has size about $n^{2/3}$, but what if the probability is perturbed slightly, say with $f(n)=1/\log n$ or something a bit larger? (I'm interested in the answer on both sides, $\pm$.)


text:
Q: How can I set up another alias like "localhost" to point to a folder within htdocs? So I have xampp running, localhost or 127.0.0.1 will take me to htdocs within my xampp folder. Is there a way I can use a similar name such as localhost2 on the same machine to take me to folder, lets say its called localhost2, within htdocs.
The reason I am asking this is because I think I have some redirect issues. I am trying use bromine and apparently it only works needs to be at the root; however, I have other things in root, and I know there will be issues with rewrite + cake + normal folders. So i guess my work around (other than trying to fix the main rewrite issue) is to try to create a shortcut, or subdomain or something to folder I am trying to get to.
I am sure there is a better word for all of this, but I am no server admin! I hope that makes sense.
Thanks!

A: XAMPP uses Apache, right?
Yes, it's possible.
There's two things you'd need to do:

*

*Add "localhost2" to the /etc/hosts entry for localhost (if it's not there, simply add "127.0.0.1 localhost localhost2").  I'm assuming Unix of some sort.  If it's Windows there's ways to do the same thing.

*Add a virtualhost for localhost2 to the apache configuration (pointed at the other directory).


text:
Q: Как подождать боту в телеге, пока пользователь напишет сообщение Хочу добавить команду /addtown, которая будет добавлять город в панель под клавиатурой
Но как это сделать, чтобы бот подождал пока пользователь введёт этот город
@bot.message_handler(commands=["addtown"])
def send(message):

    bot.send_message(message.chat.id, "Пиши город который хочешь добавить в подклавиатурную панель".format(message.from_user, bot.get_me()), parse_mode="html")

    markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
    item1 = types.KeyboardButton(message.text)
    markup.add(item1)

    bot.send_message(message.chat.id, "Город успешно добавлен", reply_markup=markup)

A: Попробуйте этот код:
@bot.message_handler(commands=["addtown"])
def send(message):
    bot.send_message(message.chat.id, "Пиши город который хочешь добавить в подклавиатурную панель")
    bot.register_next_step_handler(message, callback=keyboard_city)

def keybord_city(message):
    markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
    item1 = types.KeyboardButton(message.text)
    markup.add(item1)
    bot.send_message(message.from_user.id, "Город успешно добавлен", reply_markup=markup)


text:
Q: ASP.NET + Rabbit MQ connection and channel lifetime I see a lot of examples of usage RabbitMq in .NET (in ASP.NET or console applications). Most of them look like this:
using (var connecttion = MyConnectionFactoryWrapper.CreateConnection())
using (var channel = connection.CreateChannel())
{
   ...
}

Is it efficient? In documentation I see:

AMQP connections are typically long-lived. AMQP is an application
  level protocol that uses TCP for reliable delivery.

So I suppose it's better to have one connection for application. Another point about channels:

AMQP 0-9-1 connections are multiplexed with channels that can be
  thought of as "lightweight connections that share a single TCP
  connection".

Here I suppose I can use channel-per-request in case of ASP.NET application. My question: is it the best practice to have connection-per-application and channel-per-request?

A: Yes, connection-per-application is a suggested approach. Channel-per-request should do as well, but I'd test it for your required throughput. For our project we used EasyNetQ which takes care of creating connections/channels for you. We just kept a single MessageBus instance for the application.


text:
Q: Android: Using the same ListView for different lists I have a 3 buttons, say LanguageButton, CountryButton and PinCodeButton.
When LanguageButton is pressed, I must display a list of languages. Similarly for CountryButton a list of countries and so on. Only one list is to be displayed at a time.
My question is whether it is better to define a single ListView in my layout or 3 separate ListViews for each list in my layout!
I tried to use a single ListView and set corresponding adapters when different buttons are pressed, i.e in onClick() of languageButton, I give setAdapter(languageArray);
But my doubt arose in implementing the onItemClick() of the list. Because what must be done whenfirst item is clicked in languageList is different from what must be done in countryList.
Hence that would add to more code in the java file.
So I am just wondering whether I should simplify my onItemClick() code by defining separate ListViews, or should I simplify my layout and add logic to code?
Regards,
Kiki

A: Personally, I would probably go with just one ListView for all three. You can just change the content of it dynamically depending on the action event.

A: I would define three different ListViews and either show/hide them as appropriate or add/remove them.  I'd prefer this over including three ListViews definitions within the same Activity due to readability purposes, and I would go so far as to create three different ListView classes, i.e. LanguageListView, CountryListView, and PinCodeListView that each define their own onItemClick method through setOnItemClickListener.  If memory is a concern down the road you can take a look at rolling the ListViews all into one Activity, but for now I'd go the route of easier upfront maintainability and good readability.

A: I would use one ListView.  Depending on which ListView you are binding, just use an IF/ELSE IF or SWITCH branches to do different actions in the OnItemClick event.


text:
Q: Php long script with client side callback I'm have a very long process in a php script (generate a huge pdf).
I have a button in my HTML page that launches the php script and I'd like to show a kind of progress bar or at least an animated gif and when the php script is over, display the generated pdf.
The generation of the pdf may last 15 minutes so the php engine exits in timeout and the browser too.
I there a way to declare a kind of client-side callback that would be invoked as soon as the server side process is over ?
Thanks for your replies
Edit :
Thanks for your replies :)
If I well understand, I must launch the process on server-side and "detach" my client i.e do not wait untill the process is over. Instead, my client should periodically check the progression of server-side process. Right ?
If so, I may use the following scenario :

*

*The client sends an ajax request to the server. The server launches
the process and returns a guid to the client. This guid identifies
the job.

*The client periodically checks the progression of the job
via an Ajax request, from its guid.

*Once the job is over, the client    can issue a last Ajax query to
download the PDF

That means that the server must save the generated PDF on its disk and wait for the final Ajax request to send the file and delete it, right ?

A: For something as long as 15 minutes, I wouldn't even use web sockets for this.  15 minutes is a long time and there's really no telling what the user is going to be doing in the meantime.  A disconnected notification process is probably going to be more reliable in this case.
Consider something like:

*

*User initiates process, whereby a record is stored in the database "queueing" the process to take place.

*User is immediately presented with a page indicating that the process has been queued and that they can continue to use the application.

*A separate application which runs periodically (every minute?  every few minutes?) checks for "queued" processes in the database, updates their status to "in-progress" (so subsequent runs don't also pick up the same records), and processes them.

*As each process completes, it's either removed from the database or updated to a "completed" status.

*The user is otherwise notified that the process is complete.

This final notification can be done a number of ways.  An email can be sent to the user, for example.  Or consider a user experience similar to the Facebook notification bar.  Each page in the website can check for "completed" processes when the page loads and present a "notification" in the UI which directs the user to the result of the process.  If users spend a lot of time on any given page then this would be a good place to use web sockets or long polling via JavaScript to keep checking for completed processes.
The main thing is to separate the user interface from the long-running process.  Web applications by design aren't suited for processes which run for that long.  By separating the concerns the web application can focus just on the user interface and the command-line application can focus on the processing.  (As an added bonus, this would prevent users from over-loading the server with too many concurrent processes.  The command-line application can just run one record at a time, so too many concurrent processes just slows down the response, not the server.)

A: as @David said, but no one has covered the progress bar, the implantation of this depends on what you know ( you being the application creating the pdf ).

*

*Do you know the size of the pdf when complete.

*Do you know how long
    it will take to generate.

*Do you have code where you can hook into
    to update the progress.

The application needs a way to know when to update the completed percentage, and by how much. If you can do that then you can either store the progress in the database with the script that crates the PDF and read it on a user facing page, or store it in a file, etc..
jQuery UI progress bar is easy to use, but you will have to know what percentage is done to be able to tell the end user.
After that it is a pretty simple matter of using ajax (jquery $.post ) and a file, that's how i do it. I just wright a simple text file with a number representing the completion percent.  Load it via ajax and feed it to the jquery ui progress widget.


text:
Q: virtualenv doesn't work on network drive on other computers I set up virtualenv on network drive using virtualenv python module. It generated me few folders: Include, Lib, Scripts, share, tcl. Inside the folder with these folders i created new one called scr and then pasted there a django app called vistool. Now i created two batch scripts, to allow other users of network drive to run this app:
run.bat (main file):
cd /d "Z:\xx\Tools\New\Widget - Graphs"
cd visual\Scripts
start server.bat
timeout 30
start http://127.0.0.1:8000/graphtool/

This one seems to work, as it does everything it should.
The other one that is called inside run.bat is server.bat, which i placed in Scripts(the same folder where activate.bat is.
server.bat (for calling activate.bat and django built-in server):
call activate.bat
cd..
cd src/vistool
call python manage.py runserver

Now, these two scripts are working fine for me and they do what they want - open a tab with a django project in the browser. But on other computers in my company this doens't work and I have no idea why. Activate.bat from virtualenv package takes the
set "VIRTUAL_ENV=Z:\xxx\Tools\New\Widget - Graphs\visual"

Which should be ok, since everyone has got mapped this network disc the same. The errors that they get are: "Could not find django". Even if i set up my env correctly and installed all the packages I use in it. And the activate.bat seems to work for them. It looks like the virtualenv can't see installed packages? But then why is it working for me?
Edit: When I try to install something on Their computers I get an error, that I don't have runpy installed. When I try to pip install runpy I still can't


text:
Q: Mensagem de sucesso com ajax com validação boostrap 4 Eu tenho esse código que funciona perfeitamente. Na pagina cadastrarFuncionario.php são feitos um INSERT no banco e um upload de uma imagem e caso haja sucesso no upload tem um echo "Upload efetuado com sucesso!"; que é apresentado na

 do HTML
$(document).ready(function () {
    // evento de "submit"
    $("#botaoCad").click(function (e) {
        // parar o envio para que possamos faze-lo manualmente.
        e.preventDefault();
        // captura o formulário
        var form = $('#form_funcionario')[0];
        // cria um FormData {Object}
        var data = new FormData(form);
        // processar
        $.ajax({
            type: "POST",
            enctype: 'multipart/form-data',
            url: "processosPHP/cadastrarFuncionario.php",
            data: data,
            processData: false, // impedir que o jQuery tranforma a "data" em querystring
            contentType: false, // desabilitar o cabeçalho "Content-Type"
            cache: false, // desabilitar o "cache"
            // manipular o sucesso da requisição
            success: function (data) {
                $("#documento_e").html(data);
            },
            // manipular erros da requisição
            error: function (e) {
                $("#documento_e").html(e);
            }
        });
    });
});

Coloquei nele uma validação boostrap 4
    $(document).ready(function () {
        // evento de "submit"
        $("#botaoCad").click(function(event) {
                // Fetch form to apply custom Bootstrap validation
                var form = $("#form_funcionario")

                if (form[0].checkValidity() === false) {
                  event.preventDefault()
                  event.stopPropagation()
                }else{
                    // cria um FormData {Object}
                    var data = new FormData(form[0]);
                    // processar
                    $.ajax({
                        type: "POST",
                        enctype: 'multipart/form-data',
                        url: "processosPHP/cadastrarFuncionario.php",
                        data: data,
                        processData: false, // impedir que o jQuery tranforma a "data" em querystring
                        contentType: false, // desabilitar o cabeçalho "Content-Type"
                        cache: false, // desabilitar o "cache"
                        // manipular o sucesso da requisição
                        success: function (data) {
                            $("#documento_e").html(data);
                        },
                        // manipular erros da requisição
                        error: function (e) {
                            $("#documento_e").html(e);
                        }
                    });

            }
            form.addClass('was-validated');

        });
    });

nesse caso, tanto o INSERT quanto o upload são executados, porém, não aparece a mensagem Upload efetuado com sucesso! na

 do HTML
OBS: O arquivo cadastrarFuncionario.php é exatamente o mesmo para os dois casos.
Como poderia ser apresentado uma mensagem no segundo caso?

A: O problema, ao meu ver, é que você está colocando a preventDefault() dentro do if. Quando seu código entra no else o preventDefault() não é acionado, alterando o estado atual e não mostrando a div com mensagem de sucesso. Na verdade a div é mostrada, mas de maneira tão rápida que não se vê pois logo depois o evento altera o estado atual.
Se você fizer isso dentro do click, irá funcionar normalmente, como antes:
event.preventDefault();
  if (form[0].checkValidity() === false) {
      event.stopPropagation()
    }else{
        // cria um FormData {Object}
        var data = new FormData(form[0]);
        // processar
        $.ajax({
            type: "POST",
            enctype: 'multipart/form-data',
            url: "processosPHP/cadastrarFuncionario.php",
            data: data,
            processData: false, // impedir que o jQuery tranforma a "data" em querystring
            contentType: false, // desabilitar o cabeçalho "Content-Type"
            cache: false, // desabilitar o "cache"
            // manipular o sucesso da requisição
            success: function (data) {
                $("#documento_e").html(data);
            },
            // manipular erros da requisição
            error: function (e) {
                $("#documento_e").html(e);
            }
        });

    }


text:
Q: C++ Process exited after 4.017 seconds with return value 3221225477 I am new to C++ and I am trying to write this simple code where I input and display employee data.
I want to pass the user input to the inputEmployee function by address, save it in an array then display it. When I get to the part of typing the employee name I get the following message "Process exited after 4.017 seconds with return value 3221225477".
Could someone please suggest a solution or explain what is wrong with my code.
I am not sure if what I'm doing is right.

struct Employee {
    char    name[30];
    char    surname[30];
    int     age;
    float   salary;
};

Employee* inputEmployee(struct Employee *emp, int n, int index) {
     Employee *employeeRecords = new Employee[n];
     employeeRecords[index] = *emp;
     return employeeRecords;
}

int displayEmployee(struct Employee *arr) {
    int arraySize = sizeof(arr)/sizeof(*arr);
    printf("\nEmployee data:");
    for(int i=0; i < arraySize; i++) {
        printf("Name: %s", arr[i].name);
        printf("Surname: %d", arr[i].surname);
        printf("Age: %d", arr[i].age);
        printf("Salary: %f\n", arr[i].salary);
    }
    return 0;
}

int main()
{
    int n = 0;
    printf("\nEnter employee number :\n");
    scanf("%d", &n);
    struct Employee *eArr;

    for(int i=0; i<n; i++) {
        struct Employee *emp = NULL;

        printf("\nEnter employee data :\n");
        printf("Name ?:"); scanf("%s", emp->name);
        printf("Surname ?:"); scanf("%s", emp->surname);
        printf("Age ?:"); scanf("%d", &emp->age);
        printf("Salary ?:"); scanf("%f", &emp->salary);
        eArr = inputEmployee(emp, n, i);
    }

    displayEmployee(eArr);

    return 0;
}

A: You should go a step back and read something about memory management, arrays, pointers and references in C++. This is a hard part, you have to learn, when you want to program C++. You should definitely read some more articles.
Learning-by-doing is only half the the way to go here. You need to understand what happens in the background. Your program can do 'something', even if it seems okay, it could fail badly later on. But keep your head up on go on.

Employee *emp = NULL; creates a pointer to 'nowhere' in your memory. The least thing you have to do, is Employee *emp = new Employee();. This will allocate memory you can use for your data. Please keep in mind, that you have to use the delete operator for each allocated memory.
I tried to fix your code. I allocated memory for the whole array.
#include <cstdio>

struct Employee
{
  char name[30];
  char surname[30];
  int age;
  float salary;
};

//--------------------------------------------------------------------------//
int displayEmployee(Employee *arr, int count)
{
  printf("\nEmployee data:");
  for (int i = 0; i < count; i++)
  {
    printf("Name: %s ", arr[i].name);
    printf("Surname: %s ", arr[i].surname);
    printf("Age: %d ", arr[i].age);
    printf("Salary: %f\n", arr[i].salary);
  }
  return 0;
}

//--------------------------------------------------------------------------//
int main()
{
  int n = 0;
  printf("\nEnter employee number: \n");
  scanf("%d", &n);

  Employee *eArr = new Employee[n];
  for (int i = 0; i < n; i++)
  {
    Employee &emp = eArr[i];

    printf("\nEnter employee data :\n");
    printf("Name ?: ");
    scanf("%s", emp.name);
    printf("Surname ?: ");
    scanf("%s", emp.surname);
    printf("Age ?: ");
    scanf("%d", &(emp.age));
    printf("Salary ?: ");
    scanf("%f", &(emp.salary));
    // eArr = inputEmployee(emp, n, i);
  }
  displayEmployee(eArr, n);

  delete[] eArr;
  return 0;
}

A: You already have a fine answer, but there are several additional points you must cover in order to have any confidence in your input routine. Primarily, you must validate every user input and you must empty stdin of any additional characters before the next input. Ask your self what would happen if you entered "Ninety One" for Age? Clearing stdin can be done with a simple loop continuing with your C-stye input or using std::cin.ignore() if using iostream.
For example, when you loop to collect the employee data, you must force the user to enter valid input for each variable before moving on the store the next, e.g.
    for (int i = 0; i < n; i++) {   /* loop for input of n empoloyees */
        struct Employee emp;

        puts ("\nEnter employee data :");
        for (;;) {  /* loop continually until valid input received */
            fputs ("\n  Name ?: ", stdout);     /* prompt (fputs for \n control) */
            int rtn = scanf("%s", emp.name);    /* save return from scanf */
            if (rtn == EOF) {                   /* check for manual EOF */
                puts ("(user canceled input)");
                return 0;
            }   /* remove any extraneous characters from stdin */
            for (char c = getchar(); c != '\n' && c != EOF; c = getchar()) {}
            if (rtn == 1)                       /* if good input break loop */
                break;
        }

You must add an additional check when handling numeric-input to cover the matching-failure case, e.g.
        for (;;) {  /* ditto for Age, but note the additional validation required */
            fputs ("  Age ?: ", stdout);
            int rtn = scanf ("%d", &emp.age);
            if (rtn == EOF) {
                puts ("(user canceled input)");
                return 0;
            }
            for (char c = getchar(); c != '\n' && c != EOF; c = getchar()) {}
            if (rtn == 1)
                break;
            fputs ("error: invalid integer input.\n", stderr);
        }

If you have a requirement that the number enter be within a particular rage, you can add an additional check such as if (emp.age < 16 || emp.age > 80) handle the error for an invalid age.
For output, you do not need multiple printf(or std::cout) calls -- one will do, e.g.
/* No return, you must pass number of elements as second parameter */
void displayEmployee (struct Employee *arr, int n)
{
    puts ("\nEmployee data:");      /* no conversion, just use puts */

    for (int i=0; i < n; i++)       /* only 1 printf needed */
        printf ("\n  Name: %s\n  Surname: %s\n  Age: %d\n  Salary: %.2f\n",
                arr[i].name, arr[i].surname, arr[i].age, arr[i].salary);
}

Also note there is no reason to return a value from displayEmployee, it is simply an output function and there is nothing to return to indicate success or failure of an operation within the function.
Putting it altogether, you could do:
#include <cstdio>

#define MAXN 30

struct Employee {
    char    name[MAXN];
    char    surname[MAXN];
    int     age;
    float   salary;
};

/* No return, you must pass number of elements as second parameter */
void displayEmployee (struct Employee *arr, int n)
{
    puts ("\nEmployee data:");      /* no conversion, just use puts */

    for (int i=0; i < n; i++)       /* only 1 printf needed */
        printf ("\n  Name: %s\n  Surname: %s\n  Age: %d\n  Salary: %.2f\n",
                arr[i].name, arr[i].surname, arr[i].age, arr[i].salary);
}

int main()
{
    int n = 0;
    fputs ("\nEnter employee number : ", stdout);
    if (scanf ("%d", &n) != 1) {                    /* validate every input */
        fputs ("error: invalid integer input.\n", stderr);
        return 1;
    }
    struct Employee *eArr = new struct Employee[n]; /* allocate */

    for (int i = 0; i < n; i++) {   /* loop for input of n empoloyees */
        struct Employee emp;

        puts ("\nEnter employee data :");
        for (;;) {  /* loop continually until valid input received */
            fputs ("\n  Name ?: ", stdout);     /* prompt (fputs for \n control) */
            int rtn = scanf("%s", emp.name);    /* save return from scanf */
            if (rtn == EOF) {                   /* check for manual EOF */
                puts ("(user canceled input)");
                return 0;
            }   /* remove any extraneous characters from stdin */
            for (char c = getchar(); c != '\n' && c != EOF; c = getchar()) {}
            if (rtn == 1)                       /* if good input break loop */
                break;
        }
        for (;;) {  /* ditto for Surname */
            fputs ("  Surname ?: ", stdout);
            int rtn = scanf("%s", emp.surname);
            if (rtn == EOF) {
                puts ("(user canceled input)");
                return 0;
            }
            for (char c = getchar(); c != '\n' && c != EOF; c = getchar()) {}
            if (rtn == 1)
                break;
        }
        for (;;) {  /* ditto for Age, but note the additional validation required */
            fputs ("  Age ?: ", stdout);
            int rtn = scanf ("%d", &emp.age);
            if (rtn == EOF) {
                puts ("(user canceled input)");
                return 0;
            }
            for (char c = getchar(); c != '\n' && c != EOF; c = getchar()) {}
            if (rtn == 1)
                break;
            fputs ("error: invalid integer input.\n", stderr);
        }
        for (;;) {  /* ditto for Salary with same note */
            fputs ("  Salary ?: ", stdout);
            int rtn = scanf ("%f", &emp.salary);
            if (rtn == EOF) {
                puts ("(user canceled input)");
                return 0;
            }
            for (char c = getchar(); c != '\n' && c != EOF; c = getchar()) {}
            if (rtn == 1)
                break;
            fputs ("error: invalid floating-point input.\n", stderr);
        }
        eArr[i] = emp;  /* simply assign struct to element */
    }

    displayEmployee(eArr, n);

    return 0;
}

Example Use/Output
$ ./bin/empstruct

Enter employee number : 3

Enter employee data :

  Name ?: Mickey
  Surname ?: Mouse
  Age ?: 91
  Salary ?: 88.82

Enter employee data :

  Name ?: Minnie
  Surname ?: Mouse
  Age ?: 88
  Salary ?: 93.25

Enter employee data :

  Name ?: Goofy
  Surname ?: Dog
  Age ?: 85
  Salary ?: Bone and Treats
error: invalid floating-point input.
  Salary ?: .25

Employee data:

  Name: Mickey
  Surname: Mouse
  Age: 91
  Salary: 88.82

  Name: Minnie
  Surname: Mouse
  Age: 88
  Salary: 93.25

  Name: Goofy
  Surname: Dog
  Age: 85
  Salary: 0.25

Try entering an invalid input for either Age or Salary with your current code and see what happens (have your fingers hovering over Ctrl+c when you do... or see which input appears to be skipped)
Also, you should pick either C or C++. What you have is a C program that uses new instead of malloc for allocation. If you replace your allocation with new with struct Employee *eArr = malloc (n * sizeof *eArr); then you have a pure C program. There is nothing invalid about mixing the languages, but it is not looked upon well.
Let me know if you have any further questions.


text:
Q: R Shiny: how to link checkbox input in ui.R to observe function in server.R? I am trying to create a checkbox input in a Shiny app that allows the data product user to select all options available, select/deselect options one at a time, and throw an error message when all options in the checkbox group are deselected. I am able to get the actionLink input in my ui.R file working, where all options are selected or deselected when the user clicks 'Select All' and the plot updates with the correct values. However, when the user deselects options one at a time, I occasionally get an error and warning message, and the plot does not update.
From what I can tell, every other time the "Social" option is selected/deselected, the console throws an error and warning message and the plot does not update, then if the user selects/deselects the "Social" option again, the plot updates and no error/warning messages are thrown.
I wonder if this has something to do with the way I've set up the observe function in my server.R file, with the data frame manipulations I've done in the reactive expression for 'ssDf', or how I've defined the 'channels_input' reactive expression.
Below is an abstract from my ui.R file.
channel_chr <- list("Display" = "Display", "Paid Search" = "Paid Search", "Organic Search" = "Organic Search",
                "Email" = "Email", "Social" = "Social", "Direct" = "Direct", "Referral" = "Referral",
                "Affiliate" = "Affiliate")

fluidPage(sidebarLayout(
  sidebarPanel(

  ## Other inputs

    checkboxGroupInput("channel", label = "Channel(s)",
                       choices = channel_chr,
                       selected = as.character(channel_chr)),
    actionLink("selectall","Select All"),

  ## Other inputs

  ),
  mainPanel(
    uiOutput("plot_ui"),
    ggvisOutput("plot")

  )
))

And a relatively small section from my server.R file is below.
channel_chr <- list("Display" = "Display", "Paid Search" = "Paid Search", "Organic Search" = "Organic Search",
                 "Email" = "Email", "Social" = "Social", "Direct" = "Direct", "Referral" = "Referral",
                 "Affiliate" = "Affiliate")

shinyServer(function(input, output, session) {

    # If "Select All" is chosen in ui.R for input$selectall, select all checkboxes in input$channel
    observe({
            if (input$selectall == 0) {
                ## I tried keeping this blank and return(NULL), but saw no difference
            } else if (input$selectall > 0 & input$selectall %% 2 == 0) {
                updateCheckboxGroupInput(session,"channel","Channel(s)",choices=channel_chr,
                                         selected=as.character(channel_chr))
            } else if (input$selectall %% 2 == 1) {
                updateCheckboxGroupInput(session,"channel","Channel(s)",choices=channel_chr,
                                     selected=c("Display"))
            }
    })

    channels_input <- reactive ({
        temp_chr <- character(length=length(channel_chr))
        temp_channel <- input$channel
        temp_chr[1:length(temp_channel)] <- temp_channel
        return(temp_chr)
    })

# A subset of original data frame as reactive function
ssDf <- reactive({

    ## contains dplyr, plyr, and ddply manipulations of data frame
    ## according to the user's interactions with ui.R.

    ## One example of data frame manipulation in ssDf() reactive function
    ## based on user inputs, and using if/else condition statements

    else if (input$[inputB] == [option1] & all(sort(channels_input())!=sort(as.character(channel_chr)))) {

            ## If channels_input() != channel_chr { filter only those channels where Channel==channels_input() }
            filteredDat2 <- dplyr::filter(filteredDat, Channel==channels_input()[1])
            for (i in 2:length(channels_input())) {
                if (channels_input()[i] != "") {
                    filteredDat2 <- rbind(filteredDat2, dplyr::filter(filteredDat,
                                                                      Channel==channels_input()[i]))
                }
            }
            filteredDat2 <- ddply(filteredDat2, .(Date, [Column2]), summarize, sum_[Variable1]=sum([Variable1]),
                                 [Variable2]=weighted.mean([Variable2], [Variable1]),
                                 [Variable3]=weighted.mean([Variable3], [Variable1]),
                                 [Variable4]=weighted.mean([Variable4], [Variable1]),
                                 [Variable5]=weighted.mean([Variable5], [Variable1]))
            ## Subsequent manipulations removed for brevity.
            return(filteredDat2)
})

ssDf %>%
    ggvis(~Date, ~[Variable4], stroke = ~TimePeriod) %>%
    layer_lines() %>%
    add_axis("y", title = [Variable4], title_offset = 50) %>%
    scale_datetime("x", domain=c(startNowDate, endNowDate)) %>%
    add_tooltip(all_values, "hover") %>%
    bind_shiny("plot", "plot_ui")

Note that I replaced some of my column, variable, and input names with [Column2], [Variable4], etc. for the sake of this post. Also, my tooltip function is not yet functional, so ignore the all_values function within the add_tooltip function in the ggvis pipeline.
Any help with identifying where I went wrong or tips for debugging complex Shiny apps with ggvis would be much appreciated.
Thank you.


text:
Q: Unable to load application or execute command 'Microsoft.Dnx.TestHost'. Available commands: test Trying to test an ASPNET 5 application in VS2015.
{
  "version": "1.0.0-*",
  "description": "HoldingTank Class Library",
  "dependencies": {
    "EntityFramework.InMemory": "7.0.0-rc1-final",
    "FluentAssertions": "4.1.1",
    "GenFu": "1.0.4",
    "MyMVCProject": "1.0.0-*",
    "xunit": "2.1.0",
    "xunit.runner.visualstudio": "2.1.0"
  },
  "commands": {
    "test": "xunit.runner.dnx"
  },
  "frameworks": {
    "dnx451": { }
  }
}

However, no tests show up in the Test Explorer window and when I hit F5 I get:
------ Discover test started ------
------ Test started: Project: HoldingTank ------
Starting  Microsoft.Dnx.TestHost [C:\Users\erik\.dnx\runtimes\dnx-clr-win-x86.1.0.0-rc1-update1\bin\dnx.exe --appbase "C:\code\PortalSolution\src\HoldingTank" Microsoft.Dnx.ApplicationHost --port 52620 Microsoft.Dnx.TestHost --port 56351 --parentProcessId 8368]

Error: Unable to load application or execute command 'Microsoft.Dnx.TestHost'. Available commands: test.
Unable to start Microsoft.Dnx.TestHost
   ========== Discover test finished: 0 found (0:00:01.8238001) ==========

I just have one test, decorated with [Fact] but it doesn't look like it is getting that far.
Looking at similar questions that have "unable to load" errors (but couldn't find any specific to TestHost), I've tried making sure that both the test project and the application target the same frameworks, but couldn't find any discrepancies. And I don't see anything in the Event Log.
Any suggestions? - not even sure where to go to start to troubleshoot this.

A: You have to add the "xunit.runner.dnx" as dependency instead of the "xunit.runner.visualstudio". Then it will work in VisualStudio.
Since ASP.Net 5 is in beta, so is xunit.runner.dnx. Use the current pre-release which matches ASP.Net RC1 ... I currently use 2.1.0-rc1-build204 with ASP.Net 5 RC1


text:
Q: RxJava2 Flowable.create blockingSubscribe semantics with BackpressureStrategy I'm having some difficulty understanding how the Flowable BackpressureStrategy works with the blockingSubscribe method - or it seems unexpected to me and would appreciate if someone could explain it to me.
I was testing this code in the FlowableTests file in current trunk.
@Test
public void testCreateBackpressureDrop() {
    Flowable.create(new FlowableOnSubscribe<Integer>() {
        @Override
        public void subscribe(FlowableEmitter<Integer> e) throws Exception {
            e.onNext(1);
            e.onNext(3);
            e.onNext(4);
            e.onComplete();
        }
    }, BackpressureStrategy.DROP).blockingSubscribe(w);

    verify(w, times(1)).onNext(1);
    verify(w, times(1)).onNext(3);
    verify(w, times(1)).onNext(4);
    verify(w, times(1)).onComplete();
}

If I use subscribe(w) and BackpressureStragegy.DROP or Backpressure.BUFFER the test passes.  However if I use blockingSubscribe(w), Backpressure.BUFFER passes but Backpressure.DROP fails saying the onNext(1) was never called.
Thanks!

A: This is a typical problem with using Mockito to mock a Subscriber: you have to call request(N) in its onSubscribe:
@SuppressWarnings("unchecked")
public static <T> Subscriber<T> mockSubscriber() {
    Subscriber<T> w = mock(Subscriber.class);

    Mockito.doAnswer(new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock a) throws Throwable {
            Subscription s = a.getArgument(0);
            s.request(Long.MAX_VALUE);
            return null;
        }
    }).when(w).onSubscribe((Subscription)any());

    return w;
}

The complication with blockingSubscribe is that it executes the w.onSubscribe above after the FlowableOnSubscribe has run.


text:
Q: How to make corrections to a git project created in a wrong directory -- if it is one level up and that means it includes other repos? If I have a directory called code, inside my home directory:
~/code

and then there are tiny projects, and each one is a git repository with the remote repo on either github or gitlab:
~/code/TryAngularJS
~/code/TryReactJS

Now I created a TryNodeJS project, but mistakenly, instead of being inside of
~/code/TryNodeJS

and do
git init
git remote add origin git@gitlab.com:mike/TryNodeJS.git
git add .
git commit

I actually did it in ~/code, which is one level up.  So in other words, I created a repo that includes other tiny repos.
In this case, how do I fix / correct the mistake from this point on?
I think I have to do things on the local computer as well as on gitlab because I already git remote add? (I didn't git push -u origin master yet)

A: *

*Delete the .git folder in the root folder

*cd into the inner folder where you want git to be

*git init again with the script that you just posted above.
// Delete wrong git folder
rm -rf ~/code/.git

// go into the right folder
cd ~/code/TryNodeJS

// init it as git repository
git init

// Add origin (remote)
git remote add origin git@gitlab.com:mike/TryNodeJS.git

// add and commit all files
git add .

// Commit the changes.
git commit

I think I have to do things on the local computer as well as on gitlab ...
    (I didn't git push -u origin master yet)

Since you did not pushed yet there is no code on the remote so no harm was done.
Simlpy create the git project in the new location and you are good to commit and push

if yo ualready pushed (which you did not)
In this case you simply need to overwrite the remote data with the -f flag
// Overwrite any existing data in the remote server
git push origin -f master


text:
Q: Что означает этот синтаксис? С++ В своих поисках наткнулся на вот такую функцию:
template<class T>
class Maybe : // ....

// ....

template <class M>
Maybe<M> fetch(M T::*mem_ptr) {
   return (bool(t)) ? Maybe<M>((*t).*mem_ptr) : Maybe<M>() ;
}

И не могу понять, что означает синтаксис M T::*mem_ptr? Как он называется и где можно про него почитать?


text:
Q: Commutator of vector fields (related to spherical coordinates) I'm reading the book Gravitation (Misner, Thorne and Wheeler), and going over some of the exercises. The exercise that I'm particularly interested in at the moment is Exercise 9.7, which poses the following question:

Compute the commutator $[e_{\hat{\theta}},e_{\hat{\phi}}]$ of the vector fields
  $$e_{\hat{\theta}}=\frac{1}{r}\frac{\partial}{\partial\theta},\space\space\space e_{\hat{\phi}}=\frac{1}{r\sin\theta}\frac{\partial}{\partial\phi}.$$
  Express your result as a linear combination of $e_{\hat{\theta}}$ and $e_{\hat{\phi}}$.

The book has been interchangeably using the notation that partial derivative operators are equal/equivalent to basis vectors. As a result I'm treating $\frac{\partial}{\partial\theta}$ as $e_{\theta}$, and $\frac{\partial}{\partial\phi}$ as $e_{\phi}$ (I'm not sure if I'm abusing notation here accidently). Also, since only $\theta$ and $\phi$ "vector fields" have been provided should I make the assumption that the coordinate index corresponding to $r$ is not being summed over for repeated dummy indices $\alpha$ and $\beta$. I figure that even if it was to be summed over, it wouldn't contribute any non-vanishing terms as $r$ is orthogonal to $\theta$ and $\phi$ (?).
I've attempted to find the commutator by substituting $e_{\hat{\theta}}$ and $e_{\hat{\phi}}$ into a formula provided in a previous section (eq. 9.20) where the commutator of vectors $u$ and $v$ was derived:
$$[u,v]=(u^\alpha v^\beta_{,\alpha}-v^\alpha u^\beta_{,\alpha})\frac{\partial}{\partial x^\beta}$$
Below is what I've tried so far:
$$[e_{\hat{\theta}},e_{\hat{\phi}}]=\left[\left(\frac{1}{r}e_\theta\right)^{\alpha}\left(\frac{1}{r\sin\theta}e_\phi\right)^{\beta}_{,\alpha}-\left(\frac{1}{r\sin\theta}e_\phi\right)^{\alpha}\left(\frac{1}{r}e_\theta\right)^{\beta}_{,\alpha}\right]\frac{\partial}{\partial x^\beta}$$
At this next line I suspect I might be slightly abusing notation by replacing $\alpha$ in the first and second term with $\theta$ and $\phi$ respectively to indicate the component:
$$=\left[\left(\frac{1}{r}e_\theta\right)^{\theta}\left(\frac{1}{r\sin\theta}e_\phi\right)^{\beta}_{,\theta}-\left(\frac{1}{r\sin\theta}e_\phi\right)^{\phi}\left(\frac{1}{r}e_\theta\right)^{\beta}_{,\phi}\right]\frac{\partial}{\partial x^\beta}$$
$$=\left[\left(\frac{1}{r}\right)\left(\frac{1}{r\sin\theta}e_\phi\right)^{\beta}_{,\theta}-\left(\frac{1}{r\sin\theta}\right)\left(\frac{1}{r}e_\theta\right)^{\beta}_{,\phi}\right]\frac{\partial}{\partial x^\beta}$$
Expressing the two indices of $\beta$ explicitly:
$$=\left[\left(\frac{1}{r}\right)\left(\frac{1}{r\sin\theta}e_\phi\right)^{\phi}_{,\theta}-\left(\frac{1}{r\sin\theta}\right)\left(\frac{1}{r}e_\theta\right)^{\phi}_{,\phi}\right]\frac{\partial}{\partial \phi}+\left[\left(\frac{1}{r}\right)\left(\frac{1}{r\sin\theta}e_{\phi}\right)^{\theta}_{,\theta}-\left(\frac{1}{r\sin\theta}\right)\left(\frac{1}{r}e_\theta\right)^{\theta}_{,\phi}\right]\frac{\partial}{\partial \theta}$$
$$=\left[\left(\frac{1}{r}\right)\left(\frac{1}{r\sin\theta}\right)_{,\theta}-\left(\frac{1}{r\sin\theta}\right)(0)_{,\phi}\right]\frac{\partial}{\partial \phi}+\left[\left(\frac{1}{r}\right)(0)_{,\theta}-\left(\frac{1}{r\sin\theta}\right)\left(\frac{1}{r}\right)_{,\phi}\right]\frac{\partial}{\partial \theta}$$
$$=\left[\left(\frac{1}{r}\right)\left(\frac{1}{r\sin\theta}\right)_{,\theta}\right]\frac{\partial}{\partial \phi}+\left[-\left(\frac{1}{r\sin\theta}\right)\left(\frac{1}{r}\right)_{,\phi}\right]\frac{\partial}{\partial \theta}$$
Assuming $\frac{1}{r}$ is constant with respect to $\phi$, causing the second term to vanish:
$$=\left[\left(\frac{1}{r}\right)\left(\frac{1}{r\sin\theta}\right)_{,\theta}\right]\frac{\partial}{\partial \phi}=\left[\left(\frac{1}{r}\right)\left(-\frac{r\cos\theta}{r^2\sin^2\theta}\right)\right]\frac{\partial}{\partial \phi}=-\frac{\cos\theta}{r^2\sin^2\theta}\frac{\partial}{\partial \phi}$$
$$\therefore [e_{\hat{\theta}},e_{\hat{\phi}}]=-\frac{\cos\theta}{r\sin\theta}\frac{1}{r\sin\theta}\frac{\partial}{\partial \phi}=-\frac{1}{r}\cot\theta \space e_{\hat{\phi}}$$
I have no one to check this with and was hoping someone could take a look on here. Thanks in advance!

A: You are making hard work of this: $[e_\theta,e_\phi]=e_\theta e_\phi-e_\phi e_\theta$. Let's see what this differential operator does to a function $f$.
$$e_\theta e_\phi f=\frac1r\frac{\partial}{\partial\theta}\frac1{r\sin\theta}
\frac{\partial f}{\partial\phi}=\frac1{r^2\sin\theta}
\frac{\partial^2 f}{\partial\theta\,\partial\phi}-\frac{\cos\theta}{r^2\sin^2\theta}\frac{\partial f}{\partial\phi}$$
while
$$e_\phi e_\theta f=\frac1{r\sin\theta}\frac{\partial}{\partial\phi}\frac1r
\frac{\partial f}{\partial\theta}=\frac1{r^2\sin\theta}
\frac{\partial^2 f}{\partial\phi\,\partial\theta}$$
so that
$$[e_\theta,e_\phi]f=-\frac{\cos\theta}{r^2\sin^2\theta}\frac{\partial f}{\partial\phi}=-\frac{\cot\theta}re_\phi f.$$


text:
Q: nhibernate mapping by code approach, mapping object I have following model
public class Car : Entity<int>
{
    public virtual int Id{ get; set; }
    ...
    public virtual Engine Engine { get; set; }

}

and I'm using nhibernate mapping by code approach
public class CarMap : ClassMapping<Car>
{
    public CarMap()
    {
        Id(x => CarId, m => m.Generator(Generators.Identity));
        // how map reference Engine?
        **// edit**
        HasOne(x=>x.Engine, m=>{}) // is this good enough?

    }
}

how map Engine in this CarMap object?

A: You need a little more information in the question, but here's a couple of options.
Is this really a one to one relationship?  One to one relationships are somewhat unique in that both sides of the relationship tend to share the same Id.  Like David Osborne said you most likely want a One to Many relationship.  But you you want it to be bi-directional?  i.e.  you can navigate down from the Engine to all the cars that may have that engine or up from the car to a specific engine.  i.e. engine is Chrysler Hemi engine 5.7L and it is in the cars, Ram Pickup, Dodge Durango, Dodge Charger.
Then you may want to map the objects like this
public class Engine : Entity<int>
{
    public Engine()
    {
        Cars = new List<Car>();
    }

    public virtual int Id { get; protected set; }
    public virtual decimal Displacement { get; set; }
    //more properties

    public virtual IList<Car> Cars { get; }

    public virtual void AddCar(Car car)
    {
        if (Cars.Contains(car)) return;

        Cars.Add(car);
    }

    public virtual void RemoveCar(Car car)
    {
        if (!Cars.Contains(car)) return;

        Cars.Remove(car);
    }
}

public class Car : Entity<int>
{
    public virtual int Id { get; set; }
    public virtual Engine Engine { get; set; }

}

So if you are mapping the Engine you need to define the Cars mapping list this
        Bag(x => x.Cars, map =>
        {
            map.Key(k => k.Column(col => col.Name("EngineId")));
            map.Cascade(Cascade.All | Cascade.DeleteOrphans); //optional
        },
            action => action.OneToMany());

and the other side of the relationship like this
        ManyToOne(x => x.Engine, map =>
        {
            map.Column("EngineId");
            map.NotNullable(true); // if you require the Engine to be in a car
        });

If you just want a one way mapping from the car to the engine, just remove all the references to the Cars list and delete the Bag mapping.

A: Using Fluent NH, I would use References(), which has a mapping-by-code equivalent of ManyToOne() apparently.


text:
Q: PHP call-time pass-by-reference It seems that the error I' posting about is quite common indeed, but as I know very little of php, I need to ask you shed further light on the following problem.
On my website, after a Wordpress update, the following error is displayed:
Fatal error: Call-time pass-by-reference has been removed in [...website...] on line 4.
Actually, the file the error refers t has the following code:
if (!empty($catid)) {
$Anno=0;
$Mese=0;
Pasw13_MeseAnnoCorrenti(&$Anno,&$Mese);
$ArchiviMesiAnno=Pasw13_ElencoAnniMesi("mesi",$catid,$Anno);
$ArchiviAnni=Pasw13_ElencoAnniMesi("anni",$catid,$Anno);
if (!empty($ArchiviMesiAnno) Or !empty($ArchiviAnni)){

As I've said, the error is on line 4, but I can't solve it out.
Thanks in advance for your help
Regards
kowalski215

A: This error happens because of &$in function call which is deprecated, remove & and your code should work.
Meaning that you should change:
Pasw13_MeseAnnoCorrenti(&$Anno,&$Mese);

to
Pasw13_MeseAnnoCorrenti($Anno,$Mese);

More information about error happening with wordpress can be found here - link


text:
Q: WPF C# Get Visibility of Object I have a hidden label and text field. I can make it visible but if I try to hide it later it doesn't work, I get a null reference error.
if (SMTPAuthValue != "None")
{
    lblSMTPAccount.Visibility = System.Windows.Visibility.Visible;
    comboSMTPAccount.Visibility = System.Windows.Visibility.Visible;
}
else
{
    if (lblSMTPAccount.Visibility == System.Windows.Visibility.Visible)
    {
        lblSMTPAccount.Visibility = System.Windows.Visibility.Hidden;
        comboSMTPAccount.Visibility = System.Windows.Visibility.Hidden;
    }
}

I do not know how to get the visibility property and compare its current state. If you could help me correct the code or succinctly explain why its not working and where I can read more on WPF and C# to better understand why this is not working, I would appreciate that help too.

A: If the NullReferenceException is sourced from the code provided then lblSMTPAccount or comboSMTPAccount must be null. Otherwise the exception is from code not included in your question.


text:
Q: How to get the current page in view? Is there a way to access the "current page number" (which is a parameter in a method inside my controller class) inside a view without sending it from controller via the View(modelWithCurrentPageAndOtherParameters) method? Does something like Context.Current.Page exist?
Example:
If I access this url for example: https://example.com/products/page/3
How can i get the number 3 within the view?

A: please try either of the following solutions
@Request.Params["paramName"] or
@ViewContext.RouteData.Values["id"]

A: In order to get the request parameter, you'd have to set it in the controller either via the view's model or via the ViewBag in order for it to be accessible to the view. E.g.;
public ActionResult Test(string parameterName)
{
    ViewModelSample model = new ViewModelSample();
    model.Value = parameterName;
    return View(model);
}

and in your view you'd have;
@model ViewModelSample

@Model.Value

Alternatively you could have in your controller;
ViewBag.ParameterName = parameterName;

And in the view;
@ViewBag.ParameterName


text:
Q: Serving lots of small files? I am building a website which depends on serving lots of little mp3 files (approx 10-15KB each) quite quickly. Each file contains a word pronunciation, and 20-30 per user will be downloaded every minute they are using the site. Each user might download 200 a day, and I anticipate 50 simultaneous users. There will be approx. 15,000 separate file eventually.
What would be the best way to store, manage, call and play these files as required? Will I need specialist hosting to deal with all the little files, or will they behave happily in one big folder (using a standard host)? Any delays will ruin the feel.

Update
Having done a bit more searching, I think the problem could be solved with either:

*

*A service like Photobucket but for audio instead, with its own API

*Some other sort of 'bucket hosting' solution where you can upload thousands of files at a reasonable cost, and call for them easily

Does anyone know of such a product?

A: 15k Files in one directory should not be a problem for any modern file system. It surely isn't for NTFS. What you don't want to do is open up a folder that contains 100k+ files in explorer or something similar, because populating the list-box (GUI) is a killer. Also you wouldn't want to iterate over the contents of such a folder repeatedly. However just accessing a file if you know the filename (path) is still very fast, and a server usually does just that.
The frequency doesn't sound too scary too. 50 users * 30 requests/minute/user is 25 requests per second. That's not something you can ignore completely, but any decent web-server should be able to serve files at that rate. Also I see no need for a specialized in-memory server/database/data-store. Every OS has a file-cache, and that should take care of having frequently accessed files in memory.
If you must guarantee low (worst-case) latency, you might still need an in-memory data-store. But then again if you must guarantee latency, things become complicated anyway.
One last thing: think about reverse proxies. I find it very convenient to be able to primarily store/update data in just one place (of my choosing), and have reverse proxies take care of the rest. If your files never change (i.e. same URL means same data) this is a very easy way to provide really good scalability. If the files indeed can chance, just make it so that they can not :) e.g. by encoding the change-date into the filename (and deleting the "old versions").

A: If you want (or need) to store the files on disk instead of as BLOBs in a database, there are a couple of things you need to keep in mind.
Many (but not necessarily all) file systems don't work too well with folders containing many files, so you probably don't want to store everything in one big folder - but that doesn't mean you need specialist hosting.
The key is to distribute the files into a folder hierarchy, based on some hash function. As an example, we'll use the MD5 of the filename here, but it's not particularly important which algorithm you use or what data you are hashing, as long as you're consistent and have the data available when you need to locate a file.
In general, the output of a hash function is formatted as a hexadecimal string: for example, the MD5 of "foo.mp3" is 10ebb1120767e9de166e0f5905077cb1.
You can create 16 folders, one for each of possible hexadecimal characters - so you have a directory 0, one named 1, and so on up to f.
In each of those 16 folders, repeat this structure, so you have two levels. (0/0/, 0/1/,... , f/f/)
What you then do is simply to place the file in the folder dictated by its hash.  You can use the first character to determine the first folder, and the second character to determine the subfolder. Using that scheme, foo.mp3 would go in 1/0/, bar.mp3 goes in b/6/, and baz.mp3 goes in 1/b/.
Since these hash functions are intended to distribute their values evenly, your files will be distributed fairly evenly across these 256 folders, which reduces the number of files in any single folder; statistically, 15000 files would result in an average of nearly 60 per folder which should be no problem.
If you're unlucky and the hash function you chose ends up clumping too many of your files in one folder anyway, you can extend the hierarchy to more than 2 levels, or you can simply use a different hash function. In both cases, you need to redistribute the files, but you only need to do that once, and it shouldn't be too much trouble to write a script to do it for you.
For managing your files, you will likely want a small database indexing what files you currently have, but this does not necessarily need to be used for anything other than managing them - if you know the name of the file, and you use the filename as input to your hash function, you can just calculate the hash again and find its location that way.

A: I would serve these from an in memory database  15ksize * 15000 = 225Mb of raw data, even with significant overhead it will easily fit in a medium hosting plan. The disk based caches might be elegant here, e.g. memcachedb, ehcache or similar then you only have one API and some configuration.
You should warm up the cache though on startup.
The metadata can be in a mysql or similar. You might keep a mastercopy there too for easier management and as a backend for the cache.


text:
Q: (continue , break) (equality operator , inequality operator) in this Javascript example? I wonder what is the difference between (!==) and (===) in this example, and what is the difference between break and continue??!
In this example I thought that it would print out only the strings, but it prints out every data type except strings.
I know the use of (!== and ===) but in this example it seems strange for me.
Please give an explanation of the use of (!== and ===) also (continue and break) in this example.
var array = [1, 2, "hello", true];

for(let i = 0; i < array.length; i++) {
    if(typeof array[i] === "string") continue;

    console.log(array[i]);
};

A: In the example you gave if the typeof element is String it will not execute rest of statements in loop but continue with the next iteration. If there would have been break it will break out of loop and not execute any further iterations.

A: The continue keyword causes the loop to move forward to the next iteration without executing any of the statements in the loop body after it.
=== is used for strict equality comparison, i.e. two values are only considered the same if they are of the same type and have the same value (no type coercion is done).
The code you have shown is checking if the array element at each index is a string and if so, it is moving on to the next iteration of the loop without printing it.
The code can be rewritten as follows:
for(let i = 0; i < array.length; i++) {
    if(typeof array[i] !== "string") console.log(array[i]);
};

A: In your example, it will continue the execution to the next iteration if the type is equal to the string.
But the array has only one element with type string because of this it prints the other 3 elements.

*

*Equal to the operator(===) is a strict comparison operator. It checks/compare type of data with its content.

*Not (!) - It just inverts the operation, in your case, it checks for not equal to(!==)

*Continue - continue keyword will take you to the next iteration by skipping any lines of code below it.

*Break - break keyword will take you to out of the loop by skipping any further iterations.


text:
Q: suitable http status code to respond with in case you want to "warn" user? In my app there's a number of actions after which I want to "warn" user that something, that he might want to rollback, has happened. Basically, I show the short version of this warning before user submits his request so it's more for assurance ( user knows what he's doing ).
I use to render json notification with a bunch of other details from server with the appropriate status code, so that javascript then places notification accordingly ( like, if 201 then place json notification to 'green' div, if 422 then place it to 'red' div ).
So the question is, what might be the 'best fit' status code for 'yellow' div? Thanks!

A: How about:
203 Non-Authoritative Information


text:
Q: Two jars are shuffled. One jar contains 2 white balls and 1 black ball. Another jar contains 2 black balls and 1 white ball. The jars are shuffled. A ball is withdrawn which turns out to be a white ball. What are the chances of withdrawing a white ball?
Let $W$ be the event that the ball withdrawn is white. Let $J_1$ be the event that the first white withdrawn was from jar 1.
$$P(W) = P(W|J_1)P(J_1) + P(W|J_2)P(J_2) $$
$$ P(W|J_1)=\frac{1}{2}, P(J_1) = \frac{2}{3}  $$
$$ P(W|J_2)=0, P(J_2) = \frac{1}{2}  $$
so $P(W) = 1/3.$
The solutions say the following

if we pick the other jar the chances are $$\frac{2}{3}\frac{1}{3}+\frac{1}{3}\frac{2}{3} =  \frac{4}{9}$$

Let $J_1$ be the event that the first white withdrawn was from jar 2.
$$P(W) = P(W|J_1)P(J_1) + P(W|J_2)P(J_2) $$
$$ P(W|J_1)=\frac{2}{3}, P(J_1) = \frac{1}{3}  $$
$$ P(W|J_2)=\frac{1}{3}, P(J_2) = \frac{2}{3} $$
Is this what is meant? Is my intuition correct?

A: Your notation is confusing because you're using $W$ to denote both 1st and 2nd white withdrawals. Let's call them $W_1$ and $W_2$. Another confusing thing is that we have 2 states of jars - when they are full ($J_1$ and $J_2$) and after we drew from them (smaller $j_1$ and $j_2$).
So the 1st part of the problem requires us to calculate the probability of drawing from either of jars (e.g. $P(J_1|W_1)$) multiplied by probabilities that 2nd withdrawal will be white (e.g. $P(W_2|j_1)$):
$$P(W_2) = P(J_1|W_1) P(W_2|j_1) + P(J_2|W_1)P(j_2) = \frac{2}{3}\frac{1}{2} + \frac{1}{2}0$$
You seem (again it's confusing because you wrote $P(J_2)$ instead of $P(J_2|W_1)$) to be saying that $P(J_2|W_1) = \frac{1}{2}$, while in fact you end up with $P(J_2|W_1) = \frac{P(W_1|J_2)P(J_2)}{P(W_1)} = \frac{1}{3}$. But this doesn't change your answer because eventually this was multiplied by $P(j_2)=0$.
The 2nd part of the task says that 2nd withdrawal ($W_2$) should happen from another jar, therefore it's:
$$
P(W_2) = P(J_1|W_1)P(W|J_2) + P(J_2|W_1)P(W|J_1) = \frac{2}{3}\frac{1}{3}+\frac{1}{3}\frac{2}{3}=\frac{4}{9}
$$
Where $W$ is the probability of drawing while ball from a full jar.


text:
Q: Xamarin FacebookClient I am using Xamarin Forms and want to integrate Facebook in android app. I want to pull the feed from a page like https://www.facebook.com/HyundaiIndia
I have installed Xamarin.Facebook from Nuget. It doesn't have a FacebookClient object as mentioned in here: https://components.xamarin.com/gettingstarted/facebook-sdk
Then I found the Xamarin.Facebook and Xamarin.FacebookBolts namespaces which I included, but I still didn't get FacebookClient. Instead I found Xamarin.Facebook.XAndroid.Facebook and I created an instance:
Xamarin.Facebook.XAndroid.Facebook fb = new Xamarin.Facebook.XAndroid.Facebook(FacebookAppId);

But this object doesn't have GetTaskAsync. How do I pull down the feeds in Xamarin?

A: I had the same experience trying following the article you mentioned.
The component created by Outercurve Foundation (Facebook.dll version 6.2.1)
needs that you reference Facebook.dll and you include it in your file like this:
using Facebook;

Don't confuse it with:
using Xamarin.Facebook;

EDIT
I finally found a bit of time for a more complete answer and since the example on the link
doesn't specify how to obtain the AccessToken (called userToken in the facebook-sdk component page example linked in the question) I'm posting one of the possible solutions.
This one works for me and doesn't require any other library or component (but the one already mentioned in the question).
using Xamarin.Auth;
using Facebook;

string FaceBookAppId = "YOUR_FACEBOOK_APP_ID";
string AccessToken;
string OauthTokenSecret;
string OauthConsumerKey;
string OauthConsumerSecret;

void GetFBTokens()
{
    var auth = new OAuth2Authenticator(FaceBookAppId,
       "",
       new Uri("https://m.facebook.com/dialog/oauth/"),
       new Uri("https://www.facebook.com/connect/login_success.html")
      );

    auth.Completed += (sender, eventArgs) =>
    {
        if (eventArgs.IsAuthenticated)
        {
           eventArgs.Account.Properties.TryGetValue("access_token", out AccessToken);
           eventArgs.Account.Properties.TryGetValue("oauth_token_secret", out OauthTokenSecret);
           eventArgs.Account.Properties.TryGetValue("oauth_consumer_key", out OauthConsumerKey);
           eventArgs.Account.Properties.TryGetValue("oauth_consumer_secret", out OauthConsumerSecret);
        }
    };
}

//Now we can use the example of the link.
void PostToMyWall ()
{
    FacebookClient fb = new FacebookClient (AccessToken);
    string myMessage = "Hello from Xamarin";

    fb.PostTaskAsync ("me/feed", new { message = myMessage }).ContinueWith (t => {
        if (!t.IsFaulted) {
            string message = "Great, your message has been posted to you wall!";
            Console.WriteLine (message);
        }
    });
}

A: There are 2 editions of Facebook SDK, one is binding for official SDK, another is from Outercurve Foundation.
Looks like you're using this one: the "official" binding , so check the documentation on this link.


text:
Q: Is there a way to obtain the logical index of a row in Handsontable The Handsontable sorting documentation shows how you can obtain a physical index given a logical index:

So I want to get the physical index, having the logical index. This is the code I have to write:
physicalIndex = instance.sortIndex[logicalIndex][0];
The revers mapping is a bit more complicated, but is also possible. In fact, columnSorting plugin has two dedicated methods which translates logical indices to physical and vice versa (called translateRow() and untranslateRow()) but they are currently inaccessible from the global scope.

A mention of the reverse is made, but it doesn't say how this can be achieved.  Can someone explain how this can be done using the public API of Handsontable?


text:
Q: Finding similarities in text, and more specifically answers to the text? - PHP I have a unique situation in the sense that what I am asking is for my own convenience rather than the end user of my application.
I am attempting to create an application that tests peoples' IQ scores (I know they are irrelevant and not much use to anyone), nothing too serious, just a project of mine to keep me busy in between assignments.
I am writing it locally in WAMP with PHP. I have found that there are a lot of available IQ questions and answers on the internet that I can use for my project. I have also noticed that there are a lot of the same questions but they are worded slightly differently.
Is there any third party PHP library that I can utilize in order to stop me from including "two" of the same questions in my application?
Some examples of questions that are the "same" but programatically are considered different;
The average of 20 numbers is zero. Of them, at the most, how many may be greater than zero?

The average of 20 numbers is zero. Of them how many may be greater than zero?

The average of 20 numbers is zero. Of them how many may be greater than zero, at the most?

Obviously you can see that PHP itself using operators cannot accomplish this and myself trying to differentiate between the similarities in the questions is far greater than my programming skill.
I have looked into plagiarism software but have not found any open source PHP projects.
Is there a simpler solution?
Thanks
** EDIT **
One idea I had was before inserting a question use explode at every space, and then in the resulting array match it against other questions that have also had the same function applied. The more matches the more equal the questions are?
I am a newcomer to PHP does this sound feasible?

A: Try using the Levenstein Distance algorithm:
http://php.net/manual/en/function.levenshtein.php
I've used it (in C#, not PHP) for a similar problem and it works quite well. The trick I found is to divide the Levenstein Distance by the length of the first sentence (in characters). That will give you a rough percentage of change required to convert question 1 into question 2 (for example).
In my experience, if you get anything less than 50-60% (i.e., less than 0.5 or 0.6), the sentences are the same. It might seem high but notice that 100% isn't the maximum. For example, to convert the string "z" into "abcdefghi" requires around 10 character changes (that's the Levenstein Distance: remove z then add abcdefghi) or a change of 1,000% as per the calculation above. With big enough changes, you can convert any random string into any other random string.

A: As acfrancis has already answered: it doesn't get much simpler than using the built in levenshtein function.
However, to answer your final question: yes, doing it the way that you suggest is feasible and not too difficult.
Code
function checkQuestions($para1, $para2){
    $arr1 = array_unique(array_filter(explode(' ', preg_replace('/[^a-zA-Z0-9]/', ' ', strtolower($para1)))));
    $arr2 = array_unique(array_filter(explode(' ', preg_replace('/[^a-zA-Z0-9]/', ' ', strtolower($para2)))));

    $intersect = array_intersect($arr1, $arr2);

    $p1     = count($arr1);            //Number of words in para1
    $p2     = count($arr2);            //Number of words in para2
    $in     = count($intersect);       //Number of words in intersect
    $lowest = ($p1 < $p2) ? $p1 : $p2; //Which is smaller p1 or p2?

    return array(
        'Average'  => number_format((100 / (($p1+$p2) / 2)) * $in, 2), //Percentage the same compared to average length of questions
        'Smallest' => number_format((100 / $lowest) * $in, 2)          //Percentage the same compared to shortest question
        );
}

Explanation

*

*We define a function that accepts two arguments (the arguments being the questions that we're comparing).

*We filter the input and convert to an array

*

*Make the input lower case strtolower

*Filter out non-alpha-numeric characters preg_replace

*We explode the filtered string on spaces

*We filter the created array

*

*Remove blanks array_filter

*Remove duplicates array_unique

*Repeat 2-4 for the second question

*Find matching words in both arrays and move to new array $intersect

*Count number of words in each of the three arrays $p1, $p2, and $in

*Calculate percentage similarity and return

You'd then need to set a threshold for how similar the questions had to be before being deemed the same e.g. 80%.
N.B.

*

*The function returns an array of two values. The first comparing the length to the average of the two input questions the second only to the shortest. You could modify it returns a single value.

*I used number_format for the percentages... But you'd be fine with returning int probably
Examples
Example 1
$question1 = 'The average of 20 numbers is zero. Of them, at the most, how many may be greater than zero?';
$question2 = 'The average of 20 numbers is zero. Of them how many may be greater than zero?';

if(checkQuestions($question1, $question2)['Average'] >= 80){
    echo "Questions are the same...";
}
else{
    echo "Questions are not the same...";
}

//Output: Questions are the same...

Example 2
$para1 = 'The average of 20 numbers is zero. Of them, at the most, how many may be greater than zero?';
$para2 = 'The average of 20 numbers is zero. Of them how many may be greater than zero?';
$para3 = 'The average of 20 numbers is zero. Of them how many may be greater than zero, at the most?';

var_dump(checkQuestions($para1, $para2));
var_dump(checkQuestions($para1, $para3));
var_dump(checkQuestions($para2, $para3));

/**

Output:

array(2) {
  ["Average"]=>
  string(5) "93.33"
  ["Smallest"]=>
  string(6) "100.00"
}
array(2) {
  ["Average"]=>
  string(6) "100.00"
  ["Smallest"]=>
  string(6) "100.00"
}
array(2) {
  ["Average"]=>
  string(5) "93.33"
  ["Smallest"]=>
  string(6) "100.00"
}

*/


text:
Q: Can you capture the output of ipython's magic methods? (timeit) I want to capture and plot the results from 5 or so timeit calls with logarithmically increasing sizes of N to show how methodX() scales with input.
So far I have tried:
output = %timeit -r 10 results = methodX(N)

It does not work...
Can't find info in the docs either.  I feel like you should be able to at least intercept the string that is printed.  After that I can parse it to extract my info.
Has anyone done this or tried?
PS: this is in an ipython notebook if that makes a diff.

A: This duplicate question Capture the result of an IPython magic function has an answer demonstrating that this has since been implemented.
Calling the %timeit magic with the -o option like:
%timeit -o <statement>

returns a TimeitResult object which is a simple object with all information about the %timeit run as attributes.  For example:
In [1]: result = %timeit -o 1 + 2
Out[1]: 10000000 loops, best of 3: 23.2 ns per loop

In [2]: result.best
Out[2]: 2.3192405700683594e-08

A:
PS: this is in an ipython notebook if that makes a diff.

No it does not.
On dev there is te %%capture cell magic.
The other way would be to modify the timeit magic to return value instead of printing, or use the timeit module itself. Patches welcomed.


text:
Q: Need to show one particular view in App Delegate in a particular seconds while push notification receives need to show one particular view (push view) for 30 secs in AppDelegate after that it want to disappear.The whole project i did in storyboard.After clicking the button that was designed in a particular view(push view),Need to go home page that i designed in storyboard.

A: First as usual, your first viewControler will be visible , whatever views are there on it. After you receive notification you can calll presentModalView controller and then after 30 seconds you can dismiss modal viewController. e.g
(do this in didReceiveNotificationPart)
when received notification call:
[self presentViewController:yourViewController animated:YES completion:NULL];

[self performSelector:@selector(dismissMyView) withObject:nil afterDelay:30];

for dismissing
-(void)dismissMyView
{

 [self dismissViewControllerAnimated:YES completion:nil]

}


text:
Q: Strategy for Excel Formula or VBA to do this. I have an Excel sheet with information about auto parts.
Part number is on A2. First Vehicle it fits is on B3. Second Vehicle it fits is on B4. Third vehicle it fits is on B5. And so on and so forth until the next Part Number for the next part. Some parts have hundreds of vehicles they fit. Some have 0 (parts for non-US cars).
I need to have the part number on A3, A4, A5, etc.

A: Cool trick to fix this - Do the following:

*

*Select the entire region in column A you want to fill in

*Prsee the F5 key

*Select Special

*Select Blanks and click Ok
Now all the blank cells chould be chosen

*

*Type in = and press the up arrow

*Hit ctrl + enter
That should do it


text:
Q: WorkManager custom constraint Is it possible to set some custom constraints (conditions) on workers?
In my case, I want the worker to be only executed when there are some data available in a table in Room database. I could observe on the database and schedule the worker if the table is not empty, but it would make more sense if I could just set some custom constraints on the worker in such case.

A: As far as I know you cannot.
The Constraints class is a final class therefore you cannot extend it to add functionality.

A: You can not use custom constraints with WorkManager at this time.
If you're controlling the database I recommend creating a OneTimeWorkRequest once data has been added to the table.


text:
Q: setAttribute in JavaScript not working with oraSearch I'm working in ORMB and have an input element like this
<input id="charVal" class="oraInput" oraField="charVal">

I want to dynamically add an oraSearch attribute using Javascript but it's not working
document.getElementById("charVal").setAttribute("oraSearch","CM_SR_CHAR");

Though if I try with other attributes, it's working fine. Also if I add the oraSearch statically like below, then also it's working
<input id="charVal" class="oraInput" oraField="charVal" oraSearch="CM_SR_CHAR">

A: I believe the problem is in the DOM path for the JavaScript code.
I tried to put the script from the <head> and it didn't work, like this:
<!DOCTYPE html>
<html>
<head>
<script>
document.getElementById("charVal").setAttribute("oraSearch","CM_SR_CHAR");
</script>

</head>
<body>

<input id="charVal" class="oraInput">

</body>
</html>

But, if you put it in the body, it works fine:

<!DOCTYPE html>
<html>
<head>

</head>
<body>

<input id="charVal" class="oraInput">
<script>
document.getElementById("charVal").setAttribute("oraSearch","CM_SR_CHAR");
console.log(document.getElementById("charVal"));
</script>

</body>
</html>

Note: if you are taken the script from another file put the <script></script> inside the <body>