jQuery mousedown not updating

Question: I have this that I've been messing with:

$('.container').mousedown(function(e) {
    $('.coords').text(e.pageX + ' : ' + e.pageY);
});
.container {
    width: 300px;
    height: 300px;
    background-color: white;
    border: 2px solid black;
    margin: 0 auto;
    display: inline-block;
}

Coords:

I'm trying to program it such that when you click inside the box and move the mouse around the coordinates will also change - then if you leave the box, it's not updated.  Right now, the coordinates will only change when you let go of the mouse button and then click again.  Help?
Answer: You need to create more that a mousedown function. You need to use mousemove as well. Here are the docs on that, https://api.jquery.com/mousemove/
You could do something like this (fiddle).
var mouse_clicked;

$('.container').mousedown(function(e) {
    mouse_clicked = true;
});

$('.container').mouseup(function(e) {
    mouse_clicked = false;
});

$('.container').mouseleave(function(e) {
    mouse_clicked = false;
});

$('.container').mousemove(function(e) {
  if (mouse_clicked) {
    $('.coords').text(e.pageX + ' : ' + e.pageY);
  }
});

Here is a different way of doing it that looks a little cleaner
var mouse_clicked;
$('.container').on({
  'mousedown': function() {
    mouse_clicked = true;
  },
  'mouseup': function() {
    mouse_clicked = false;
  },
  'mouseleave': function() {
    mouse_clicked = false;
  },
  'mousemove': function(e) {
    if (mouse_clicked) {
      $('.coords').text(e.pageX + ' : ' + e.pageY);
    }
  }
});

Comment: @zklim - No prob, I also added a mouseleave because I noticed that the var stays true if you leave the div while mousedown. I added a cleaner way to do it as well.
Answer: One easy approach is to use a switch that detects when the mouse is held down. This example works on document but could easily be adapted for an element:
var isDown = false;
$(document).mousedown(function(e) {
   isDown = true;
});

$(document).mousemove(function(e) {
    if(isDown) {
        console.log(e.pageX + ',' + e.pageY);
    }
});

$(document).mouseup(function(e) {
   isDown = false;
});

http://jsfiddle.net/kynwywss/1/
Answer: I would track it like this.

var mousePosition = { x: 0, y: 0};
var BUTTONS = { LEFT: 0, MIDDLE: 1, RIGHT: 2};
var mouseDown = [];
var mouseDownCount = 0;

var buttonInfo = document.getElementById("buttons");
var posInfo = document.getElementById("pos");

// Track mouse all the time.
document.addEventListener('mousemove', function storeMouse(event) {
    mousePosition = {
        x: event.clientX,
        y: event.clientY
    };
});

document.addEventListener('mousedown', function (event) {
    mouseDown[event.button] = true;
    ++mouseDownCount;
});
document.addEventListener('mouseup', function (event) {
    mouseDown[event.button] = false;
    --mouseDownCount;
});

function checkMouseStuff() {
    var buttons = [];

    if (mouseDownCount) {
        for (var i = 0; i < mouseDown.length; ++i) {
            if (mouseDown[i]) {
                buttons.push("Button: " + i);
            }
        }
    }

    buttonInfo.textContent = buttons.join(", ");
    posInfo.textContent = mousePosition.x + " : " + mousePosition.y;
}

window.setInterval(checkMouseStuff, 10);

jQuery mousedown not updating


How do I make a function with if in Kontakt?

Question: I make a function that contains if in NI Kontakt:
on init
    message(Add(1,2))
end on

function Add(x,y) -> output
    if x > 0
        output := x + y
    else
        output := 0
    end if
end function

And I get the error message:

The definition of function Add needs to consist of a single line (eg.
"result := ") in order to be used in this context

Ho do I make a function with if?
Answer: there are several things wrong. I'm sure reading some example code helps to avoid too much try-and-error with this exotic language. But that's probably done after almost 4 months? ;-)
Firstly you need to declare all variables in the on init and always use their corresponding prefix (for integers its "$") like so:
on init
    declare $x
    declare $y
    declare $output
end on

Secondly you can not call a function in the on init. For this example I use the on note callback that triggers every time you play a note. Additionally use "call" to execute a function.
on note
    $x := 1
    $y := 2
    call Add
    message($output)
end on

And lastly use brackets around your conditions:
function Add
    if ($x > 0)
        $output := $x + $y
    else
        $output := 0
    end if
end function

It is like in most programming languages important to declare all your functions before their execution. Since you can not use them in the on init, you can place this callback always on top followed by your functions.
This would be the full code:
on init
    declare $x
    declare $y
    declare $output
end on

function Add
    if ($x > 0)
        $output := $x + $y
    else
        $output := 0
    end if
end function

on note
    $x := 1
    $y := 2
    call Add
    message($output)
end on

Enjoy ;-)


Formulation Fenchel Duality for Convex problem

Question: What is the Fenchel dual problem for a general convex problem with constraints?
Precisely  assume slater condition holds in following convex problem
$$\begin{matrix}
\min & f(x) \\
 s.t& g(x) \leq 0 \\
 &Ax =b
\end{matrix}$$
What would be the dual problem.
From Wikipedia I only see that Fenchel duality only works for convex unconstrained problems or at most with affine constraint. How can I incorporated nonlinear constrains into the dual problem?
Comment: Define $\tilde{f}(x) = f(x)$ if the constraints are satisfied and $+\infty$ otherwise?
Comment: @copper.hat   Then to Find conjugate of $\tilde{f}(x)$ we  need to solve an optimization problem with same constraints , so what's the point of duality ?
Comment: What do you mean by the Fenchel dual of a constrained problem? A Fenchel dual usually applies to a nominally unconstrained problem of the form $\inf (f-g)$. Without an explicit form of $g$, it is hard to see how you would obtain a useful form of the dual.
Comment: did you appreciate my answer?
Comment: @LinAlg Yes but that wasn't what I was looking for.
Comment: @Redshoes how so?
Answer: By definition, the Fenchel dual is
$$\begin{align}
&\mu^T b + \inf_x (f+\lambda g - \mu^T A)(x)\\
= \; &\mu^Tb-\sup_x (0^Tx-f-\lambda g + \mu^T A)(x) \\
= \; &\mu^Tb-(f+\lambda g - \mu^T A)^*(0)\end{align}$$
To compute the conjugate of this sum, use the rules
$$(f+\lambda g - \mu^T A)^*(y) = \inf_{y_1,y_2 : y_1 + y_2 + y_3 = y}f^*(y_1)+(\lambda g)^*(y_2) + (-\mu^TA)^*(y_3),$$
$$(\lambda g)^*(y_2)=\lambda g^*(y_2/\lambda)\text{, and}$$
$$(-\mu^TA)^*(y_3)=0 \text{ if } -A^T\mu=y_3.$$
After you substitute these last two formulas into the second one, you obtain the dual with variables $y_i$, $\lambda$ and $\mu$.
Comment: What's the source of this definition ? and that infimum looks like a mess .
Comment: Just the definition of the conjugate: $\mu^Tb-\sup_x (0^Tx-f-\lambda g - \mu^T A)(x) = \inf_x (f+\lambda g + \mu^T A)(x)$. A mess? You wanted the dual ;)
Comment: definition of the conjugate of what function?
Comment: I have updated the answer
Comment: I suspect a missing minus signs somewhere, since the equality constraint should appear as $\mu^T (Ax-b)$.
Comment: @copper.hat good point! I updated the answer based on $\mu^T(b-Ax)$.
Comment: Sorry, I forgot to mark your answer as the correct answer 4 years ago. lol


Why null hypothesis of a statistical test is always opposite to what one wants to prove

Question: Why is it that the null hypothesis is typically the opposite of what one believes to be true?
Comment: It is a form of modus tollens: https://en.wikipedia.org/wiki/Modus_tollens
Comment: Can you add some context to explicate what you have in mind here?
Answer: The treatment of the null and alternative hypothesis is, by convention, asymmetrical. The null hypothesis is rejected at $p \ll 0.5$ (say $p = 0.05$ or $p = 0.01$). It follows that if the null hypothesis is rejected, then the null hypothesis is not just less likely, but compellingly so. If you want to convince someone of the alternative hypothesis, setting the opposite to the null hypothesis, then rejecting it at low p-values, is a convincing argument.
Imagine you found a new drug for some disease. If the new drug is effective, it will entail changing medical protocol, building a new factory for producing the drug, and so forth. Intuitively, in order to get this done, you don't need to show that the new drug is just more likely than not to work, but rather that it is compellingly more likely than not to work. Framing the converse as the null hypothesis is a step in that direction.


In the R randomForest package for random forest feature selection, how is the dataset split for training and testing?

Question: I'm using the randomForest R package to perform a random forest feature selection. I undestand that, after the execution of the randomForest function, I have to check the importance field, and study the importance measured throudh mean square error accuracy reduction and Gini purity reduction.
For example, by using this R code:
<code>data(iris)
library("randomForest")
set.seed(71)
iris.rf <- randomForest(Species ~ ., data=iris, importance=TRUE,
proximity=TRUE)
print(iris.rf)
</code>
It will print out:
<code>                     MeanDecreaseAccuracy  MeanDecreaseGini
        Sepal.Width  0.007962441             2.625413
        Sepal.Length 0.031901722            10.714741
        Petal.Length 0.304760304            42.104241
        Petal.Width  0.300907912            43.767952
</code>
Then, I see that I can rank these features by the MeanDecreaseAccuracy or MeanDecreaseGini field to understand what are the most important ones.
Even if I understand the output of the method, I cannot understand how the method obtains its results.
The questions are:

How does the method compute the accuracy?
How does the method split the dataset into training set and test set to compute the accuracy?
Answer: It does not use a separate training and testing set. Instead, standard accuracy estimation in random forests takes advantage of an important feature: bagging, or bootstrap aggregation.
To construct a random forest, a large number of data subsets are generated by sampling with replacement from the full dataset. A separate decision tree is fit to each bootstrap data subset, the trees jointly forming the random forest. Each data point from the full dataset is present in approximately 2/3 of the bootstrap data subsets, and absent from the remaining 1/3. You can therefore use the 1/3 of trees that do not contain a point to predict what their value would be; these are called out-of-bag (OOB) estimates. This process avoids the overfitting problem (and arguably makes crossvalidation redundant for this purpose) since the points were not present in the trees used to predict them. By repeating this for every point in the full dataset and comparing the OOB predictions against the true values, you can calculate the accuracy of the random forest.
The mean decrease in accuracy metric (generally recommended) for a variable is calculated by permuting the values of this variable across the entire dataset and estimating how the accuracy of the random forest changes.
The mean decrease in Gini metric is explained this way by Breiman & Cutler (which I took from this helpful answer):

Every time a split of a node is made on variable m the gini impurity
  criterion for the two descendent nodes is less than the parent node.
  Adding up the gini decreases for each individual variable over all
  trees in the forest gives a fast variable importance that is often
  very consistent with the permutation importance measure.
Comment: Thanks @mkt, very clear. Question: is there a particular reason why accuracy is used instead of Matthews correlation coefficient (MCC) or F1 score?
Comment: @DavideChicco.it Good question, but I'm afraid I don't know. I mostly work in a regression context, where 'MSE increase' is a simple and good metric. I'm less familiar with the classification applications and had not heard of the MCC or F1 score. You might ask that as a separate question.
Answer: In order to calculate mean decrease in accuracy randomForest doesn't use train and test sets per se it uses something called the out of bag sample.  Since each tree is built using a bootstrap sample (a sample of the same size as your dataset sampled with replacement) there will be records that are in your dataset that are not used to build the tree, these records are called the out of bag (OOB) sample.  You run these records down the tree and calculate their accuracy (you could think of the OOB records as your test set).  In order to determine the mean decrease in accuracy you randomly permute one of the explanatory variables in your OOB sample and then rerun the OOB sample down the tree and recalculate the accuracy, the decrease you see in the accuracy is what the importance measure refers to.
Answer: If you want to have a more detailed description you can read the Wikipedia article that answers your questions:
https://en.wikipedia.org/wiki/Random_forest
and this post:
this is a nice post for a more detailed explanation:
https://www.quora.com/What-is-the-out-of-bag-error-in-random-forests-What-does-it-mean-Whats-a-typical-value-if-any-Why-would-it-be-higher-or-lower-than-a-typical-value
But in short and just to start you up:
1) the random forest algorithm generates a set of decision trees
2) each tree is trained on a different, randomly chosen subset of the data (ca. 2/3) and using a different, randomly chosen subset of the features. so each decision tree in the random forest has a different test and training sets (answers your second question)
3) for each element X_i of the data you can then compute an out of bag error (OOB error). briefly you consider all the trees in the RF that are trained on a set not containing X_i. you compute an OOB error counting the percentage of those trees that fail classifying X_i. averaging this error on all data you get the OOB. Accuracy = 1-OOB


Showing that $(1,2)$ is an open set

Question: I was reading an example and it said $(1,2)$ is an open set in $(\mathbb{R},|.|)$. It showed that $(1,2)$ is an open set as follows:
Let $x \in (1,2)$ and $\delta = \min\{x-1,2-x\}$. Then $B(x,\delta) \in (1,2)$. Thus $(1,2)$ is open.
I understand what they did, but the only part Im not sure is, how did they choose that $\delta = \min\{x-1,2-x\}$? Is it baesd on your own intuition or is that a standard way to define $\delta$?
What would be a standard way to show that a set is open or closed?
Answer: $\delta$ is chosen such that $x$ is "$\delta$ away from each end of the interval $(1,2)$". It means that $(x-\delta, x+\delta) \subset (1,2)$.
You achieve exactly this by choosing $\delta$ as $\min (x-1, 2-x)$.
Comment: @Steven Yes! Exactly : ) That's the definition of open set for metric spaces.
Comment: Thanks @MattN.

So if I want to show that a set is open, do I just have to find a delta such that $(x-\delta, x+\delta) \subset \text{the set}$?
Comment: Okay, thanks again!
Answer: You want to find a $\delta>0$ such that $(x-\delta,x+\delta)\subseteq(1,2)$. To do that, you must choose $\delta$ so that $x-\delta\ge 1$ and $x+\delta\le 2$. Solve those inequalities for $\delta$, and you find that need to have $\delta\le x-1$ and $\delta\le 2-x$. The easiest way to make both of these things happen is to choose $\delta$ to be the smaller of the two numbers $x-1$ and $2-x$.
If you're visually oriented, a picture may help:
<code>                      1         x                     2
             ---------|---------|---------------------|--------
                      |<- x-1 ->|<------- 2-x ------->|
</code>
You need to choose $\delta$ so that $x-\delta$ doesn't reach to the left past $1$, and $x+\delta$ doesn't reach to the right past $2$. The distance from $x$ to $1$ is $x-1$, so $\delta$ has to be at most this distance. Similarly, it has to be at most $2-x$, the distance from $x$ to $2$.
In general the details of choosing a $\delta$ that 'works' depend very much on the specific problem. Here it's easy, because we can write down very simple necessary and sufficient requirements that $\delta$ must meet.
Comment: Thanks Brian, very nice answer and clear to understand!
Answer: The standard way to show that a set is open is from the definition, show that it contains a neighborhood of each of its points. This is what Matt and Brian showed above. To show a set is closed, it is often easier to show that its complement is open. One can always show that a set is open by showing that its complement is closed. In your case, the complement of (1,2) is the union of two closed intervals. But the union of any finite number of closed sets is closed, so you are done. As usual, what way you proceed is going to be dictated by the tools and concepts that you have available, and by what you feel most comfortable with.
Comment: Thanks for your suggestions, yes I think i need to practice more examples to get a better feel for it.
Comment: But then Steven would have to show that the two intervals $]-\infty,1]$ and $[2,\infty[$ are closed :-)

Showing that $(1,2)$ is an open set


Regular expression for strings, which are no ended with a specified substring

Question: Please advice a regular expression to find all string which are not ended with ".pdf".
So, it should find stings "some string" and "some stringpdf", but not the strings like "some string.pdf"
Thanks,
Aleksey Asiutin
Comment: @NannuoLei Don't even think about abusing regex for this purpose.
Comment: If that's all you need, you can use a regexp to find .pdf-ended strings, and then reject them when they match, and accept the rest
Comment: @Jack you're right, regexp is too mucch for such small task, thank you for pointing it out.
Answer: If you are going to test individual string's you can use this regex
<code>/^(?!.*\.pdf$).*$/
</code>

If there are multiple string's to be matched within the string,you can use
<code>/(\s|^)(?![^\s]+\.pdf(\s|$))[^\s]+/
</code>
Answer: here's the regex
<code>/^(?!.*\.pdf$).*/
</code>
example:
<code>var r =  /^(?!.*\.pdf$).*/;
r.test("some string");     //true
r.test("some stringpdf");  //true
r.test("some string.pdf"); //false
</code>
in actually, I recommend the suggestion from @Nannuo Lei.


bootstrap not working with chrome (firefox and ie work fine)

Question: I have a basic website I'm building to learn Bootstrap. On firefox and ie 11, the website works as expected. The grid system works and the navigation collapses and toggles the hamburger icon as expected.
On chrome the navigation starts a little under 992px to go cover the right links and it doesn't collapse/toggle the hamburger icon.
Why is it not working on chrome?
So far I have this as my code, thank you in advance:
<!doctype html>

    <meta charset="utf-8">
    <title>Testing Bootstrp</title>
    <link rel="stylesheet" type="text/css" href="css/bootstrap.css">
    <link rel="stylesheet" type="text/css" href="css/main.css">

                        WELCOME TO MY WORLD

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    Toggle Navigation

                </button>

HOME

Testimonails

Insurance

Here is main.css, not much going on.
.features .glyphicon {
    font-size: 32px;
    color: purple;
}

body {
    padding-top: 70px;
}

996px
It starts to break here, the grid stops adapting under the 991 mark
Comment: Would need to know the contents of main.css to have any real way to debug this.  can you add a link to a codepen (http://codepen.io) and include your stylesheet?
Comment: I edited it to include my main.css, thanks for the quick response!
Comment: can I assume you're also closing the body tag and loading bootstrap.js?  :-)  When I put your code into a codepen, it looks like it's working exactly the same in Chrome as in FF...http://codepen.io/anon/pen/GoQdMZ
Comment: Yes I have the js loading and the body + html tags closing. Odd, you're codepen works on FF but still doesn't work on chrome.
Comment: what version of Chrome are you using? and/or can you grab a screenshot of the isssue?
Comment: I reinstalled chrome so it should be the latest version. Version 48.0.2564.82 m

Ill attach screenshots of two break points (you can find them at the end of my post)
Comment: any chance you might be getting trolled by the chrome dev tools? if you resize the window itself with the dev tools closed, does it still break?
Comment: bingo ;0 dev tools buggin out. why is that? Thanks for the help!!
Comment: I don't know exactly what causes it, but that device emulation feature has always behaved a little unpredictably - you really have to reload the page each time you resize it or it's fairly unpredictable what you will see.  If I'm just testing viewport width (max/min-width media queries, like bootstrap uses) I usually just toggle the emulator off (the little phone looking icon) and toggle the dev tools to the right instead of the bottom (the '...' icon) that way you can just drag the divider between the webpage and the dev panel back and forth and get a more accurate view without refreshing.
Comment: was this solved? I'm having same issue. what was solution?
Answer: Try adding this line of code to your head section:
<meta name="viewport" content="width=device-width, initial-scale=1">


Declaração e inicialização de struct fora da função main em C

Question: Estou fazendo um joguinho em C que possui a estrutura carta:
typedef struct {
    int numero;
    int cor;
} TipoCarta;

Um método para colocar os valores na carta:
void inicializaCarta(TipoCarta *carta, int num, int cor){
    carta->numero = num;
    carta->cor = cor;
}

E na main eu terei que declarar e inicializar cada carta passando os valores, por exemplo:
TipoCarta amarelo1, amarelo2;
inicializaCarta(&amarelo1, 1, amarelo);
inicializaCarta(&amarelo2, 2, amarelo);

(no cabeçalho tem uma constante definindo um inteiro para amarelo)
É possível fazer essa inicialização em outro arquivo .c, ou pelo menos fora da main? Pro código não ficar tão "poluído", visto que terá muitas cartas.
Comment: Parece ser possível, mas não sei se entendi a dúvida exata.
Answer: Se o problema é a poluição, você poderia reescrever sua main() de uma outra forma, veja só:
typedef enum { corVermelho, corAzul, corVerde, corAmarelo } TipoCor;

typedef struct {
    int numero;
    TipoCor cor;
} TipoCarta;

void inicializaCarta( TipoCarta * carta, int num, TipoCor cor ){
    carta->numero = num;
    carta->cor = cor;
}

int main( void ) {
    int i = 0;

    TipoCarta amarelo[10];
    TipoCarta azul[10];
    TipoCarta verde[10];
    TipoCarta vermelho[10];

    for( i = 0; i < 10; i++ ) {
        inicializaCarta( &vermelho[i], i + 1, corVermelho );
        inicializaCarta( &azul[i], i + 1, corAzul );
        inicializaCarta( &verde[i], i + 1, corVerde );
        inicializaCarta( &amarelo[i], i + 1, corAmarelo );
    }

    return 0;
}

No exemplo acima, 10 cartas de 4 cores diferentes foram inicializadas, totalizando 40 cartas.
Alternativamente, você pode colocar suas Cartas dentro de um Deck, veja só:
typedef enum { corVermelho, corAzul, corVerde, corAmarelo } TipoCor;

typedef struct {
    int numero;
    TipoCor cor;
} TipoCarta;

typedef struct {
    TipoCarta amarelo[10];
    TipoCarta azul[10];
    TipoCarta verde[10];
    TipoCarta vermelho[10];
} TipoDeck;

void inicializaCarta( TipoCarta * carta, int num, TipoCor cor ){
    carta->numero = num;
    carta->cor = cor;
}

void inicializaDeck( TipoDeck * deck )
{
    int i = 0;

    for( i = 0; i < 10; i++ ) {
        inicializaCarta( &deck->vermelho[i], i + 1, corVermelho );
        inicializaCarta( &deck->azul[i], i + 1, corAzul );
        inicializaCarta( &deck->verde[i], i + 1, corVerde );
        inicializaCarta( &deck->amarelo[i], i + 1, corAmarelo );
    }
}

int main( void )
{
    TipoDeck deck;
    inicializaDeck( &deck );
    return 0;
}

Comment: bem interessante, vou testar, obrigada :)


Pandas grouby 7 days

Question: How to sum my data counts by week and if the last week still not completed calculate the average "normalization"
let's say these is my lists
days = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31]
counts = [1839,1334,2241,2063,1216,1409,1614,1860,1298,1140,1122,2153,971,1650,1835,889,653,484,2078,1198,426,684,910,701,851,360,763,402,1853,400,1159]

Thanks
Answer: Here is a solution with Pandas:
1) Create dataframe:
df = pd.DataFrame({'days':days,'counts': counts})
df['week'] = df.days.sub(1)//7 # adding week column

2) calculate sum and mean by week, then producing normalized sum:
d2 = df.groupby('week').agg({'counts':['sum','mean']}) # ca
d2['norm_sum'] = d2[('counts','mean')] * 7

3) output:
print (d2)

     counts                   norm_sum
        sum         mean
week
0     10102  1683.666667  11785.666667
1     10158  1451.142857  10158.000000
2      8787  1255.285714   8787.000000
3      4695   670.714286   4695.000000
4      3814   953.500000   6674.500000

Comment: `df.days.sub(1)//7`
Comment: Comment from @ansev accepted and implemented into the solution. This makes the first week complete.
Comment: perfect @Ruslan S. .Nice solution + 1
Answer: I do not know how to use pandas in this case, but I would do it using built-in python modules following way:
from collections import defaultdict
from statistics import mean
days = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31]
counts = [1839,1334,2241,2063,1216,1409,1614,1860,1298,1140,1122,2153,971,1650,1835,889,653,484,2078,1198,426,684,910,701,851,360,763,402,1853,400,1159]
weeks = [d//7 for d in days]
avg_count = int(mean(counts))
weeks = weeks + [weeks[-1]]*(len(weeks)%7)  # pad weeks to multiply of 7
counts = counts + [avg_count]*(len(counts)%7)  # pad counts to multiply of 7
count_per_week = defaultdict(int)
for w, c in zip(weeks, counts):
    count_per_week[w] += c
print(dict(count_per_week))

Output:
{0: 10102, 1: 10158, 2: 8787, 3: 4695, 4: 3814}

Note that I assume average is reasonable filler value, which do not have to always holds true. defaultdict(int) when asked for non-existing key will set that key value to int() that is 0.
Answer: This my approach:
The data:
counts = [1839,1334,2241,2063,1216,1409,1614,1860,1298,1140,1122,2153,971,1650,1835,889,653,484,2078,1198,426,684,910,701,851,360,763,402,1853,400,1159]

To array:
counts = np.array(counts)

Reshape: (thanks to https://stackoverflow.com/users/4427777/daniel-f)
def shapeshifter(num_col, my_array=data):
    return np.lib.pad(my_array, (0, num_col - len(my_array) % num_col), 'constant',  constant_values = 0).reshape(-1, num_col)

data = shapeshifter(7, counts)

array([[1839, 1334, 2241, 2063, 1216, 1409, 1614],
       [1860, 1298, 1140, 1122, 2153,  971, 1650],
       [1835,  889,  653,  484, 2078, 1198,  426],
       [ 684,  910,  701,  851,  360,  763,  402],
       [1853,  400, 1159,    0,    0,    0,    0]])

To dataframe with zeros converted to NaN:
df = pd.DataFrame(data)
df[df == 0] = np.nan

Fill missing values with the mean value of the month:
df.fillna(counts.mean())

    0   1   2   3   4   5   6
0   1839    1334    2241    2063.000000     1216.000000     1409.000000     1614.000000
1   1860    1298    1140    1122.000000     2153.000000     971.000000  1650.000000
2   1835    889     653     484.000000  2078.000000     1198.000000     426.000000
3   684     910     701     851.000000  360.000000  763.000000  402.000000
4   1853    400     1159    1211.483871     1211.483871     1211.483871     1211.483871

Get the sum by row or week:
df.sum(axis=1)

0    11716.0
1    10194.0
2     7563.0
3     4671.0
4     3412.0
dtype: float64

Pandas grouby 7 days


How do I solve the SQL(query) missing database error?

Question:
Error Code : 1 (SQLITE_ERROR)
                    Caused By : SQL(query) error or missing database.
                        (near "=": syntax error (code 1): , while compiling: DELETE FROM notesWHEREid='1')

This is the error i am getting:
This is the part of my database handler that is the source of this error:
    public void deleteNote(String id) {
    SQLiteDatabase db = this.getWritableDatabase();
    String deleteQuery="DELETE FROM " + DatabaseValues.TABLE_NOTES + "WHERE" + DatabaseValues.NOTES_ID + "= '" + id + "'";

    db.execSQL(deleteQuery);
    db.close();
}

Comment: And what is the query right before you execute it? Please learn to debug your code. You won't get far without knowing how to do it.
Comment: @juergend Truer words have not been spoken!!! :)
Comment: Look into using parameters as well.
Answer: If you are using C# 6.0, using interpolated strings makes life much easier for strings concatenation, avoiding such silly errors:
String deleteQuery= $"DELETE FROM {DatabaseValues.TABLE_NOTES} WHERE {DatabaseValues.NOTES_ID} = id";

Note: $ operator is available in C# 6.0. Also you should take a look into how to build parameterized queries because passing parameters like this can expose you to SQL injection.
Comment: @CamiloTerevinto - yes, I know. That's why I have put the link for parameterized queries.
Comment: @CamiloTerevinto - this is not entirely true, as some people managed to make it work in earlier versions of Visual studio ([source](http://stackoverflow.com/questions/27093908/how-to-enable-c-sharp-6-0-feature-in-visual-studio-2013)) or even without Visual Studio ([source](http://stackoverflow.com/questions/27093908/how-to-enable-c-sharp-6-0-feature-in-visual-studio-2013)).
Answer: Change your following statement:
String deleteQuery="DELETE FROM " + DatabaseValues.TABLE_NOTES + "WHERE" + DatabaseValues.NOTES_ID + "= '" + id + "'";

to
String deleteQuery= "DELETE FROM " + DatabaseValues.TABLE_NOTES + " WHERE " + DatabaseValues.NOTES_ID + " = '" + id + "'";

Actually you are combining the table name with where clause. You need to add a space before and after WHERE Clause like  " Where "
Hope it helps.


Visual studio 2013 Designer crashing on custom IBehavior

Question: I want to use a custom IBehavior to be able to show/hide the StatusBar from XAML in a Universal app targeted at Windows Phone 8.1.
The code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xaml.Interactivity;
using Windows.ApplicationModel;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;

namespace test.Behaviors
{
    public class StatusBarBehavior : DependencyObject, IBehavior
    {

        public DependencyObject AssociatedObject { get; private set; }

        public void Attach(DependencyObject associatedObject) { }

        public void Detach() { }

        public StatusBarBehavior()
        {

        }

        public bool Show
        {
            get { return Convert.ToBoolean(GetValue(ShowProperty)); }
            set { SetValue(ShowProperty, value); }
        }

        public static readonly DependencyProperty ShowProperty =
            DependencyProperty.Register("Show",
            typeof(object),
            typeof(StatusBarBehavior),
            new PropertyMetadata(null, OnIsVisibleChanged));

        private static async void OnIsVisibleChanged(DependencyObject d,
            DependencyPropertyChangedEventArgs e)
        {
            var statusBar = StatusBar.GetForCurrentView();
            if (statusBar == null || e == null || e.NewValue == null || DesignMode.DesignModeEnabled)
                return;

            if (Convert.ToBoolean(e.NewValue))
                await statusBar.ShowAsync();
            else
                await statusBar.HideAsync();
        }
    }
}

XAML:
<Page
    x:Class="test.TestPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:test"
    xmlns:behavior="using:test.Behaviors"
    xmlns:i="using:Microsoft.Xaml.Interactivity"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

        <behavior:StatusBarBehavior  Show="False"/>

</Page>

The Behaviors SDK (12.0) has been added as a reference to the project.
Unfortunatly in Visual Studio 2013 (Community edition, Update 4), the design window for the page in question shows an error:
COMException: Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))
StackTrace: Empty
InnerException: None

However, the StatusBarBehavior works perfectly fine when I deploy the app on a device, no errors are thrown.
Is there a way to fix this error? Having the design window is quite necessary to preview the layout of the pages...
Answer: Changing the OnVisibleChanged event to
private static async void OnIsVisibleChanged(DependencyObject d,
            DependencyPropertyChangedEventArgs e)
        {
            if (DesignMode.DesignModeEnabled) { return; }

            var statusBar = StatusBar.GetForCurrentView();
            if (statusBar == null || e == null || e.NewValue == null)
                return;

            if (Convert.ToBoolean(e.NewValue))
                await statusBar.ShowAsync();
            else
                await statusBar.HideAsync();
        }

fixes the issue. I assume StatusBar.GetForCurrentView() throws an error in the design view.
Comment: wow thank you so much this has been bothering me for far too long


Showing that a subgroup is not finitely gerated

Question: Problem:
If $G$ is the multiplicative subgroup of $GL_2\mathrm{R}$ generated by $a = \bigg(\begin{matrix}2& 0\\ 0 & 1\end{matrix}\bigg)$ and $b = \bigg(\begin{matrix}1& 1\\ 0 & 1\end{matrix}\bigg)$, and $H$ is the subset $H\subset G$ of matrices whose diagonal entries are $1$, show that $H$ is not finitely generated.
Attempt:
So, I was able to show that $H=\bigg\{\bigg(\begin{matrix}1& m/2^n\\ 0 & 1\end{matrix}\bigg)\bigg| m,n \in Z\bigg\}$. But I'm unsure on how to proceed from this to finite generated-ness. The way I used to show that H is like that was based around how general elements in $G$ can have a determinant of $1$ and exploring around with the form of $a^{-n}b^ma^n$...The elements in the RHS of the above equality are all of the form $a^{-n}b^ma^n$. Is it enough to point out that finitely many pairs of $(n,m)$ cannot generate all terms in the RHS, only infinitely many can?
Answer: You already basically observed that $H$ is isomorphic to the additive structure of the ring $\mathbb Z [1/2]$. If this means nothing to you,
$$\mathbb Z [1/2] = \{m/2^n : n, m \in \mathbb Z\}.$$
Now if this were finitely generated by $S = \{m_1/2^{n_1}, \dots, m_k/2^{n_k}\}$, let $n$ be the minimum of the $n_i$. But then, $2^{-(n+1)}$ is not a linear combination of elements of $S$ over $\mathbb Z$, a contradiction.


Remover Borda do Report Viewer

Question: já tentei de várias formas remover esta borda que aparece no report viewer, e não consegui de jeito nenhum.

Abaixo está parte do meu código com as propriedades que adicionei para remover a borda:
viewer.SizeToReportContent = true;
viewer.Width = System.Web.UI.WebControls.Unit.Percentage(100);
viewer.Height = System.Web.UI.WebControls.Unit.Percentage(100);
viewer.BorderWidth = 0;
viewer.InternalBorderStyle = System.Web.UI.WebControls.BorderStyle.None;

O código HTML esta abaixo:

RELATÓRIO /

PAGAMENTOS POR EMPRESA

RELATÓRIO DE PAGAMENTOS POR EMPRESA

                @Html.ReportViewer(ViewBag.ReportViewer as Microsoft.Reporting.WebForms.ReportViewer, htmlAttributes: new { @Width = "100%", @Height = "100%" })

Comment: @VirgilioNovic editei o problema e incluí o trecho do código html
Comment: Essa bordar não é do reportViewer, poderia colocar esse trecho de código html que envolve o componente? A borda do componente já não aparece e outra borda de outro tag!
Answer: É criado um iframe, então, adicione essa configuração no htmlAttributes: @style = "border:0" para remover a bordar.
@Html.ReportViewer(ViewBag.ReportViewer as Microsoft.Reporting.WebForms.ReportViewer,
          htmlAttributes: new { @Width = "100%", @Height = "100%", @style = "border:0" })

Comment: Funcionou perfeitamente. Valeu

Remover Borda do Report Viewer


Split the string into two based on a last two occurrence of a delimiter

Question: I need to split a string into two based on last two occurrence of a same delimiter.
Example:

"this_is_an_example".split_by_last_two_occurance("_") => #[this_is, an_example]

"this_is_an_example_string".split_by_last_two_occurance("_")  => #["this_is_an", "example_string"]

As far as I tried,
splitted_string = "this_is_an_example_string".split("_")

string_array = [splitted_string[0..-3].join("_"), splitted_string[-3,-1].join("_")]
=> #["this_is_an", "example_string"]

This doesn't looks like an efficient way to do it.
Is there any other way to it?
Answer: Using regular expression:
"this_is_an_example_string".split(/_(?=[^_]*_[^_]*$)/)
# => ["this_is_an", "example_string"]


update github my old pull request

Question: I was working on this feature in on of the open source project, however, due to some other work, I stopped for working on for quite long.
Now I want to make some changes to this feature branch and push this. However, the pull request says there are some conflicts and I should resolve it first.
I am new to Git so things look really confusing.
Following are the details.

Remote Branch: https://github.com/robotframework/Selenium2Library/
My forked Branch: https://github.com/Gaurang033/Selenium2Library
Pull Request: https://github.com/robotframework/Selenium2Library/pulls/Gaurang033

this is how my branch look

git branch -vv
*feature-table-functions fecb9a6 [origin/feature-table-functions: ahead 1] incorporated comments

Now how should I update the branch and resolve the conflict and push new changes?

git pull --rebase
Current branch feature-table-functions is up to date. git status
On branch feature-table-functions Your branch is ahead of
'origin/feature-table-functions' by 1 commit.   (use "git push" to
publish your local commits)
Comment: Possible duplicate of [How to do a GitHub pull request](https://stackoverflow.com/questions/14680711/how-to-do-a-github-pull-request)
Comment: @dannemp it's not, the question there is generic, mine here is very specific, I already have the pull request in the review.
Answer: If this is really an open source project, then those conflicts are probably due to other people's work which has come in since you last synched.
How you proceed here really depends on the repository and the rules of the open source project.  Though generally you would resolve the conflicts in one of two ways:

you do a git pull (and merge)
you do a git pull --rebase

In either case, you will be bringing in the latest changes to your own local branch, resolving the conflicts, and then issuing another pull request for your work.
In your case, since you are on your own feature branch, you would need to fetch the latest master branch, and then merge or rebase with that:
git fetch origin
git checkout feature-table-functions
git merge origin/master
# or git rebase origin/master

After this you can push your feature-table-functions branch to the remote.  Note that if you went with the rebase option, you might have to force push the branch.
Comment: two things. 1. on my github page it says my master is 7 months old. 2. I think after `git merge origin/master` it will ask me to resolve the conflict. right?
Comment: Is your branch eventually going to be merged to `master`?  You missed an important point in my answer: `git fetch origin`.  You don't merge with your 7 month old `master`, you merge with the latest version.
Comment: `git fetch origin` is going to get me the data from my forked project to my local machine, right? and my branch is already 34 commits behind and 4 commits ahead. is it ahead of master or forked project or remote? After the merge the changes of the master will be merged to my feature branch, right ? but it's 7 months old. shouldn't I worry about that.
Comment: I have given you enough information to resolve your problem.  If you are this unsure about how Git works then you should stop and review a tutorial.  This isn't the way to learn Git.

update github my old pull request


How to solve multicollinearity in OLS regression with correlated dummy variables and collinear continuous variables?

Question: I have predicted an ecological variable using OLS regression which showed the model accounts for more than 72% of the variance in the dependent variable (DV). However, I am also interested in which covariates have much impact on the DV. But I found that some of the independent variables are collinear making the Variance Inflation Factor > 10. What is the solution to the multicollinearity problem both for the continuous variables Temp and Vapor ( Drop one? ) and the categorical variables 1-8 which have very high VIF?
 Variable           Coeff.  Std Coeff.  VIF    Std Error    t      P -Value
 Constant          -0.228   0            0      0.086       -2.644  0.008
 Precipitation      <.001   0.151       2.688   <.001        8.541  0.0
 Solar Rad          0.002   0.343       2.836   <.001        18.939 <.001
 Temp              -0.116  -1.604       28.12   0.004       -28.11  0.0
 Water Stress       0.881   0.391       2.352   0.037        23.7   <.001
 Vapor Pressure     0.135   1.382       30.49   0.006        23.259 0.0
   1               -0.103   -0.109      52.086  0.074       -1.398  0.162
   2               -0.14    -0.048      6.49    0.079       -1.761  0.078
   3               -0.11    -0.048      10.007  0.077       -1.42   0.156
   4               -0.104   -0.234      236.288 0.073       -1.416  0.157
   5               -0.097   -0.242      285.244 0.073       -1.331  0.183
   6               -0.104   -0.09       35.067  0.074       -1.406  0.16
   8               -0.119   -0.261      221.361 0.073       -1.629  0.103
   ELEVATION        <.001   -0.115      3.917   <.001       -5.381  <.001

Condition Number: 59.833
Mean of Correlation Matrix: 0.221
1st Eigenvalue divided by m: 0.328

Comment: I would pay more attention to the standard errors of the coefficients than the VIF. After all, the main problem with multicolliniariy is that it increases standard errors.
Answer: For the categorical variable, you may collapse the variable and make it fewer levels as it is now. For instance, you may convert it to a dummy: level 2 and not level 2.
I think domain knowledge should come in to decide which variable to keep: temp or vapor pressure. Certainly, you may keep the one with smaller least squares (seems that you are minimizing the sum of squared errors to estimate the coefficients) or the one leading to smaller test error. If you only care about the prediction performance, you may keep both. If you want to interpret the coefficients, then you need to think which one makes more sense to keep. Does temperature leads to increasing vapor pressure? Then, I would say keep temperature but drop vapor pressure. When you are explaining the impact of temperature on your response variable, you need to explain the theory which may well involve vapor pressure.
Comment: Thank you for the explanation.To further explain my question- The dummy variables are actually landcovers ( forest, cropland,etc.) which are vital in determining the dependent variable ( C stock), so it would not give sense to reduce/collapse it since they are mutually exclusive.I was wondering( recently came across) if i am able to use Lasso regression for variable selection and prediction accuracy at the same time.
Comment: As @Rwitch has more or less said, seeking predictive accuracy will not give you the same model as seeking to distinguish the causal effect of particular variables.  Atheoretical prediction differs from causal explanation.  An algorithm-based variable selection tool such as lasso will not help you with causality.


TBB parallel_for with less number of threads

Question: I have written a multi-view face detection code using opencv face detector. I am running five detectors (trained for different pose angles) over an image and taking their weights to detect faces in an image. I have made the code parallel using TBB parallel_for but it improved the performance by just 1.7-times. I would like to ask if there is any better way to run five detectors in parallel?
I am running my code on a cluster with 16-cores. I think number of threads (that in my case are 5) are too less to utilize the complete power.
Any suggestions?
Thanks,
Answer: Some possible problems to look into:

One of the detectors takes longer than the other detectors to run.  For example, if one detector takes 4 units of time, and the other four detectors each take 1 unit of time, the most possible speedup is 2x.  Parallelizing the slow detector itself might help in this kind of situation.
The detectors run so fast that the parallel_for does not have time to spread the work.  If the detectors each take at least 0.1 sec, this should not be a problem.
Memory bandwidth can be a limiting resource, particularly if working sets do not fit in outer-level cache.

A profiler such as Intel(R) VTune(TM) Amplifier can sometimes help to track down these problems.  Both commercial and non-commercial licenses exist for Amplifier.  [Disclaimer: I work for Intel.]


jQuery - Animate numbers when appears in viewport

Question: I'm currently trying to animate some numbers when the user scroll and the DIV appears in the viewport. Like that: http://www.dimfolio.fr/
On the example it looks to be CSS3, for some reasons I'd prefer to use jQuery.
Currently, I use "animateNumber" plugin and this function to check if the div appears in the viewport:
$.fn.is_on_screen = function(){

var win = $(window);

var viewport = {
    top : win.scrollTop(),
    left : win.scrollLeft()
};
viewport.right = viewport.left + win.width();
viewport.bottom = viewport.top + win.height();

var bounds = this.offset();
bounds.right = bounds.left + this.outerWidth();
bounds.bottom = bounds.top + this.outerHeight();

return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));

};

Here is my code:
JS:
function animate_stats() {
  $('.stats_number').each(function() {
     if(!$(this).hasClass("numbered")) {
        var thisnumber = $(this).attr('title');
        $(this).animateNumber({ number: thisnumber }, 3000, function() {
            $(this).addClass('numbered');
        });
     }
  });
};

if( $('#statistics').is_on_screen() ) {
  animate_stats();
}

$(window).scroll(function(){
  if( $('#statistics').is_on_screen() ) {
     animate_stats();
  }
});

HTML:

0

   My title

The problem is that the number animation repeats and repeats again when the div appears. Of course I'd like the animation to run only once.
I suppose that the issue comes from my utilisation of "each" function but note sure.
Anyone can help? Thank you very much!
Comment: might want to check out [WOW.js](http://mynameismatthieu.com/WOW/)
Comment: Thanks for your reply, anyway as I said I'd prefer to use jQuery instead of CSS.
Answer: After the animation is run, remove the listener.
$(window).on('scroll.animateStats', function(){
  if( $('#statistics').is_on_screen() ) {
     animate_stats();
     $(window).off('scroll.animateStats');
  }
});

I namespaced the scroll event so that when we remove it we're only removing this event handler, and not all scroll handlers.


celerra checkpoint for a share paused

Question: This morning when i tried to check the checkpoint feature-I stumbled upon this...

Id Name                 State      Next Run                       Description

21 Daily_Patient        Paused     Wed Nov 17 01:05:00 EST 2010
11 UFS11_daily           Active     Tue Nov 16 23:02:00 EST 2010                     UFS11_Weekly             Active     Sun Nov 21 05:32:00 EST 2010 <
nas_ckpt_schedule -list

Id                     = 21
Name= Daily_Patient                                                                  ,Description = Snap_Patient_daily,
Tasks  = Checkpoint Daily_Patient on filesystem id=143
Next Run               = Wed Nov 17 01:05:00 EST 2010
State                  = Paused
Recurrence             = every 1 weeks
Start On               = Fri Nov 20 14:04:12 EST 2009
End On                 =
At Which Times         = 01:05
On Which Days of Week  = Mon,Tue,Wed,Thu,Fri

Does this mean the checkpoint feature is disabled for the share because of SavVol full or something? i am unable to understand this..
Do i get an option in CLI to check for the SavVol used? As far as i know, this shouldn't be happening since we use AVM feature and have HWM set up ,SavVol is auto expandable in this case>>  Any help will be appreciated!
Answer: Try to run fs_ckpt -list -all, to check the SavVol usage, basically when the SavVol is full, the newly created ckpts overwrite the oldest one in the SavVol.
If you find the SvVol over utilized, you can extend it using nas_fs command
nas_fs -xtend <ckpt name> -size=10G [just an example] not sure about the exact syntax
run nas_fs followed by Enter key to display the command parameters and usage.

celerra checkpoint for a share paused


How to replace a view

Question: Application requires more than one window (Lets call A,B,C). Each window has more than one view (table views, image views as well as web view). Lets say window A has three views (x, y,z) and window B has three views (d,e,f). Application needs to display images of different size on orientation change.
I have achieved the same using gesture event listener and looping through windows for views and replacing the view with new images. The problem I have is when we navigate from one window to other and the orientation changes, the loading of view after looping goes for a toss. Is there a better way to achieve the same ?
Is there a method in titanium like following code to replace a view ?
var self=Ti.UI.currentWindow
var newView=Ti.UI.createImageView({image:'abc.png'})
self.replace(self.children[1],newView )

Answer: Unfortunately there is now replace method.
You need to remove the whole view and add it again but this can cause a wrong layout if you have more than one view on a same level. The implementation then depends on the layout which was set (vertical, horizontal, composite etc).
For example in vertical layout removing an item and simply add a new one would remove your specified item but appends the new one at the end since you can't specify in which order it should be added.
If you have a composite layout you can specify absolute positions but adding a new view causes a higher zIndex for this view so that it will hide views that were previously added at the same/similar position.
Answer: Why not simply change the image link ?
var self = Ti.UI.currentWindow;
self.children[1].image = 'bcd.png';

Answer: Prasad,
If this is about just ensuring that the images look good on different orientations,you can make use of the different folders provided by Titanium in the android/images folder.You can just make different images for each of the orientations and device sizes.For IOS you can change just the images on orientation change as you are already doing.
https://wiki.appcelerator.org/display/guides/Using+density-specific+resources+on+Android
If you are concernced about the layout there are couple of things you can do:
1.Give all the height or width values in percentages.This way all elements will be re sized once the orientation changes automatically.
2.On each window open check if the orientation is vertical or horizontal by default and accordingly set the image attribute of the imageView.
Ti.UI.orientation

This property will give you the orientation of the window by default.Values of this property could be this
Ti.UI.PORTRAIT
Ti.UI.UPSIDE_PORTRAIT
Ti.UI.LANDSCAPE_LEFT
Ti.UI.LANDSCAPE_RIGHT
Use "if else"  and accordingly set the images.
Answer: Well you could always lock the orientation of your window. But this isnt exactly good practice (especially for iOS).
Generally orientation changes are handled pretty well if you define the width and height of your views to be percentages or Ti.UI.FILL, if you have a composite layout. Check that you are not giving the views absolute coordinates as this could cause layout problems. If you have a vertical or horizontal layout you usually don't have to worry about orientation change, unless you did not nest your views in a main container correctly.

How to replace a view


Functional equation with periods depending on $f$

Question: Find all functions $f:\mathbb{R}\rightarrow \mathbb{R}$ such that $f(x)=f(x+y+f(y))$ for any $x,y\in\mathbb{R}$ and $f(0)=-1$.
I suspect that the only solution is $f(x)=-1$. It is easy to see that we can reformulate that $y+f(y)$ is a period of the function. If we would know that this is a surjective function or its image contains an interval we would be done . Unfortunately not much can be said about it.
Note: It is false without an extra assumption like continuity. See example below.
Comment: Requiring $f$ to be continuous makes the problem  easy that is why I have not mentioned it. I think you can show that every rational number has to be a period. I am interested in this more general statement.
Comment: FYI, using an [Approach0 search](https://approach0.xyz/search/?q=OR%20content%3A%24f(x)%3Df(x%2By%2Bf(y))%24%2C%20OR%20content%3A%24f(0)%3D-1%24&p=1), I found the somewhat similar AoPS thread [Functional Equation](https://artofproblemsolving.com/community/c6h1881402p12802809), where its functional equation is $f(x)=f(x+y-f(y))$, with the condition $f(0)=0$, plus the additional requirement that $f(x)$ is continuous.
Answer: (not an answer, but the picture won't fit in a comment)
This will do as well.
Comment: Great! I was hoping that a construction would work to give a counterexample.


How do I make Nginx redirect all requests for files which do not exist to a single php file?

Question: I have the following nginx vhost config:
server {
    listen 80 default_server;

    access_log /path/to/site/dir/logs/access.log;
    error_log /path/to/site/dir/logs/error.log;

    root /path/to/site/dir/webroot;
    index index.php index.html;

    try_files $uri /index.php;

    location ~ \.php$ {
            if (!-f $request_filename) {
                    return 404;
            }

            fastcgi_pass localhost:9000;
            fastcgi_param SCRIPT_FILENAME /path/to/site/dir/webroot$fastcgi_script_name;
            include /path/to/nginx/conf/fastcgi_params;
    }
}

I want to redirect all requests that don't match files which exist to index.php. This works fine for most URIs at the moment, for example:
example.com/asd
example.com/asd/123/1.txt

Neither of asd or asd/123/1.txt exist so they get redirected to index.php and that works fine. However, if I put in the url example.com/asd.php, it tries to look for asd.php and when it can't find it, it returns 404 instead of sending the request to index.php.
Is there a way to get asd.php to be also sent to index.php if asd.php doesn't exist?
Comment: You could just rewrite ^ /index.php; instead of return 404;
Comment: See my comment under tyoyengel's answer - I need some way of telling the index.php file to use `error/404` as the path
Answer: Going by your additional comments this sounds like it might be the most optimal way, though it's not a pretty config.
server {
    listen 80 default_server;

    access_log /path/to/site/dir/logs/access.log;
    error_log /path/to/site/dir/logs/error.log;

    root /path/to/site/dir/webroot;
    index index.php index.html;

    location / {
        try_files $uri $uri/ /index.php;
    }

    location ~ \.php$ {
        try_files $uri @missing;

        fastcgi_pass localhost:9000;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include /path/to/nginx/conf/fastcgi_params;
    }

    location @missing {
        rewrite ^ /error/404 break;

        fastcgi_pass localhost:9000;
        fastcgi_param SCRIPT_FILENAME $document_root/index.php;
        include /path/to/nginx/conf/fastcgi_params;
    }
}

Comment: there's supposed to be a semicolon at the end of that try_files line
Comment: @jab11 Yep! Added that in now.
Answer: Wow, I think all you want to replace that code is:
error_page 404 /index.php

...if I read what you want correctly.
Comment: This works well, and so I have `error_page 404 /error/404/` which then redirects to `index.php`, but then in the php request_uri (what I use to get the path requested) it has `asd.php` (assuming this is what was typed in and resulted in the 404) and I have no way of getting the `error/404` path to then act on in the php. Is there any way to pass this path to php? I.E. I still want a single front index.php to handle errors as well. How do I tell the index.php that this is an error to handle?
Answer: What you are trying to do is same as custom error page. You can use the error_page property of nginx to achieve this. Follow the link for more information
http://wiki.nginx.org/HttpCoreModule#error_page
Answer: It's worked with me!
    location /anyfolder {
        error_page 404 /yourhandler.php?fnf=$uri;
    }

Answer: I think the problem is that you are using "try_files" along with an "if" statement in your location. From the documentation, try_files is supposed to be a replacement for if and mod_rewrite style existence check. From the nginx wiki, the "try_files" page ( http://wiki.nginx.org/HttpCoreModule#try_files ):
"try_files is basically a replacement for the typical mod_rewrite style file/directory existence check. It is supposed to be more efficient than using if - see IfIsEvil"
Check the "if" wiki page ( http://wiki.nginx.org/NginxHttpRewriteModule#if ):
"note: Before using if please see the if is evil page and consider using try_files instead."
So, try remove that if check and just staying with the "try_files". That should check for the existence of any page (including asd.php or anything else endind in .php) and fall back to index.php if it doesn't find it.
Comment: The if statement is to prevent a potential security hole described here: http://blog.martinfjordvald.com/2010/07/nginx-primer/ (linked from http://wiki.nginx.org/Configuration). It is one exception to the rule of not using if statements inside location blocks.
Answer: Richard, according to the Pitfalls guide its recommended to set "cgi.fix_pathinfo = 0″ in php.ini as it resolves a potential vulnerability between nginx and php.
Answer: I want to redirect all missing php files to custom internal /error404 error page. I will post my solution found during permutation.
error_page 404 /error404;

didn't help me. Neither did combinations of location, @missing, rewrite and break. But
location ~ \.php$ {
    # this is it! $fastcgi_script_name points to my url
    try_files $fastcgi_script_name = /error404;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_param SCRIPT_FILENAME /var/www$fastcgi_script_name;
    ...
    etc.


Determining Sample Size for ANOVA

Question:  So I'm pretty sure I'm thinking about this all wrong, but.. I'm trying to run an AB test on a web platform that will increase the total number shares to a social network (incredibly exciting, I know). This number has a mean of 30 shares per person, currently. The new mean should be around 40.
How do I determine the sample size for this experiment? Normally we'd throw some numbers into a calculator like baseline mean, the minimal detectable effect, etc. But all these calculators are designed for proportions, i.e. conversion rates, with the assumption that the proportion will be less than zero.
EDIT
We're revisiting this problem here and it's become much clearer what the goal is. The outcome of the experiment will affect a count (i.e. number of shares per user) and there will be multiple experimental variations. So the test that we'll end up using to find significance will be ANOVA. So the question then becomes, how do you calculate the sample size/power per experimental variation for ANOVA?
For context, the variations A, B and C, where C is control, will be split roughly at 5%, 5%, 90% of all traffic respectively. This of course could vary to get enough power faster.
Comment: Do you know the standard deviation? Do you expect the treatment to alter it?
Comment: I'm not expecting to see a change in the standard deviation between the experiment and control. Unfortunately I can't get to an actual number for the SD right now since the data is hard to get to. Is it completely necessary to have?
Comment: You will need the sd eventually to sure, but I can repeat the calculation for range. Can the treatment "harm"?
Comment: If by "harm" you mean decrease the mean, then yes, it's possible. Can you share with me the process that you're using?
Comment: It looks you're dealing with counts (0,1,2,...), not proportions. Your title is misleading/confusing. If you're prepared to assume a Poisson or Negative Binomial model it may be possible to do some kind of similar calculation.
Comment: @Glen_b Three months later and I'm finally getting back to this question. You're absolutely right about counts v proportions. I'll go ahead and edit the question.
Comment: In general, rather than use ANOVA for counts, I'd suggest a GLM suitable GLMs  (Poisson or negative binomial, perhaps) can do the equivalent analysis to ANOVA. If you do use ANOVA, I'd strongly suggest considering the Welch correction.
Answer: Here are the sample size calculations for a two-sample means test. This assumes an equal split between T (group 2) and C (group 1), which maximizes power. The diff column is the minimum detectable difference given alpha (the significance level), the power, and the standard deviation. N is the total sample size.
<code>. power twomeans 30, sd(5(5)30) alpha(.05 .1) power(.8 .9) diff(-10 10)

Performing iteration ...

Estimated sample sizes for a two-sample means test
t test assuming sd1 = sd2 = sd
Ho: m2 = m1  versus  Ha: m2 != m1

  +---------------------------------------------------------------------------------+
  |   alpha   power       N      N1      N2   delta      m1      m2    diff      sd |
  |---------------------------------------------------------------------------------|
  |     .05      .8      12       6       6     -10      30      20     -10       5 |
  |     .05      .8      34      17      17     -10      30      20     -10      10 |
  |     .05      .8      74      37      37     -10      30      20     -10      15 |
  |     .05      .8     128      64      64     -10      30      20     -10      20 |
  |     .05      .8     200     100     100     -10      30      20     -10      25 |
  |     .05      .8     286     143     143     -10      30      20     -10      30 |
  |     .05      .8      12       6       6      10      30      40      10       5 |
  |     .05      .8      34      17      17      10      30      40      10      10 |
  |     .05      .8      74      37      37      10      30      40      10      15 |
  |     .05      .8     128      64      64      10      30      40      10      20 |
  |     .05      .8     200     100     100      10      30      40      10      25 |
  |     .05      .8     286     143     143      10      30      40      10      30 |
  |     .05      .9      14       7       7     -10      30      20     -10       5 |
  |     .05      .9      46      23      23     -10      30      20     -10      10 |
  |     .05      .9      98      49      49     -10      30      20     -10      15 |
  |     .05      .9     172      86      86     -10      30      20     -10      20 |
  |     .05      .9     266     133     133     -10      30      20     -10      25 |
  |     .05      .9     382     191     191     -10      30      20     -10      30 |
  |     .05      .9      14       7       7      10      30      40      10       5 |
  |     .05      .9      46      23      23      10      30      40      10      10 |
  |     .05      .9      98      49      49      10      30      40      10      15 |
  |     .05      .9     172      86      86      10      30      40      10      20 |
  |     .05      .9     266     133     133      10      30      40      10      25 |
  |     .05      .9     382     191     191      10      30      40      10      30 |
  |      .1      .8       8       4       4     -10      30      20     -10       5 |
  |      .1      .8      28      14      14     -10      30      20     -10      10 |
  |      .1      .8      58      29      29     -10      30      20     -10      15 |
  |      .1      .8     102      51      51     -10      30      20     -10      20 |
  |      .1      .8     156      78      78     -10      30      20     -10      25 |
  |      .1      .8     224     112     112     -10      30      20     -10      30 |
  |      .1      .8       8       4       4      10      30      40      10       5 |
  |      .1      .8      28      14      14      10      30      40      10      10 |
  |      .1      .8      58      29      29      10      30      40      10      15 |
  |      .1      .8     102      51      51      10      30      40      10      20 |
  |      .1      .8     156      78      78      10      30      40      10      25 |
  |      .1      .8     224     112     112      10      30      40      10      30 |
  |      .1      .9      12       6       6     -10      30      20     -10       5 |
  |      .1      .9      36      18      18     -10      30      20     -10      10 |
  |      .1      .9      80      40      40     -10      30      20     -10      15 |
  |      .1      .9     140      70      70     -10      30      20     -10      20 |
  |      .1      .9     216     108     108     -10      30      20     -10      25 |
  |      .1      .9     310     155     155     -10      30      20     -10      30 |
  |      .1      .9      12       6       6      10      30      40      10       5 |
  |      .1      .9      36      18      18      10      30      40      10      10 |
  |      .1      .9      80      40      40      10      30      40      10      15 |
  |      .1      .9     140      70      70      10      30      40      10      20 |
  |      .1      .9     216     108     108      10      30      40      10      25 |
  |      .1      .9     310     155     155      10      30      40      10      30 |
  +---------------------------------------------------------------------------------+
</code>
The formulas used by Stata can be found here.
A free software alternative that easily handles unequal T-C allocations is G*Power.
Comment: The trouble here is that we don't want to assume a 50-50 split (i.e. the sample sizes shouldn't be the same). Looking through the STATA docs, there does seem to be support for that but it doesn't go into as much detail...
Comment: Sample sizes and the experimental-group means are obtained by iteratively solving the nonlinear equation (5). There's no easy formula. If you modify the original question with what sort of allocation ratio you're considering, I can modify the answer.

Determining Sample Size for ANOVA


Using Bootstrap Modal as Register and Login Form. On error the full page is served

Question: I am using jquery.bootstrap.modal.forms.js to load Login and Register form from their url as Modals using the code below:

HTML code for the modal

Register

          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            ×
          </button>

          <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
          <button type="button" class="btn btn-primary">Save changes</button>

Modal Code :
{% extends 'base.html' %}
{% load static %}

 {% block title %} Login {% endblock %}
 {% block style %}

 {% endblock %}

 {% block content %}

            <form class="account-register form-narrow p-3 mb-4 bg-white" id="login_form" method="POST"
                action="" autocomplete="off">
                {% if messages %}

                {% for message in messages %}

                    <button type="button" class="close" data-dismiss="alert"
                        aria-label="Close">
                    ×
                    </button>
                    {{ message|escape }}

                {% endfor %}

            {% endif %}
            {% if form.non_field_errors %}

                {% for message in form.non_field_errors %}

                    <button type="button" class="close" data-dismiss="alert"
                        aria-label="Close">
                    ×
                    </button>
                    {{ message|escape }}

                {% endfor %}

            {% endif %}

Login

                {% csrf_token %}

                    Email Address
                    <input class="form-control input-lg" id="id_username" maxlength="150" name="username"  pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$" type="text" required />

{{ form.username.errors }}

                    Password

                    <input class="form-control input-lg" id="id_password" name="password" type="password" required />

{{ form.password.errors }}

                <button type="submit" name="login"
                    class="btn btn-danger btn-sm btn-block text-uppercase shadow-4 mb-4" >
                Login
                </button>

                    Don't have an account?<button type="button" class="register-btn a btn btn-link" style="font-size:14px; margin-top:-4px;">Register </button>

                    <button  type="button" class="forgot-password a btn btn-link" style="font-size:14px; text-decoration:none;">Forgot user ID and/or password? </button>

            </form>

 {% endblock %}

 {% block scripts %}

{% endblock %}

LoginView Code
class LoginViewModal(FormView):
    template_name = 'login-modal.html'
    form_class = LoginForm
    success_url = '/dashboard'

    def get(self, request, *args, **kwargs):
        if request.user.is_authenticated:
            return redirect ("/dashboard")
        else:
            return super(LoginViewModal, self).get(request, *args, **kwargs)

    def dispatch(self, request, *args, **kwargs):

        if (self.request.user.is_authenticated) and (self.request.user.user_type==4):
            return redirect('/dashboard')
        else:
            return super().dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        """Use this to add extra context."""
        context = super(LoginViewModal, self).get_context_data(**kwargs)
        if 'show_captcha' in self.request.session:
            show_captcha = self.request.session['show_captcha']
            context['show_captcha'] = True
        return context

    def form_valid(self, form):
        user = form.login(self.request)

        recaptcha_response = self.request.POST.get('g-recaptcha-response')
        url = 'https://www.google.com/recaptcha/api/siteverify'
        payload = {
            'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY,
            'response': recaptcha_response
        }
        data = urllib.parse.urlencode(payload).encode()
        req = urllib.request.Request(url, data=data)

        # verify the token submitted with the form is valid
        response = urllib.request.urlopen(req)
        result = json.loads(response.read().decode())
        if result['success']:
            if user.two_factor_auth is False and (user.phone_number_verified is True):
                login(self.request, user)
                try:
                    UserLog.objects.filter(username=user.id).update(failed_attempt=0)
                except Exception:
                    print("No failed attempts ")

                return redirect('/dashboard')

            else:
                try:
                    response = send_verfication_code(user)
                    pass
                except Exception as e:
                    messages.add_message(self.request, messages.ERROR,
                                        'verification code not sent. \n'
                                        'Please retry logging in.')
                    return redirect('/login')
                data = json.loads(response.text)

                if data['success'] == False:
                    messages.add_message(self.request, messages.ERROR,
                                    data['message'])
                    return redirect('/login')

                if data['success'] == True:
                    self.request.method = "GET"
                    print(self.request.method)
                    kwargs = {'user':user}
                    return PhoneVerificationView(self.request, **kwargs)
                else:
                    messages.add_message(self.request, messages.ERROR,
                            data['message'])
                    return redirect('/login')
        else:
            messages.add_message(self.request, messages.ERROR, 'Invalid reCAPTCHA. Please try again.')
            return redirect('/login')

When an error occurs in the form (for example if the user enters incorrect password. The modal redirects to /login-modal/ and a full page with login form is seen instead of returning to the same modal. What can I do in order to stay on the modal when error occurs ?
Answer: Correct me if I am wrong, what you are trying to achieve here is that when a user enters incorrect credentials, for example, you want to show an error message on the page without having to reload so that the credentials are not lost? if that is the case, you must use AJAX/fetch API, I'd go for AJAX since you're already using jquery, you can send the data using jquery $.post
Implementing AJAX with Django is a bit complicated but a simple google search would do, this tutorial explains how to implement a login and signup mechanism using ajax and Django.
Now if you just want to show the modal again when an error you could have an error variable as a boolean, with 0 being no errors and 1 being the opposite, and pass it to your front-end, and have a script tag in your HTML that will trigger the modal when there is an error.
Comment: All, I want it that when the form returns error, it should not redirect to /login-modal/ instead it should remain at / and error should be displayed inside the modal. Since I am loading a url inside the modal, or error it always redirects to /login-modal/
Comment: Yes, then you must use AJAX to verify the credentials and catch errors, and only redirect on success.
Comment: well I am validating my form on submit.
Comment: That's front-end verification, you need the actual server to verify everything and attempt to log the user in, without refreshing or redirecting except on success, and I do not see any AJAX in your code to do that.


web service deployment does not appear in weblogic admin console

Question: We have an ear project created with Netbeans 8.1 and the Maven Project wizard. Running WLS 12.1.3. The project contains some EJBs and a jax-ws web service using the standard jax-ws annotations.  For some reason, I cannot get the web service to show up after deployment in the admin console as shown below.

However, the web service is deployed, and running properly, but then we cannot admin the deployment config, or monitor, etc.  The strange thing is that the corrsponding
servlet does show up on the testing tab.  Does anyone know what would cause this?
Answer: The web service should be running withing a Web Application.  I presume you have packaged the web service within a war file within the ear.  The web application specification will contain the context root.  Depending on your servlet mapping, or more paths within the context root will be handled by your web service.
Comment: Yes, to all the above.


Homebrew's formula-like object creation in Ruby

Question: I'd like to create an object in Ruby by extending a class (like in Homebrew):
class Somepackage < Formula
    version "2.8"
    homepage "http://foo.bar.com/"
end

However, I'm a Ruby recruit and I can't find a way to define the Formula class that would fit my needs:
class Formula
    attr_reader :version, :homepage
    def self.version (version)
        @version = version
    end
end

This obviously doesn't work:
Somepackage.version #=> nil

(I need it to return 2.8)
I know it must be a very simple thing to do, but I tried various combinations and just can't make it.
Update
Ok, so, thanks to Sergio's answer, the final version looks like this:
def property(*properties)
  properties.each do |prop|
    self.class_eval("def self.#{prop}(#{prop} = nil); @#{prop} = #{prop} if #{prop}; @#{prop}; end")
  end
end

class Formula
    property :version, :homepage
end

class Somepackage < Formula
   version "2.8"
   homepage "http://foo.bar.com/"
end

Answer: Note that your attr_reader methods are on instance level. To call them you'd need to do this
Somepackage.new.version

which obviously was not your intent. You can promote them to class level like this:
class Formula
  class << self
    attr_reader :version, :homepage
  end

  def version(version)
    @version = version
  end
end

But here's a problem as well. Your second version of version overwrites version from attr_reader. As a result, you have a method which can set values, but not return. After some experiments, you'll end up with something like this:
class Formula
  def self.version(version = nil)
    if version
      @version = version
    end

    @version
  end
end

class Somepackage < Formula
  version "2.8"
end

Somepackage.version # => "2.8"

Make your own version for homepage. Or, better yet, write a method that generates these methods, so that you can just do
class Formula
  property :version, :homepage
end

Comment: Following your advice, I wrote the method-generator method and posted its source in my question update. Thank you! :)


Need help calculating number of possible passwords with given criteria

Question: I need help calculating the number of possible passwords with a given set of criteria. Here is the set of criteria:

Passwords are case insensitive.
Must be 6-14 characters.
Must contain at least 1 letter and 1 number.
Must not be equivalent to your current or 3 previous passwords.
May not contain 9 or more numbers.
May not be identical to your Username.
May not repeat the same number or letter more than 3 times in a row.
May not contain more than 3 sequential numbers or letters (such as '1234' or 'abcd') in a row.
May contain special characters (such as @, %, &, #).

Any help would be greatly appreciated.
Comment: Please do not cross-post. That is against SE policy. Decide which site you want your question on & delete the other version.
Comment: What kind of passwords are case insensitive?
Comment: The system changes the to lowercase and stores them that way. Not a good practice.
Comment: I think you need to state the rules more clearly. For instance, exactly how many special characters are there which are allowed (you listed 4 of them)? Ruling on '0123' , '7890', '9012', etc.? "May not repeat the same number or letter more than 3 times in a row" is ambiguous (specifically, "repeat") - does that mean "May not have the same number or letter more than 3 times in a row"?  Results will vary with user and password choice time for previous password and Username rule, but that's at most a subtraction of 5 possible passwords.
Comment: No problem. Assume all standard keyboard special characters (32 chars). No, '0123' would not be allowed, but '0987' would be allowed, as they are not numerically sequential. Yes, "May not have the same number or letter more than 3 times in a row". I generally know how to approach this problem by calculating on possible passwords, and then subtracting based on the criteria. I'm struggling with how to calculate some of the criteria. Thanks for your help.
Comment: What writing systems are allowed? For example, are any of the following characters permitted? é, $\zeta$, $\aleph$, ひ, پے
Comment: ASCII only allowed
Comment: This IS on-topic here, but [math.SE] might want a crack at it too :)
Comment: @dprofancik [*Which* ASCII](https://en.wikipedia.org/wiki/ASCII)?
Comment: Assume 7-bit ASCII (1234567890abcdefghijklmnopqrstuvwxyz~!@#$%^&*()_+`-={}|[]\:";'<>?,./).
Comment: If you're content with an approximate answer, you could consider using simulation to estimate the fraction of all possible length k passwords composed of the 68 allowed characters, i.e. $68^k$, which are in compliance with the rules.  Do separately for k = 14, 13, etc.  There might also be some clever ways to incorporate some of the rules restrictions into the simulated candidates, then estimate the fraction of those which are in compliance with the remaining rules.
Answer: No one has provided an exact answer, so I'll discuss approximations. If you're content with an approximate answer, you could consider
I. Use simulation to estimate the fraction of all possible length j passwords composed of the 68 allowed characters (26 letters, 10 numbers, 32 special characters), i.e. $68^j$, which are in compliance with the rules. Do separately for j = 14, 13, etc. Multiply the fraction in compliance by the number of passwords of that length, and sum over lengths of 6 to 14.  There might also be some clever ways to incorporate some of the rules restrictions into the simulated candidates, then estimate the fraction of those which are in compliance with the remaining rules.
or
II. An upper bound approximation (code strands are in MATLAB, but they should be understandable by all):
There are 68 allowed characters, so if no passwords were disallowed, there would be sum(68.^(6:14)) = 4.587e25 possible passwords.
For a length j password, there is
$P$(no numbers) + $P$(no letters) - $P$(no numbers or letters) =
$(58/68)^j+(42/68)^j-(32/68)^j$ probability of not having at least one number and one letter.  The probability of not having at least one number is dominant within this.
That comes out as follows:
   j    P(not having at least one letter and one number in password of length j)
   6             0.429706323418485
   7             0.357603415290630
   8             0.298900283824793
   9             0.250880451281631
  10             0.211340972742333
  11             0.178563920283941
  12             0.151226117928902
  13             0.128306817799266
  14             0.109011434066698

So, decrementing the total number of passwords of lengths 6 to 14 only by those disallowed due to not having at least one number and one letter, results in a total of
sum(68.^(6:14).*(1-((58/68).^(6:14)+(42/68).^(6:14)-(32/68).^(6:14))))

= 4.086e+25 passwords.
The probability of not having 9 or more numbers given at least one exceeds 0.99996.  I believe that disallowance due to all other reasons would only contribute a "very small" decrement, although I have not quantified that.  Therefore, the number of allowed passwords will be "a little less" than 4.086e+25, if I haven't made a mistake. I leave any further refinement to others.  But this is probably "good enough for government use".


What is ?reqp=1&reqr=... at the end of my URL? Malicious?

Question: I'm not sure if this is a StackOverflow or more of a Programmers kind of question, but several others here have asked similar questions.
While scanning my Google Analytics account, I noticed a few exit links were tagged with the query string:
<code>?reqp=1&reqr=[....]</code>
There's no mention of it on StackOverflow, couldn't find anything in Google other than some sites that looked malicious, and I'm a bit worried.
Does anyone know how to find out what this could be? And if so, could you please point me to a JavaScript and/or Rails code solution (if it's actually a problem)?
Thanks!
Comment: "solution" usually implies a problem, so what are the symptoms?
Comment: I clarified that sentence. I'd like to know how to find out what this is, and then if it's a problem, how should I fix it. No need to seek a solution if it's not a problem :)
Comment: you can't control what URLs your clients will hit, only the result of hitting a given url. Extensions, userscripts, etc can all dance upon your html as they see fit.
Comment: You're right. I only asked this question because I've never seen query strings like that on any of my sites. When that kind of thing happens at work, it's usually someone trying to do something nasty.
Comment: i could be something, but unless it causes issues, i would consider it more noise than signal.
Answer: this is dns hi-jacking at its finest. Just carefully check to see where the domain resolves and that its configured correctly. Blame your host if you are landing on one of their parking pages.
Answer: From my experience, the ending of a domain name having "?reqp=1&reqr=" usually indicates that the hosting package has not been purchased or expires. You should contact your hosting company to see what hosting packages are available for you. Hope this helps and have a great day!


how to add number for every content in views?

Question: i useing drupal 8.
i create ResTful export with views.
my site have several content type and i use several views for any content type.
but in clinet(android) i need have list with specified numbers...so i cant use Nid(Because i have several content type)
how i can add number for every content in my views?
(such as this pic that firefox add number(0)to my every content)
(upside down number this image)

Answer: You can add a Field in Views that counts the result rows. The Field is called View result counter and you can find it under Global Category.
Humans usually prefer to start count at 1, but there is an option in that Field settings to set the Starting value so you can use zero.
I haven't tried it with Rest export, grouping like in your screenshot won't work. It will just be one of the fields.
Comment: i think thats what I wanted! but i think drupal have bug for restful export with View result counter !
https://i.stack.imgur.com/RPFBE.png
Comment: Yes it seems there is a bug. What version are you using? Will you report it if you don't find an existing one? https://www.drupal.org/project/issues/drupal?text=restful+services+views&status=All
Answer: Mahdi Baghery,
You can customize the JSON response using views plugin that extends Serializer
like https://cgit.drupalcode.org/one_api/tree/src/Plugin/views/style/SerializerCount.php
The above SerializerCount.php code is used to add pager to ResTful export like http://one-drupal-demo.technikh.com/onedrupal/api/v1/content?page=1
{
results: [],
pager: {}
}

This JSON is parsed by Drupal 8 Android app at https://github.com/onedrupal/One-Drupal-Android. https://play.google.com/store/apps/details?id=com.technikh.onedrupal


Regular expression matching unescaped paired brackets and nested function calls

Question: Here's the problem: given a string like
"
The price for vehicles {capitalize(pluralize(vehicle))} is {format_number(value, language)}
{employee_name}\{do not parse me}"

I need (1) a regex pattern in PHP that matches all values between un-escaped pairs of curly brackets and (2) another regex pattern that matches function calls and nested function calls (once the first pattern is matched). Of course, if I could use one regex only for both tasks that would be awesome.
By the way, I can't use Smarty, Twig or any other library - that's the only reason I have to build a parsing mechanism myself.
Thanks a ton!
Solution
(1) A partial solution for the first problem can be found here. Basically, we use the regex (?={((?:[^{}]++|{(?1)})++)}) and find the matches at index 1 of the resulting array.
It's partial because I still need to find a way of ignoring escaped braces, though.
(2) I'm considering the use of recursive regex, as suggested by Mario. Will post result here.
Thanks, guys!
Comment: You can use a negative lookbehind `(?<!\\\\)` for eschewing escaped curlys, and a [`(?R)` recursive regex](http://php.net/manual/en/regexp.reference.recursive.php) if you want to assert proper function nesting.
Comment: Is [this](http://www.regex101.com/r/uI4qN0) what you're looking for?
Comment: The first regex is easy, but the second one can't be done using PHP. You will have to use a parser instead.
Comment: Regular expressions are not a good choice for parsing nested / recursive structures.
Comment: Thanks for the answers. I found a way to solve (1) [here](http://stackoverflow.com/questions/16258143/get-all-nested-curly-braces). I still haven't been successful with (2).
Comment: @mario I didn't know that there is anther language than .NET that supports nested structures, +1 for that.
Comment: @Jerry - If you're game to recap the solution as your own answer, I'll delete my answer. (See http://meta.stackexchange.com/questions/90263/unanswered-question-answered-in-comments for elaboration of why this is helpful.) Thanks!
Comment: @DreadPirateShawn I just wanted to make sure that this is what OP required, but they didn't revert back... I try to avoid instances where OP has one problem which turns out to be a completely different problem ^^ You can keep your answer :)
Comment: @Jerry - Completely understood. I just found myself re-attempting to solve the regex before noticing your comment. Not to mention, your solution appears to solve the OP's needs by my reading as well - may as well flag as a viable answer candidate.
Answer: Copying the answer from the comments in order to remove this question from the "Unanswered" filter:
This appears to be what you're looking for:
(?<!\\){([^(){}]+)\(((?:[^(){}]+|\(((?2))\))*)\)}

Link: http://www.regex101.com/r/uI4qN0
~ answer per Jerry
Note: For comparison - simply ignoring escaped braces is accomplished by adding a negative lookahead (?<!\\) to the beginning of the expression, like so:
(?<!\\)(?={((?:[^{}]++|{(?1)})++)})


Node Export being downloaded as a .sh file and unable to be imported

Question: In my Drupal 7 project, I have some content of a custom content-type (page) that I need to import into another environment.
When I go to this content instance, I select on Node Export, which then gives me the option to download the file. When I download the file, it is downloaded as -.sh. In my other environment where I want to import this content using a Node Export Import, it says that that file isn't allowed..
How is it possible that you aren't able to use a Node Export for a Node Export Import??? That makes absolutely zero sense.
Answer: You can Import and export the content by using "Node Export with Features".
need to enable this module under node export module.
next, you have to go this URL admin/structure/features/create
and create the feature with the particular content type of content and download the module. next, this module you have to enable in another site.
content will be created.but make sure content type of fields same in two sites.


How to send what ever list of DTOs are ready from(spring-boot) as a backend to the front(angular-12)?

Question: I have long list from Execution entity and after some process fill related ExecutionDto, the DTO is like this,
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ExecutionDto {

    private long OrgUnitId;
    private long countsDone;
    private long countsShouldBe;
    private float progressPercentage;
    private double countsIndicator;
    private String OrgUnitDisplayName;

}

the method that processes Execution return list of ExecutionDto is like this,
public List<ExecutionDTO> processExecutions(){
// some proccess and return list of ExecutionDto
return listOfExecutions;

}

I don't want to use pagination and send what ever data is ready to the front and not wait the completed list, How can I do this?
and my web rest method is like this,
  @GetMapping("/executions/procces")
    public ResponseEntity<List<ExecutionDTO>> proccesedExecutions(){
    // get list of ExecutionDtos from related service
        return ResponseEntity.ok().body(executionDTOs);
    }

I expect gradually list to complete but front wait until back-end completed list, it takes a lot of time to complete the list of ExecutionDtos,
Comment: http is one response per one request. That said, you can probably choose to not close/commit the stream until you get the complete list and keep writing to the response body stream and close it once its done. I am not sure, with spring you will get such fine level controls
Answer: To stream a list you should use WebFlux and return something like Flux<List<ExecutionDTO>>.
You'll need a reactive data store though to realistically stream results as the database returns them (e.g. MongoDB).
Comment: A Flux can return a `MediaType.TEXT_EVENT_STREAM_VALUE`, and the client can subscribe to the server sent events in the stream.

See an example at https://www.baeldung.com/spring-server-sent-events
Comment: what is the point of using Flux in this case if you return Flux> ? Then you should return Flux
Comment: you mean if I use just Flux and add WebFlux as a dependency  my front doesn't wait until completed list?


Linear Combinations and solutions [Columnwise Description of Matrices]

Question:
Let $A$ be a $5\times 3$ matrix.
If $b = a_1 + a_2 = a_2 + a_3$ where $a_1, a_2, a_3$ are columns of $A$ then what can we conclude about the number of solutions of the linear system $Ax = b$?

Same Question for: when $b = a_1+a_2+a_3+a_4$
This query is from this Book page number 62
I am stuck at: let $a_1=[1,0,0]$, $a_2=[0,1,0]$ and $a_3=[0,0,1]$ but upon $a_1+a_2$ and $a_2+a_3$ these are not equal. such as $[1,1,0]$ and $[0,1,1]$
Comment: What do you think? We are not here to blindly answer your homework questions, but can help you if you are stuck. It may also help to give the page number of the problem in the book so we can read the context surrounding it
Comment: i am stuck at:
let a1=[1,0,0], a2=[0,1,0] and a3=[0,0,1]
but upon a1+a2 and a2+a3 these are not equal. such as [1,1,0] and [0,1,1]
Answer: The rank of a matrix can be defined in many ways, in particular (i) maximum number of linearly independent rows (ii)maximum number of linearly independent columns (iii)maximum size of square sub-matrix with non-zero determinant. You should be comfortable with all 3 versions and know why they are equivalent. For your immediate purpose, (ii) is the most relevant. The rank of the augmented matrix of a system of linear equations is either the same as, or one more than, the rank of the coefficient matrix. The system is consistent iff the the rank of the augmented matrix is the same as the rank of the coefficient matrix. You can take it from there.
Answer: $A$ has $5$ rows. Let $\{e_1,e_2,e_3\}$ be the standard basis of $ \mathbb R^3.$
Then we have
$$Ae_j=a_j$$
for $j=1,2,3.$
Can you proceed ?