Keyboard-style vs upright-style digital piano

Question: I know it's a very objective question, but I hope I can get some input.  I was considering buying a Yamaha CLP-535 piano (or equivalent Kawai, or Roland).  Those pianos have a price tag of approximately $2,500, but they seem to be very good at mimicking acoustic upright pianos.
High-end keyboard style digital pianos like DGX-660, P-115 or their equivalents come in at around $1,000, but appear to be highly praised.
I am not after the extra features.  While they are very nice to have, I prefer having an instrument that is as close to an acoustic piano as possible.
Would you have suggestions, recommendations, opinions on this matter?
Comment: *As close ..as possible*: in what respect: sound, keyboard feeling, optically? I consider the keyboard  feeling the most important, and unfortunately this is the expensive part. Note, that there are also stage pianos with very good keyboards if transportability is an issue. My recommendation: try keyboards, advice is not of much help here.
Comment: Strongly related [question](http://music.stackexchange.com/q/47889/2600)
Comment: You *may* find it's less costly in Europe, given virtual parity Euro-$, well less than 2k. Although postage will affect the overall deal.
Comment: @Tim After the conversion rate and the postage, it's not going to make any difference.  Besides, I simply loaded this on the back of my truck and now it's in my home.  Zero hassle.
Answer: In your particular case, where you say you "prefer having an instrument that is as close to an acoustic piano as possible", I would recommend going for the bigger purchase.
I own and have played quite a bit on a Yamaha P115 and a Kawai ES100. I like them both a lot (and probably prefer the Kawai). I would recommend them to anyone looking for a affordable and/or portable 88-key keyboard.
I like the key feel of both them - it's really quite great. However, I don't think I would ever mistake the feel of these to instruments for the feel of an acoustic piano.
Please note that I do not have any experience playing on the CLP-535, but this reddit thread asking whats "the best feeling digital piano" seems to support the idea it has very good key feel. Excerpts:

The CLP-535 with their GH3X action is great.
I own a Yamaha CLP-535 and much prefer the touch and voicing over the similarly priced kawai models. But this is a personal thing. The CLP series pianos are great.
Comment: Thank you for the input.  I went out with my family and spent the entire day testing out different keyboards and pianos.  I could definitely hear and feel the difference between the cheaper models and the higher-end models (especially the feel).  We narrowed it down to the simiarly-priced CN35 and CLP-535.  While I liked CN35 feel just a tiny bit better, CLP-535 sound was simply stunning.  I think both are fantastic instruments, though.  In the end, we have decided to purchase CLP-535. :)
Answer: The keyboard mechanisms in 'stage' and 'furniture' versions are identical.  There will be room to put better speakers in a 'furniture' model (though this opportunity is not always taken up).  The best sound will be from good-sized external speakers, but home users usually rule these out on grounds of appearance.
Whatever you choose, if you look for differences from a real piano you'll find them very easily.
Comment: No regrets in buying our CLP-535.  We went to an actual piano dealer who had hundreds of pianos available (even a few Bösendorfer grand pianos).


Visual Ways to Remember Cross products of Unit vectors? Cross-product in $\mathbb F^3$?

Question: Objective to find visual and accessible ways to remember this formula fast
$$(x,y,z)\times(u,v,w)=(yw-zv,zu-xw,xv-yu)$$
I have used Sarrus' rule but it is slow, more here. Since it is slow, I have tried to find alternative ways such as binary-tree -visualization (but it is poor/slow until some clever ideas):

RobJohn's idea to "just cycle the permutation"
$$\begin{align}i&=j\times k\\j&=k\times i\\k&=i\times j\end{align}$$
Mariano Suárez‐Alvarez -idea

View the 3×3 matrix as the points of the affine plane over F3: then
  the terms in the determinant correspond to affine lines which are
  neither horizontal nor vertical --.

Anon's idea

Draw a triangle with vertices i, j, k with arrows i->j, j->k, k->i.
  Multiplying two of these units is done as follows: if they are the
  same, 0; if they go with the flow of the triangle, the third in the
  line; if the go opposite the flow, the third one as well but with a
  minus sign

We are discussing this issue more here.
Comment: You should elaborate why you think that the above mentioned ways are insufficient.  Saying that they are "poor/slow" is not descriptive enough.
Comment: The arrows in category theory encapsulate broad categorical data between various algebraic structures, topological spaces, etc. and their morphisms - it is a bit out of place to use it to describe the visual mnemonics here.
Comment: @anon: sorry? Small is beautiful: you can break things such as $-$, $*$, $\times$ and even numbers into functions (soon becoming theoretical cs though) -- and then formulate a category-theoretic description for the cross-product. Look we can find visual way but we may need to dig a bit. Although it may sound trivial, I think it could be quite educational, not sure whether need to dig into mathematical-logic or something like that, anyway the puzzle is set :)
Answer: I usually teach this (which requires no additional writing and avoids cyclic permutations, which are often confusing for students):
$$
\left[\begin{array}{c}
x \\
y \\
z
\end{array}\right]
\times
\left[\begin{array}{c}
u \\
v \\
w
\end{array}\right]
$$
1) ignore $x$ and $u$ (that is: mentally block view of the first row), compute $2\times 2$ determinant of remaining stuff $yw-zv$
2) mentally block view of the second row, throw in a minus, compute $2\times 2$ determinant
3) mentally block view of the third row, compute $2\times 2$ determinant
instead of mentally blocking your view, you can put a pencil on that row
Answer: I really truly believe it's hard to beat the $3\times 3$ determinant mnemonic.
However, there is a trick for $3 \times 3$ determinants which make computing them a snap.
Remember that you compute a $2 \times 2$ determinant by multiplying diagonals and off-diagonals (the upward diagonal) and taking the difference. You can do the same for $3 \times 3$'s...well, sort of. You just repeat the first two columns. Then subtract the products of the up diagonals from the products of the down diagonals.
By the way, RobJon and Anon's suggestions amount to the same thing. Commonly drawn as a circle (see below). I refer (for no apparent reason) to this as the "circle of doom". It helps you remember cross products among the standard basis as well as how to multiply quaternions (which amounts to nearly the same thing). Go clockwise and get: $ij=k$, $jk=i$, $ki=j$. Fight the circle and get negatives: $ji=-k$ etc.

Edit:
@Blah's post is quite similar to what I use when teaching the cross-product. However, instead of columns, I usually write the vectors in rows and write out the cross product like an elementary school multiplication. Then the cross product is computed by ignoring the first, second, third columns in order; computing the corresponding $2 \times 2$ determinant; and negating the middle term [which really just amounts to using the determinant mnemonic, but involves less writing]. This is easier to implement than the $3 \times 3$ trick I showed above and is applicable when computing curl [see anon's comment below].
$$\begin{array}{cccccc} & \langle & v_1, & v_2,& v_3 & \rangle \\ \times & \langle & w_1,& w_2, & w_3 & \rangle \\ \hline & \langle & v_2w_3-w_2v_3,& -(v_1w_3-w_1v_3),& v_1w_2-w_1v_2 & \rangle \end{array}$$
Comment: Note 1: the order of the terms as written in the Sarrus rule depiction here are inapplicable when computing the curl $\nabla\times\mathbf{F}$: partial derivative operators go before the quantities they act on. (This was the basis of another one of OP's questions.) Note 2: Quaternions can in fact be written as a formal sum of a scalar and a vector; multiplication is computed as $$(a+\mathbf{b})(c+\mathbf{d})=ac-\mathbf{b\cdot d}+a\mathbf{d}+c\mathbf{b}+\mathbf{b\times d}.$$ With scalar parts zero, $a=c=0$, the resulting vector part is just the cross product.
Comment: @anon Ah, yes. Curl, a mnemonic inside a mnemonic :)
Comment: Where in the world did you ever get the name "circle of doom" for such an innocuous little mnemonic? I see you comment that you use this name for no particular reason, but still...
Comment: @KCd I think I had a student complaining about remembering how the cross product worked. My response went something like "Not remembering the formula for the cross product will spell out your doom." But, yes, there's no *good* reason to call it that. :)
Answer: Perhaps this is no more clear, but I found it easy to remember as a matrix product after the first vector is changed into a skew-symmetric matrix (see the Wikipedia here).
$$
\left[\begin{array}{c}
x \\
y \\
z
\end{array}\right]
\times
\left[\begin{array}{c}
u \\
v \\
w
\end{array}\right]
=
\left[\begin{array}{ccc}
0 & -z & y \\
z &  0 & -x \\
-y & x & 0
\end{array}\right]

\left[\begin{array}{c}
u \\
v \\
w
\end{array}\right]
$$
Comment: How do you remember the way this matrix looks like?
Comment: This is the way i remember.  (1) Diagonal is always zero, (2) starting from element 1,1 and proceeding CW, the axes are in reverse order (i.e. z, y, x).  (3) Signs, I just remember that the same CW sequence is -, +, -  or you can just get the signs by knowing that they alternate and that $x \times y = z$.
Answer: This works wonderfully for me:
Say ${\bf  x}=(x_1,x_2,x_3)$ and ${\bf y}=(y_1,y_2,y_3)$. Then
$${\bf  x}\times {\bf y}=\left(\begin{vmatrix} x_2&x_3 \\y_2&y_3 \end{vmatrix},-\begin{vmatrix} x_1&x_3 \\y_1&y_3 \end{vmatrix},\begin{vmatrix} x_1&x_2 \\y_1&y_2 \end{vmatrix}\right)$$
You can also remember it by a cover method of the arrangement
$$\begin{vmatrix}  x_1&x_2&x_3 \\y_1&y_2&y_3 \end{vmatrix}$$
First coordinate: $$\begin{vmatrix}  \bf X&x_2&x_3 \\\bf X&y_2&y_3 \end{vmatrix}$$
Second coordinate: $$\begin{vmatrix} x_1&\bf X&x_3 \\y_1&\bf X&y_3 \end{vmatrix}$$
Third coordinate: $$\begin{vmatrix} x_1&x_2&\bf X \\y_1&y_2&\bf X \end{vmatrix}$$
Comment: Basically the same as pen -rule [here](http://math.stackexchange.com/a/124403/5902), I like the pen -rule +1 :)
Answer: I am not sure whether this way could deduce the more advanced case but I will elaborate the RobJohn
$$
\begin{align}
\color{Red}{i}&=\color{Blue}{j}\times \color{Green}{k}\\
\color{Blue}{j}&=\color{Green}{k}\times \color{Red}{i}\\
\color{Green}{k}&=\color{Red}{i}\times \color{Blue}{j}.
\end{align}$$
Now the "bit -shift" is equivalent to cross-product by the left-hand-side -element. For example, to get from $ijk$ to $jki$ -- we product by the LHS element i.e. here $k$
$$\begin{align}k\times (\color{Red}{i})&=k\times (j\times k ) \\ j&=k\times \color{Red}{i}.\end{align}$$
Cross-product order with toruses

1. Torus
$$\begin{pmatrix} ... & ... & ... & ... & ... & ... & ... & ... \\ ...
 & \color{Red}{i} & \color{Blue}{j} & \color{Green}{k} & i & j & k &
 ... \\ ... & i & \color{Blue}{j} & \color{Green}{k} & \color{Red}{i} &
 j & k & ... \\ ... & i & j & \color{Green}{k} & \color{Red}{i} &
 \color{Blue}{j} & k & ... \\ ... & ... & ... & ... & ... & ... & ... &
 ... \\ \end{pmatrix}$$
2. Torus cut
$$\begin{pmatrix} ... & \color{Red}{i} & \color{Blue}{j} &
 \color{Green}{k} & i & \color{Blue}{j} & \color{Green}{k} &
 \color{Red}{i} & j & \color{Green}{k} & \color{Red}{i} &
 \color{Blue}{j} & k  &    & ... \end{pmatrix} $$
3. Simplified Torus
Basically you need only to remember the order $i,j,k$, then just a few
  repetition to get $i,j,k,i,j$. Read from left to right to get $ijk$,
  $jki$ and $kij$ -- we got our cyclic permutations!

Perhaps Related

Technical problem with this answer here about plotting.
Comment: math with colors is so much easier to read...! =)
Answer:
Answer: This method is how I memorize it. Personally, I don't really need a visual way if there is an easier method of simply memorizing it. Here goes:
Cross product of vector a=(x1, y1, z1) and b=(x2, y2, z2)
First write down i, j, k, with their respective parentheses, but in reverse order:
a x b = k( ... ) + j( ... ) + i( ... )
Now, just remember xyz twice, (XY-ZX-YZ). Basically, two letters go into the parentheses, in order:
$a \times b = k(xy ... ) + j(zx ... ) + i(yz ... )$
Next just write the same term again, but with a subtraction sign:
$a \times b = k(xy-xy) + j(zx-zx) + i(yz-yz)$
Finally, label each part by writing 1-2-2-1 in the subscript (I sometimes write the numbers on top of the letters just for convenience):
$a \times b = k(x_1y_2-x_2y_1) + j(z_1x_2-z_2x_1) + i(y_1z_2-y_2z_1)$
This is just one method that I figured out myself. Sorry I'm not too good at explaining this, but I hope it helps! I like this method because I don't need to take an extra part of the paper to draw out any diagrams or anything like that.
If you are planning to share this on another source, feel free to, but please comment below! (I just want to see if others are finding this useful)
Answer: First emphasis: Think of "x y z" as you would normally, in alphabetical order. From here, one can easily remember $\hat{x}\times\hat{y}=\hat{z}$. Second emphasis: Orthogonal unit vectors permute in cross-products. This produces $\hat{z}\times\hat{x}=\hat{y}$, and $\hat{y}\times\hat{z}=\hat{x}$ by iteration, giving us the full set:
$$\hat{x}\times\hat{y}=\hat{z}$$
$$\hat{z}\times\hat{x}=\hat{y}$$
$$\hat{y}\times\hat{z}=\hat{x}$$
Now, to address the visual approach (and help reinforce this). From the first emphasis, $\hat{x}$ is the first term and $\hat{y}$ is the second term. As many would count on their hands, we denote the first/inde$\hat{x}$ (haha) finger to point along $\hat{x}$, and the second/middle to point along $\hat{y}$. Then using the Right-Hand-Rule as shown in the image below, we know naturally the outcome to that cross product is $\hat{z}$ (along the thumb). You need only use the second emphasis to solve any combination.

I've included a drawn coordinate system as I find this gimmick to also be useful in always drawing coordinate systems correctly. Looking into the 1st octant in 3-space, the ordering must follow the alphabetic order counter-clockwise. You'll notice it agrees with the ordering of the RHR fingers.
This technically only covers 3 of the 6 possibilities. For completeness I'd like to note that generally, $\vec{A}\times\vec{B}=-\vec{B}\times\vec{A}$. So, if your inputs are switched, just slap a negative sign on the ouput.


Value of $ \sum \limits_{k=1}^{81} \frac{1}{\sqrt{k} + \sqrt{k+1}} = \frac{1}{\sqrt{1} + \sqrt{2}} + \cdots + \frac{1}{\sqrt{80} + \sqrt{81}} $?

Question: I tried my best, but I am totally clueless about it. Worse thing is we were supposed to arrive at the answer in approximately $ 2 $ minutes. The correct answer is $ 8 $, right? Can you kindly explain how to arrive at it? I hope it won't be too much bother. Thank you.
Comment: Are you sure you've got the question right? If the terms were multiplied, it would be easy.
Comment: @JanDvorak Sorry for the delay in replying to you.Yes, I have got the question right.I double-check things before putting them up on this reputed maths forum.
Answer: Note that
$$ \frac{1}{\sqrt{n} + \sqrt{n+1}} = \sqrt{n+1} - \sqrt{n} $$
Then you have a telescoping sum
Comment: Thanks Muzzlator for your fine answer.
Answer: As \begin{align}
\frac{1}{\sqrt{i}+\sqrt{i+1}} = \frac{\sqrt{i}-\sqrt{i+1}}{\sqrt{i}-\sqrt{i+1}} \cdot \frac{1}{\sqrt{i}+\sqrt{i+1}} = \frac{\sqrt{i}-\sqrt{i+1}}{-1} = {\sqrt{i+1}-\sqrt{i}}
\end{align}
Thus
\begin{align}
\sum_{i=1}^{80} \frac{1}{\sqrt{i}+\sqrt{i+1}} = \sum_{i=1}^{80} {\sqrt{i+1}-\sqrt{i}} = \sqrt{80+1} -\sqrt{1} = 8
\end{align}
Comment: A prof of mine always said, that "text is the shortest connection between two formulas" ;)
Answer: $$\frac{\sqrt{2} - \sqrt{1} }{(2-1)} +\ldots +\frac{\sqrt{81} - \sqrt{80} }{(81-80)}=\sqrt{81}-\sqrt{1}=9-1=8 $$
Comment: Thanks for your answer Jim.


Accessing the first Character of a String with no Characters

Question: I am implementing a suffix trie in C++. The implementation of the Trie contructor can be seen below.
#include <iostream>
#include <cstring>
#include "Trie.hpp"
using namespace std;

Trie::Trie(string T){
    T += "#";                           //terminating character
    this->T = T;

    nodes.reserve(T.length() * (T.length() + 1) / 2);   //The number of nodes is bounded above by n(n+1)/2. The reserve prevents reallocation (http://stackoverflow.com/questions/41557421/vectors-and-pointers/41557463)

    vector<string> suffix;              //vector of suffixes
    for(unsigned int i = 0; i < T.length(); i++)
        suffix.push_back(T.substr(i, T.length()-i));

    //Create the Root, and start from it
    nodes.push_back(Node(""));          //root has blank label
    Node* currentNode = &nodes[0];

    //While there are words in the array of suffixes
    while(!suffix.empty()){

        //If the character under consideration already has an edge, then this will be its index. Otherwise, it's -1.
        int edgeIndex = currentNode->childLoc(suffix[0].at(0));

        //If there is no such edge, add the rest of the word
        if(edgeIndex == -1){
            addWord(currentNode, suffix[0]);                //add rest of word
            suffix.erase(suffix.begin());                   //erase the suffix from the suffix vector
        }

        //if there is
        else{
            currentNode = (currentNode->getEdge(edgeIndex))->getTo();       //current Node is the next Node
            suffix[0] = suffix[0].substr(1, suffix[0].length());            //remove first character
        }
    }
}

//This function adds the rest of a word
void Trie::addWord(Node* parent, string word){
    for(unsigned int i = 0; i < word.length(); i++){                //For each remaining letter
        nodes.push_back(Node(parent->getLabel()+word.at(i)));       //Add a node with label of parent + label of edge
        Edge e(word.at(i), parent, &nodes.back());                  //Create an edge joining the parent to the node we just added
        parent->addEdge(e);                                         //Join the two with this edge
    }
}

I am using two data structures, Node and Edge which have some getters and setters and properties you would expect. The method childLoc() returns the location of an edge (if it exists) representing a given character.
The code compiles just fine, but for some reason I get this error at runtime:
terminate called after throwing an instance of 'std::out_of_range'
  what():  basic_string::at: __n (which is 0) >= this->size() (which is 0)
Aborted (core dumped)

I've been told that this error means I am accessing the first character of an empty string, but I can't see where this is happening in the code.
Comment: have you debugged your code with a debugger? e.g. compile with '-g' flag with g++, then use a gdb based debugger to step thru the code...
Comment: It is very difficult to help you with a run time error without being able to compile the example. You should step through the code with a debugger on your end. If you want an answer, you will need to reduce the example and provide input data that produces your problem. See [this link](http://stackoverflow.com/help/mcve) on how to produce a helpful example that will attract more answers.
Comment: So somewhere you have confused no string of sausages with a string of no sausages. Easy to do since and std:;string cannot be null, unlike a C char *.
Comment: @MalcolmMcLean, can you please clarify?
Answer: I see two code parts that are potentially responsible for std::out_of_range:
First: The following expression might access an empty string at position 0. This might happen as (as shown in the second part), you shrink strings contained in the suffix-vector:
int edgeIndex = currentNode->childLoc(suffix[0].at(0));

Second, you operate on the entries in suffix-vector with the risk that the strings are to short:
suffix[0] = suffix[0].substr(1, suffix[0].length());

Operation substr will also yield std::out_of_range if first operand (i.e. pos-argument) exceeds the array length (cf. string::substr):

pos: Position of the first character to be copied as a substring. If
  this is equal to the string length, the function returns an empty
  string. If this is greater than the string length, it throws
  out_of_range. Note: The first character is denoted by a value of 0
  (not 1).

For finding out which of these expressions is actually responsible for the exception, I'd suggest to consult your debugger :-)
Comment: Regarding the first remark, isn't the final string pushed of length `T.length()-(T.length-1)` = 1?
Comment: @Luke Collins: yes, you are right. I adapted the answer accordingly.
Comment: @LukeCollins `suffix[0].substr(1, suffix[0].length())` is going to fail on a 1 character string since there are no characters at index 1.  It's **also** going to fail for every string since the length argument is the full length of the string, yet you're starting at index 1 and hence overflowing the string by one.  If you want to get the string starting at a character index, it's easier to just leave out the length argument.  ie: `s.substr(1)`  gets everything after the first character assuming the string has more than one character to begin with.
Comment: @ebyrob: giving an excessive length to string::substr is not a problem; it's just a max. But you're right, the one-argument version is better.
Comment: @ebyrob Thanks for that. But the way it's written, the suffix[0].substr(1, suffix[0].length()) should never run for a 1 character string no?
Comment: @Like Collins: If `pos` is equal to the string length, the function returns an empty string.
Comment: @LukeCollins You yourself in the first comment to this answer said the last pushed entry would be a 1 character string.


XOR with Neural Network

Question: I'm trying to implement a simple neural network to fit a XOR function as shown in the book 'Deep Learning' by Ian Goodfellow, Yoshua Bengio and Aaron Courville (2016). Here is my python code using Keras :
<code>import keras
import numpy as np

# creating dataset
x = np.zeros((20000, 2), dtype=int)
x[5000:10000,1] += 1
x[10000:15000,0] += 1
x[15000:,:] += 1

np.random.shuffle(x)
y = [bit1 ^  bit2 for bit1, bit2 in x ]

x_train = x[:15000]
y_train = np.transpose(y[:15000])

x_test = x[15000:]
y_test = np.transpose(y[15000:])

# generating keras model
model = keras.models.Sequential([
  keras.layers.Dense(2, input_shape=(2,)),
  keras.layers.Dense(2, activation='relu'),
  keras.layers.Dense(1, activation='relu')
])

# compiling using stochastic gradient descent and MSE
model.compile(optimizer='SGD',
              loss='mean_squared_error')

# fit and evaluate
model.fit(x_train, y_train, epochs=5)
model.evaluate(x_test, y_test)
</code>
The issue is that I'm stuck with a loss equal to 0.5,
does anyone know what I'm missing here ?
Answer: In addition to the other answer, note that you're currently training only on examples of x = [0,0], [0,1] and [1,0], and testing only on x = [1,1]. So your network actually has no way of learning the full XOR mapping, and wouldn't be expected to generalize to the test set. Also, you really don't need this many training examples, because you're just repeating identical information. Just all 4 possible inputs (combinations of 0 & 1) with their desired outputs would suffice. And then you can train using full batch gradient descent - no need to use SGD.
Answer: Firstly, you want to add a non-linearity to your first layer. If you don't mention it, you effectively only have one hidden layer.
Secondly, because you expect your output to be either 0 or 1, you should treat this as a classification problem. So, modify the final activation to be 'sigmoid', and change your loss function to 'binary_crossentropy'.
Finally, increase the number of epochs so that the network has enough time to learn.
Hope this helps!

XOR with Neural Network


Neo4j from JavaScript login info

Question: For the code below how do I get the username and password.  From  enter link description here
var driver = neo4j.driver("bolt://localhost", neo4j.auth.basic("neo4j", "123456"));
var session = driver.session();

Is it my ID when I login?

or is it the database name and password?

I tried both ways still having trouble.
Comment: I think the default is neo4j:neo4j... login into web browser and it will ask you to change your password
Answer: It's the latter, but the database name doesn't play a part here.
The database name in this case is only for your own reference within the Neo4j Desktop app.
The default database user is neo4j, and the app forces you to choose the password when you create the database, so you should know the password.
Answer: You can disable authentication. Just uncomment dbms.security.auth_enabled=false in config file. So you will not have problems with authentication. The default username and password are neo4j:neo4j

Neo4j from JavaScript login info


Delete Query not working (No bugs/syntax errors)

Question: <input type="hidden" name="code"
        value="<?php echo $product['productCode']; ?>">
<input type="submit" value="Delete">

// Get ID
$code = filter_input(INPUT_POST, 'productCode', FILTER_VALIDATE_INT);

// Delete the product from the database
if ($code != false) {
    $query = 'DELETE FROM products
              WHERE productCode = :productCode';
    $statement = $db->prepare($query);
    $statement->bindValue(':productCode', $code);
    $success = $statement->execute();
    $statement->closeCursor();
}

The code at the top is trying to get the code into where the php/MySQL code at the bottom of the screen here. There's no bugs that fly or trigger when the code runs in the webpage, and the code doesn't flag anything in the editor. I'm really at a loss for what's going wrong here, and no one that I ask has any idea what's wrong. Any help would be appreciated!
Comment: I think it might be an idea to reinitialise $code
Answer: table field is prdocutcode why are you only name is code replace below  my code
 <input type="hidden" name="productCode" value="<?php echo $product['productCode']; ?>">

Answer: Can you log out the :productCode? It's possible that the value is not what you think, and a delete for a non-existent item will happily report nothing if no match is found.
Answer: I think you have HTML and PHP codes in the same file.
What might be the issue:
Add condition if the form is posted, go for deleting product.
if (isset($_POST['productCode'])) {
 // Get ID
 $code = filter_input(INPUT_POST, 'productCode', FILTER_VALIDATE_INT);
 // Delete the product from the database
 if ($code != false) {
    $query = 'DELETE FROM products
              WHERE productCode = :productCode';
    $statement = $db->prepare($query);
    $statement->bindValue(':productCode', $code);
    $success = $statement->execute();
    $statement->closeCursor();
 }
}

Answer: You are posting value with different key and getting it with different, and I believe this can be the reason, replace your hidden input with following
<input type="hidden" name="productCode" value="<?php echo $product['productCode']; ?>">

Also you need to take care about php tags <?php ?>, which should start and end for php script.
Answer: Please use AJAX post request for delete by code.


Trade-offs between Job Queue vs. Drupal Queue

Question: Anyone familiar with both Job Queue and Drupal Queue enough to offer an idea of the tradeoffs between the two?
In case it makes a difference, the site I'm working on uses Drupal 6. The queue I'll be creating will check a batch of user accounts with a REST API, to verify whether the users have logged into another system. Until the API gets updated (hopefully soon) each user requires a separate request, which is why I'm batching them.
Answer: Drupal Queue is a backport of Drupal 7's queue API for Drupal 6. It provides basically the same features as Job Queue. However a big advantage with Drupal Queue is that it uses the same API as Drupal 7 Core. This means if your module uses Drupal Queue in D6, your upgrade path to 7 will be effortless.
Answer: Another module to consider is PubSub.
Unfortunately I have only used PubSub before, not the others, so I can't compare them.  If I were coding this, my first attempt would be to "publish" the users and have a drush command that would run periodically that would "subscribe" and handle them in batches.


How to Cut Off String After Some Special Symbol is Encountered

Question: I have message = 'This is a private post. Cc: @me, @you.and @others,too. I @hope>this is okay'
I extracted words that startswith('@') symbol after iterating through message.split(' ').
This yielded mentions = ['@me', '@you.and', '@others,too', '@hope>this'] which is not what I want.
The desired result is mentions = ['@me', '@you', '@others', '@hope']
How can I achieve this?
Answer: >>> import re
>>> x = 'This is a private post. Cc: @me, @you.and @others,too. I @hope>this is okay'
>>> [re.search(r'(@\w+)', z).groups()[0] for z in x.split() if z.startswith('@')]
['@me', '@you', '@others', '@hope']

Comment: this will find words that have @ in the middle of the words also
Comment: This works but how do I replace it back to their position is `x` after tampering with them?
Comment: @linuxfan: The first answer is exactly what I have looking for.
Comment: @PadraicCunningham Thanks for spotting that. Updated the code snippet first split the entire string and then search for the string.
Answer: >>> import re
>>> s = "This is a private post. Cc: @me, @you.and @others,too. I @hope>this is okay"
>>> re.findall(r"(@\w+)\b", s)
['@me', '@you', '@others', '@hope']


AWS nodejs handler module with dots yields "Bad handler" error

Question: I'm trying to put my event handler function in a file called app.lambda.js because the app.js should contain only generic stuff not related to AWS Lambda.
But specifying "app.lambda.handler" as a handler yields Bad handler app.lambda.handler.
Is it simply impossible to use dots in the file name of the handler module?
Comment: Nope, in the end I just renamed files and changed dots for underscores.
Comment: I am facing the same issue. Have you come up with a solution? For now I am replacing all dots by dashes.
Answer: Yes, You should give app.handler. Only one dot will allow you in handler name.
Try by giving your filename.handler. It will work for you.


Mongodb $group + array items count

Question: I need to $group Mongodb data according field A and the result should contain the count of field B items which is array. For example if data looks like:
<code>{A: 1, B: [1, 2, 3]}
{A: 1, B: [4, 2]}
{A: 2, B: [1]}
{A: 2, B: [2, 3]}
{A: 2, B: [1, 2, 3]}
</code>
the result should look like:
<code>{A: 1, countB: 5}
{A: 2, countB: 6}
</code>
I have a solution with $unwind like:
<code>[
    {
        $unwind: "$B"
    },
    {
        $group: {
            "_id": "$A",
            "countB": {$sum: 1}
    },
    {
        $project: {
            "_id": 0,
            "A": "$_id.A",
            "countB": "$countB"
        }
    }
]
</code>
My question is if it is possible to do it without $unwind stage?
Thank you.
Answer: You can use the $size operator to get the length the individual arrays.
<code>{
  $group: {
    _id: "$A",
    countB: {
      $sum: {
        $size: "$B"
      }
    }
  }
}
</code>
Comment: This is it. Thank you.
Answer: have you try with aggregation?
<code>db.collection.aggregate([{$project: {
"A": "$A",
  count: {
    $size: "$B"
  }
}}])
</code>
Comment: This query produces an error: https://mongoplayground.net/p/PjPV0XK_WsN
Comment: Sorry, just change $group to $project
Comment: Where is $group?
Comment: @Čamo I already edited it, so you can just use that without any error

Mongodb $group + array items count


SSRS - Multiple Value Parameter - Expression regarded 'All' option

Question: I have a SSRS report and one of the parameters allows multiple selections and I have also added an 'All' option which will pass a '' to the database and select all departments for example.
So in the drop down we have something like:
(Select All)
All (Code '')
HR (Code 1)
IT (Code 2)
Management (Code 3)
So the (Select All) is the standard option with multi select and the (All) is a custom one to pass a null/''.  We have the additional (All) to allow all departments (some not in the list ) to be returned.  What I want to do is understand what is passed to the DB if I select (All) along side other options - so if I select (All) and HR?  At the moment if I select this - just the results for HR will show.
I want to be able to write a condition that says if they have selected (All) do this,  but I am not sure how the array is passed?  I want to imitate what is being passed by the report when (All) is selected?
Comment: You should be creating a deliminated list from a multipick parameter. If you are using commas it should look like "Null,HR". Add some logic to your parameter proc logic to remove the All option and just keep the default Select All from the multi pick. In your report split the string into a table and go from there.
Answer: When the built-in Select All option is chosen, SSRS sets the parameter to be all of the possible values as a comma separated list, which is passed to your dataset.  Your custom All has its own value, that is sent as a single value that you would handle differently then the rest.
Assuming that your All parameter is valued as 'All', in your dataset query, the where clause would need to be
WWHERE dept IN (@dept) OR 'All' IN (@dept)

If your All & HR are selected, the query would be the functional equivalent of
WHERE dept IN ('HR','All') OR 'All' IN ('HR','All')

There are some performance implications so make sure you test with multiple options.
Comment: Many thanks - This solution pointing me in the right direction and I've been able to resolve


How can I field-rewrite a URL?

Question: I need the modified URL to call a view with contextual filter, in Drupal 8.
The URL must include the value of a field, that the user's clicking on.
This works.
Link to Testview

How can I overwrite Link to Testview with the field value?
{{field_example__value}} works as well.
Comment: Sorry, if I express myself unclear I'm beginner... 4*4k helped me a bit further.
Answer: I've seen it often that the path is simply built by concatenating strings. But if you want to do it in a D8 way, then use the route from the view.
You can investigate the routes with Drupal Console on the command line or the Devel module in UI, where you'll find the routes in /devel/routes.
For example this view:
ROUTE NAME: view.testview.page_1    PATH: /testview/{arg_0}/{arg_1}

When you know the route name and the arguments for the contextual filters you can build the URL:
use Drupal\Core\Url;

  $url = Url::fromRoute('view.testview.page_1', [
    'arg_0' => $arg1,
    'arg_1' => $arg2,
  ]);

The URL is an object, which you put in a render array, for example in a link element. If needed you can get the path as string with the method ->toString(), but this should be avoided.
If you want to use the route in a field rewrite you can use the twig function url() in a field replacement pattern:
Link to Testview

Comment: No, I meant something different. The view returns a field, token says: [node: field_betreuer]. How do I get the content of this field appending to the URL? "%" or "$" does not seem to work. It must be easy to transfer the contents of this field to the URL, isn't it?
How to write this?
Comment: @FrankGiesecke, added an example for a field rewrite. Please provide more details what you want to achieve.
Comment: Thanks, that works. How can I overwrite "Link to Testview" with field value? - field_example__value itself doesn't work.
Comment: {{field_example__value}} works as well. Thx

How can I field-rewrite a URL?


How to load mongo repository to spring test application context?

Question: I have to implement some test for some spring application. I am using @SpringBootTest annotation in my test:
  @SpringBootTest
  @TestInstance(TestInstance.Lifecycle.PER_CLASS)
  class MyTest(){
  //some tests...
  }

It works fine, but i do not want to load all application context and and limit it by adding one or more nessecary configuration class. I done it with @ContextHierarchy:
 @SpringBootTest
 @TestInstance(TestInstance.Lifecycle.PER_CLASS)
 @ContextHierarchy(ContextConfiguration(classes = [SomeCofigClass1::class, SomeConfigClass2::class]))
  class MyTest(){
  //some tests...
  }

 //for example
 class SomeCofigClass1(){
      @Bean
      fun(someMongoRepository: SomeMongoRepository){ \\<-- Problem is here
           return SomeService(someMongoRepository)
      }
 }

 /**
  * My repository.
  */
 interface SomeMongoRepository : MongoRepository<Job, String> {}

Because of context is partially loaded i got a error:
  No qualifying bean of type 'SomeMongoRepository' available:....

How can i load repository in test application context?
I already tried:
1) Added @AutoConfigureDataMongo. I got error java.lang.IllegalStateException: Unable to retrieve @EnableAutoConfiguration base packages
 @SpringBootTest
 @TestInstance(TestInstance.Lifecycle.PER_CLASS)
 @ContextHierarchy(ContextConfiguration(classes = [SomeCofigClass1::class, SomeConfigClass2::class]))
 @AutoConfigureDataMongo

2) Replaced @SpringBootTest by @DataMongoTest. I got error Unable to retrieve @EnableAutoConfiguration base packages
 @DataMongoTest
 @TestInstance(TestInstance.Lifecycle.PER_CLASS)
 @ContextHierarchy(ContextConfiguration(classes = [SomeCofigClass1::class, SomeConfigClass2::class]))

3) With @DataMongoTest replaced @ContextHierarchy by @Import. With @Import annotation it loads all application context. This is not suit for me.
 @DataMongoTest
 @TestInstance(TestInstance.Lifecycle.PER_CLASS)
 @Import(SomeCofigClass1::class, SomeConfigClass2::class)

Answer: Add @RunWith(SpringRunner.class) to load Spring's ApplicationContext during the test.
Furthermore, classes can be selected by using the @SpringBootTest#classes attribute (or @ContextConfiguration):
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {SomeCofigClass1.class, SomeConfigClass2.class})

If your test makes use of inner Configuration classes, be sure to make them static (and add @Configuration). From the documentation:

If you omit the classes attribute from the @ContextConfiguration annotation, the TestContext framework tries to detect the presence of
  default configuration classes. Specifically,
  AnnotationConfigContextLoader and AnnotationConfigWebContextLoader
  detect all static nested classes of the test class that meet the
  requirements for configuration class implementations, as specified in
  the @Configuration javadoc.
Comment: I use junit 5. All i need to add @ExtendWith(SpringExtension::class). My context is loaded and i can get all beans from my configuration. But if i have autowired repository bean it is not loaded in context. I must add it manually by including DataJpaTest, DataMongoTest or AutoConfigureDataMongo annotation. But it does not work and i get error that i described in question.
Comment: In spring annotation @ExtendWith included automatically.
Comment: With `@SpringBootTest(classes = {SomeCofigClass1.class, SomeConfigClass2.class})` does not work. Because it is the same that `@ContextHierarchy` and framework does not try to detect presence configuration and loads only classes parameter. I got the same error **No qualifying bean of type 'SomeMongoRepository' available:....**


pyarrow compute expression in reticulate

Question: How do I use a filter in a reticulate pyarrow compute expression.
At base I have a pyarrow dataset (in this case called woodcan) that I want to turn into a table with a filter.
tab <- woodcan$to_table(ds$field('Region')=='Canada')

The above gets Error in py_compare_impl(a, b, op) :  ValueError: An Expression cannot be evaluated to python True or False. If you are using the 'and', 'or' or 'not' operators, use '&', '|' or '~' instead.
How is that syntax supposed to look?
Answer: You could generate the expression running python code with py_run_string or py_run_file and pass it to filter argument of to_table:
library(reticulate)

run.py <- py_run_string('
import pyarrow.dataset as ds
expr = ds.field("Region") == "Canada"
')

woodcan$to_table(filter=run.py$expr)

Above code needs previous installation of py_arrow in conjuction with reticulate:
virtualenv_create("arrow-env")
arrow::install_pyarrow("arrow-env")
use_virtualenv("arrow-env")

Answer: With @Waldi's answer I came up with another way that doesn't rely on python strings.
From that answer we generate run.py$expr which is a <pyarrow.compute.Expression (Region == "Canada")> object.
From there it begs the question, how else can we generate that?  Since it's a pyarrow.compute.Expression that tells us we need, of course, pyarrow.compute
so then it's just replacing "==" with equal
pc <- import('pyarrow.compute')
filter=pc$equal(pc$field("Region"), pc$scalar("Canada"))

and finally
woodcan$to_table(filter=filter)


How to make a Google Maps API (.js) file a part of a widget for Mobiles

Question: I would like to create a Web App for device. For that I would have some script being stored on device, instead of downloading them all time when I start application. As far as I saw including a GoogleMaps API makes some additional request for javascript files. Is there any way of having all of them taken directly from local store? Or is this always have to refeer to google web address? Thanks for any answers here!
Answer: No, you always must load them from the Google site. They offer no way to run Google Maps locally. The GMaps scripts are generated on the fly, based upon (among others, I'm sure) the HTTP_REFERER header of the request.  That's how they can bind an API key to a specific website.
Comment: That was probable answer for this question, but I want to be sure uhhh... It just sux a bit but ok..


Supervised learning approaches which can accommodate a supervisory signal composed of multiple dependent continuous variables?

Question: This is a supervised learning problem. Ideally would like to work in R due to having an easy way to pre-process the input data, but could work around that as well.
For each sample, input consists of tens of thousands of features. These are genomics data and will likely need to be reduced to a manageable amount, somehow, before being used to train the classifier.
Supervisory signal consists of 4 dependent continuous values, representing relative composition of the sample.
e.g. continuous between 0 and 1, all 4 summing to 1 for each sample:
<code>Sub012  0.5940594   0.26732673  0.07920792  0.059405941
Sub013  0.5102041   0.34693878  0.08163265  0.061224490
Sub014  0.6521739   0.20652174  0.07608696  0.065217391
</code>
Wanted: a regression function capable of predicting the relative composition of a sample in terms of those same 4 dependent continuous values.
The constraints on the supervisory signal are what is causing me pause: the dependence of the variables, being constrained between 0-1 and summing to 1. I was hoping someone might have attempted something similar and could point me in the right direction - packages or approaches which may work or definitely won't work - all thoughts welcomed.
Thank you.
Comment: Have you tried simple linear regression, one model for each of the target variables? With that many input dimensions it could work. The sum-to-one constraint could be dealt with by normalizing the outputs of the four models. Not sure if the result would make sense though. Anyway, I'd give it a shot!
Answer: The constraint on the output can be achieved using the softmax inverse-link function used in multi-nomial logistic regression, i.e.
$y_i = \frac{exp\{\nu_i\}}{\sum_{j=1}^n exp\{\nu_j\}}$
where $y_i$ is the $i^{th}$ output of the model and $\nu_j$ is the linear combination of the input features for the $j^{th}$ component.
The model can then be fitted by minimising a suitable likelihood.  As the targets are constrained, the likelihood won't be Gaussian, which may be a problem.  Some sort of Dirichlet likelihood might be more appropriate?  There may not be any R software that does this already, so you will probably have some coding to do.
As you have many input variables, it will be vital to use some form of regularisation to avoid over-fitting, the regularisation parameters can probably by tuned very efficiently my minimising the leave-one-out cross-validation error, see e.g. Generalised Kernel Machines.  WHich reminds me, if you have many more features than patterns, then you can perform the computation cheaply without having to do any feature reduction using kernel methods (see the GKM paper).
Update: You may be able to just use some off-the-shelf code for multi-nomial logistic regression, providing the implementation allows a soft (probabilistic) assignment of the targets (most software assumes that the targets specify that each pattern belongs to one particular class, rather than a probability of belonging to each class, as that is what most people need).  It will have the softmax inverse-link function, so the required constraints on the output will be in place.  The multinomial loss function is probably wrong, but then again so is a Gaussian.  I have used logistic regression models for regressing ratios before, it is a bit of a hack, but it did work pretty well.


Sequence of monotone functions converging to a continuous limit, is the convergence uniform?

Question: I'm reading some extreme value theory and in particular regular variation in Resnick's 1987 book Extreme Values, Regular Variation, and Point Processes, and several times he has claimed uniform convergence of a sequence of functions because "monotone functions are converging pointwise to a continuous limit". I am finding this reasoning a little dubious.
EDIT: Thanks to some comments below I realized I was confused, I really want each $f_n$ to be a monotone function on $[a,b]$, so it isn't quite like Dini's theorem. Formally I am wondering:
Let $f_n:[a,b]\rightarrow\mathbb{R}$ be a sequence of non-decreasing functions converging pointwise to the continuous function $f$. Is the convergence uniform?
My thoughts:
I have been thinking that since the set of discontinuities of each function $f_n$ is at most countable, the set of discontinuities of the entire sequence is at most countable...something something? Any thoughts would be greatly appreciated!
Comment: Ahh, sorry, the "sequence of non-decreasing functions" was a bit misleading, I thought you wanted a theorem for functions monotonic in $x$, not in $n$. (Which I think, I have seen somewhere, but cannot remember the name of)
Comment: @DavidMitra Isn't the limit then $f(0) = 1$, $f(x)=0$ otherwise and therefore not continuous?
Comment: @DavidMitra But then $f_n$ is not monotone, which was one of the requirements.
Comment: @mlk $f_n$ is monotone, fix $x$ and increase $n$.
Comment: I am aware that this is somewhat of an old post, but I would like to point out for future readers that this proposition is actually featured and proved in the very book mentioned by OP, in the first paragraphs of Chapter $0$, at the very least in the $2008$ edition.
Comment: @DavidMitra Can anything be done if we add the hypothesis that each  $f_n$ is a monotone function?
Comment: Ahh, found it [link](http://math.stackexchange.com/questions/265211/hellys-selection-theorem-for-sequence-of-monotonic-functions) seems to be a basic version of helly's selection theorem.
Comment: Thanks for your comments, very valuable, I realized I was confused and I've edited the question suitably!
Comment: It seems the link mlk provided shows the answer is "yes". The proof is contained in the link (part b) of that post.
Answer: Let $f:=\lim f_n$, and let $\varepsilon >0$ be given. We have to show that if $n$ is large enough, then $$\vert f_n(t)-f(t)\vert\leq\varepsilon\quad \hbox{for all $t\in[a,b]$}\, .$$
Since $f$ is assumed to be continuous, it is uniformly continuous on the compact interval $[a,b]$. So we may find a subdivision $a=t_0<t_1\dots <t_K=b$ of $[a,b]$ such that the oscillation of $f$ on each interval $[t_i,t_{i+1}]$ is less than $\varepsilon/2$.
Since $f_n(t_i)\to f(t_i)$ as $n\to\infty$ for $i=0,\dots ,K$, one can find $N$ such that if $n\geq N$, then $$\vert f_n(t_i)-f(t_i)\vert\leq\varepsilon/2\quad\hbox{for $i=0,\dots K$}\, .$$
Let us check that $\vert f_n(t)-f(t)\vert\leq \varepsilon$ for every $n\geq N$ and all $t\in [a,b]$.
Fix $n\geq N$, and take any $t\in [a,b]$. One can choose $i$ such that $t\in [t_i,t_{i+1}]$. Since the functions $f_n$ are non-decreasing we have $$f_n(t_i)\leq f_n(t)\leq f_n(t_{i+1})\, . $$
Since $\vert f_n(t_i)-f(t_i)\vert$ and $\vert f_n(t_{i+1})-f(t_{i+1})\vert$ are not greater than $\varepsilon/2$, it follows that $$f(t_i)-\varepsilon/2\leq f_n(t)\leq f(t_{i+1})+\varepsilon/2\, . $$
Moreover, since the oscillation of $f$ on $[t_i,t_{i+1}]$ is less than $\varepsilon/2$ and since $t\in [t_i,t_{i+1}]$, we also have $f(t_i)\geq f(t)-\varepsilon/2$ and $f(t_{i+1})\leq f(t)+\varepsilon/2$. Altogether, this gives $$f(t)-2\varepsilon/2\leq f_n(t)\leq f(t)+2\varepsilon/2\, , $$
which concludes the proof.
Comment: @CharlieTian Thanks, for the same reason.
Comment: f(ti)−ε/2≤fn(t)≤fn(ti+1)+ε/2.

this line is wrong, as the right side of the inequality should be symmetric and just be the limit function. That gives the desired end form
Comment: @NikPronko: thanks for pointing out the typo. It should be OK now.
Comment: I have tried to include definitions of pointwise, montone, continuity and uniform continuity but to no avail. Can you explain how did you come up with the partition technique? Is this the first question you pull this off or are there precedents for this established pattern?
Answer: Definition. Let $X$ be a set and let $Y$ be a metric space. A sequence of mappings $u_n:X \to Y$ converges uniformly to $u:X \to Y$ if
$$\lim_{n \to \infty} \sup_{x \in X} d(u_n(x),u(x)) = 0.$$
Proof. Assume $(u_n)$ does not converge uniformly to $u$. There exists $\varepsilon > 0$ and a sequence $(x_n) \subset [a,b]$ such that for all $n$,
$$\varepsilon \le |u_n(x_n) - u(x_n)|.$$
Since $[a,b]$ is compact, $(x_n)$ contains a convergent subsequence. Assume, without loss of generality, that $(x_n)$ converges to $x_0 \in [a,b]$. By the Heine-Cantor theorem, $u:[a,b] \to \mathbb{R}$ is uniformly continuous. Thus, there exists $\delta > 0$ such that
\begin{equation}
    x,y \in (x_0-\delta,x_0+\delta) \implies |u(x) - u(y)| < \frac{\varepsilon}{2}.\tag{1}\label{1}
\end{equation}
Since $(x_n)$ converges to $x_0 \in (x_0 - \delta, x_0 + \delta)$, there exists $N$ such that if $n \ge N$, then $x_n \in (x_0-\delta,x_0+\delta)$. Since $(u_n)$ converges to $u$ pointwise, there exists $K \ge N$ such that if $k \ge K$, then
\begin{equation}
    |u_k(x_0+\delta) - u(x_0+\delta)| < \frac{\varepsilon}{2} \tag{2}\label{2}
\end{equation}
and
\begin{equation}
    |u_k(x_0-\delta) - u(x_0-\delta)| < \frac{\varepsilon}{2}. \tag{3}\label{3}
\end{equation}
Fix $k \ge K$. We can deduce from $\eqref{2}$ and $\eqref{3}$ that
$$u_k(x_0+\delta) < u(x_0 + \delta) + \frac{\varepsilon}{2}$$
and
$$u(x_0-\delta) - \frac{\varepsilon}{2} < u_k(x_0-\delta).$$
Since $u_k$ is nondecreasing and $x_0 - \delta < x_k < x_0 + \delta$,
$$u(x_0-\delta) - \frac{\varepsilon}{2} < u_k(x_0-\delta) \le u_k(x_k) \le u_k(x_0+\delta) < u(x_0 + \delta) + \frac{\varepsilon}{2}.$$
Subtract by $u(x_k)$ to get
\begin{equation}
    u(x_0-\delta) - u(x_k) - \frac{\varepsilon}{2} < u_k(x_k) - u(x_k) < u(x_0 + \delta) - u(x_k) + \frac{\varepsilon}{2}.\tag{4}\label{4}
\end{equation}
By $\eqref{1}$, we know that
$$-\frac{\varepsilon}{2} \le u(x_0-\delta) - u(x_k)$$
and
$$u(x_0 + \delta) - u(x_k) \le \frac{\varepsilon}{2}.$$
Combining these deductions with $\eqref{4}$, we obtain
$$-\varepsilon=-\frac{\varepsilon}{2} -\frac{\varepsilon}{2} < u_k(x_k) - u(x_k) < \frac{\varepsilon}{2} + \frac{\varepsilon}{2} = \varepsilon$$
whence
$$|u_k(x_k) - u(x_k)| < \varepsilon.$$
By assumption, $\varepsilon \le |u_k(x_k) - u(x_k)|$, so we get the contradiction $\varepsilon < \varepsilon$.


Unit test of a mapping when members are hidden

Question: I have to test a projection that handle a given events and persist it on a read only Mongo database (I'm using official c# Mongo Driver):
public class MyObjectProjection : IHandleMessages<RegisteredEvent>
{
    private MongoCollection<MyObjectView> _collection;
    private MyObjectView item;

    public MyObjectProjection (MongoDatabase db)
    {
        _collection = db.GetCollection<MyObjectView>("my-object");
    }

    public void Handle(RegisteredEvent message)
    {
        item = new MyObjectView();
        item.Id = message.Id;

        // some code omitted

        _collection.Save(item);
    }
}

I need to unit test the Handle method, given that:

I don't want an integration test. Database and collection are mocked, so the save is not real
I just want to test the item-message mapping
the members are hidden and I don't want to make them more visibile

Should I use alternative solution rather than reflection or friendly assembly? What is the best practice in a case like this?
Right now my test look like this:
    [TestMethod]
    public void TestMethod1()
    {
        // ARRANGE - some code omitted
        databaseMock
            .Setup(x => x.GetCollection<MyObjectView>(It.IsAny<string>()))
            .Returns(collection);

        collectionMock
            .Setup(x => x.Save(It.IsAny<MyObjectView>()))
            .Returns(It.IsAny<WriteConcernResult>);

        // ACT
        var handler = new MyObjectProjection(database);
        handler.Handle(evt);

        // ASSERT
        // nothin' to assert here!
    }

this works, but i have nothing to assert when Handle method is completed.
Answer: Well, your Handle() method interacts with the collection, by calling the Save() method. Therefore you can expect that the element passed to the Handle method has proper ID set:
collectionMock.Verify(x=>x.Save(It.Is<MyObjectView>(v => v.Id == 5)), Times.Once,"save should be called with object with Id = 5");

I assumed here that the evt that is passed into Handle() has and Id of 5. Code not tested, but I think something like that would do the trick.
Comment: The ID is the only field that I map manually, all others are AutoMapper stuff, i don't feel comfortable knowing that the only thing tested is the one I trust more than others :)
Answer:
What is the best practice in a case like this?

The best practice is to make members visible. Is there any particular reason why you need to hide members?
Then, you can assert against argument passed to Save method :
    MyObjectView objectView;

    collectionMock
        .Setup(x => x.Save(It.IsAny<MyObjectView>()))
        .Callback<MyObjectView>((obj) => objectView= obj)
        .Returns(It.IsAny<WriteConcernResult>);

    Assert.That(objectView.Id, Is.EqualTo(evt.Id));
    //assert other properties

Comment: I prefear to be as restrictier as I can, and I really don't like the idea to increase visibility just for testability sake. What I wanted was exactly this, testing through mock.


Inequality with complex numbers with the same modulus

Question: I got stuck at the following problem. Prove that for every three distinct complex numbers $a$, $b$, $c$ with $|a| = |b| = |c| > 0$, the following inequality holds:
$
\sum_{\text{cyclic}} |(a+b)(b-c)(c-a)|^2\ \geq \left|\sum_{\text{cyclic}} (a-b)(b+c)(c+a)\right|^2
$
If we divide the inequality by $|(a+b)(b+c)(c+a)|^2$, the inequality reduces to:
$
\sum_{\text{cyclic}} \left|\frac{b-c}{b+c}\right|^2 \cdot \left|\frac{c-a}{c+a}\right|^2 \geq \left|\sum_{\text{cyclic}} \left(\frac{a-b}{a+b}\right)\right|^2
$
Then we write $a=r(\cos(t_1)+i\sin(t_1))$, $b=r(\cos(t_2)+i\sin(t_2))$, and $c=r(\cos(t_3)+i\sin(t_3))$. Thus,
$
\frac{a-b}{a+b} = i\tan\left(\frac{t_1-t_2}{2}\right)
$
So the inequality we have to prove becomes:
$
\sum_{\text{cyclic}} \left(\tan\left(\frac{t_1-t_2}{2}\right)\right)^2 \cdot \left(\tan\left(\frac{t_1-t_3}{2}\right)\right)^2 \geq \left(\sum_{\text{cyclic}} \tan\left(\frac{t_2-t_3}{2}\right)\right)^2
$
Then I tried denoting $x = \frac{t_1 - t_2}{2}$, $y = \frac{t_2 - t_3}{2}$, $z = \frac{t_3 - t_1}{2}$, where x+y+z=0. Thus, we have to prove that:
$
\sum_{\text{cyclic}} (\tan(x))^2 \cdot (\tan(y))^2 \geq (\sum_{\text{cyclic}} \tan(z))^2
$ and I got stuck here. How can I continue the problem?
Answer: This solution is almost surely not the best, but it works.
$\color{#FF6200}{\bf{Lemma.}}$ If $\lambda\in\mathbb{R}$, then $\forall X\geq4\lambda:Q_\lambda(X):=X^2-\lambda(2+\lambda)X+\lambda^2(1-\lambda)^2\geq0$.
Proof. Note that the discriminant is $\Delta=\lambda^2(2+\lambda)^2-4\lambda^2(1-\lambda)^2=3\lambda^3(4-\lambda)$. So, if $\lambda\not\in[0,4]$, then $\Delta<0$ which means that it has no real solutions and, since the polynomial is $\geq0$ at $X=0$, it follows that it is $\geq0$ everywhere (in particular for $X\geq4\lambda$). So let's study the case $\lambda\in[0,4]$. Note that
$$Q_\lambda(4\lambda)=16\lambda^2+\lambda(2+\lambda)4\lambda+\lambda^2(1-\lambda)^2=\lambda^4-6\lambda^3+9\lambda^2=\lambda^2(\lambda-3)^2\geq0$$
Moreover, $4\lambda\geq\lambda\cdot3\geq\frac{1}{2}\lambda(2+\lambda)$ where $X=\frac{1}{2}\lambda(2+\lambda)$ is the vertex of the convex parabola. But this means that $\forall X\geq 4\lambda$ the function $Q_\lambda(X)$ is increasing and, thus, $Q_\lambda(X)\geq Q_\lambda(4\lambda)\geq0$. $\ \square$
$\color{#FF3200}{\bf{Proposition.}}$ If $x+y+z=0$ are real numbers not in $\frac{\pi}{2}+\pi\mathbb{Z}$, then
$$\sum_\text{cyc}\tan^2(x)\tan^2(y)\geq\left(\sum_\text{cyc}\tan(z)\right)^2$$
Proof.
From now on let's denote $P:=\tan(x)\tan(y)$ and $S:=\tan(x)+\tan(y)$. Note that $$z=-(x+y)\Rightarrow\tan(z)=-\frac{\tan(x)+\tan(y)}{1-\tan(x)\tan(y)}=-\frac{S}{1-P}$$
Now observe that, by the previous lemma, since $S^2\geq 4P$ by the AM-GM inequality
$$S^4-P(2+P)S^2+P^2(1-P)^2\geq0$$
$$\Rightarrow S^4-2PS^2+P^2(1-P)^2\geq P^2S^2$$
$$\Rightarrow S^2(S^2-2P)+P^2(1-P)^2\geq P^2S^2$$
Now, if $P=1$ we would then have
$$\tan(x)=\frac{1}{\tan(y)}=\tan\left(\frac{\pi}{2}-y\right)\Rightarrow z=-(x+y)\in\frac{\pi}{2}+\pi\mathbb{Z}$$
which contradicts the hypothesis. Hence, we can divide by $(1-P)^2$ on the previous inequality
$$\frac{S^2}{(1-P)^2}(S^2-2P)+P^2\geq \frac{P^2S^2}{(1-P)^2}$$
$$\Rightarrow P^2+(S^2-2P)\left(\frac{-S}{1-P}\right)^2\geq\left(S-\frac{S}{1-P}\right)^2$$
$$\Rightarrow \tan^2(x)\tan^2(y)+(\tan^2(x)+\tan^2(y))\tan^2(z)\geq\left(\tan(x)+\tan(y)+\tan(z)\right)^2$$
$$\therefore\sum_\text{cyc}\tan^2(x)\tan^2(y)\geq\left(\sum_\text{cyc}\tan(z)\right)^2$$

As an observation, note that we have to assume that neither of $x,y,z$ are in $\frac{\pi}{2}+\pi\mathbb{Z}$ because, otherwise, the tangent isn't defined. These degenerate cases come from the step of dividing by $|\prod\limits_\text{cyc}(a+b)|^2$ where you have to assume that it is $\neq0$. But this is not too big of a deal since the case $a+b=0$ is quite easy to handle (and the other degenerate cases follow directly from this one by symmetry).
Answer: You have made a very good start.
Claim: $a^2+b^2+c^2 \geq ab + bc + ca$ for $a,b,c \in \mathbb R$.
Consider $(a-b)^2\geq 0$, $(b-c)^2\geq 0$, and $(c-a)^2\geq 0$. Add all of these and consider the identity $(a-b)^2=a^2+b^2-2ab$.
Claim: $x+y+z=0 \implies \tan(x)+\tan(y)+\tan(z)=\tan(x)\tan(y)\tan(z)$ if $x,y,z$ are not of form $n\pi +\frac{\pi}{2}$ for $n \in \mathbb Z$.
To prove this consider $\tan(x+y)=-\tan z$, and expanding the compound angle $\tan$. The restriction on the angles comes from that $\tan\left(\frac{\pi}{2}\right)$ is not defined.
Case $1$: Assuming none of $\tan x,\tan y,\tan z$ are undefined, we just have to prove $$\sum_{cyc} (\tan x \tan y)^2 \geq (\sum_{cyc} \tan z)^2 = (\tan x\tan y\tan z)(\tan x + \tan y+\tan z) = \sum_{cyc} (\tan^2 x \tan y\tan z)$$ which is true by the first claim. Further, equality is attained iff $\tan x = \tan y =\tan z$.
Case $2$: Any of the $\tan$ is undefined. WLOG let $x = n\pi +\frac{\pi}{2}$. This means $t_1=2\pi n + \pi + t_2$ which further means $a=-b$. That means we have to prove $$|b+c|^4 + |b-c|^4 \geq |b+c|^2|b-c|^2$$
which is true since $|a|^2+|b|^2\geq |ab|$ by considering $(|a|^2+|b|)^2\geq 0$ and also that $|x| \geq 0 \ \forall x$. This further means our equality case occurs when $a=b=c=0$.


Show that it is impossible to find $a,b \in \mathbb{Q}$ such that $ \frac{\sqrt{5}}{10}=a+b \frac{\sqrt{3}}{7} $

Question: Show that it is impossible to find $a,b \in \mathbb{Q}$ such that
$$
\frac{\sqrt{5}}{10}=a+b \frac{\sqrt{3}}{7}
$$
We have $\frac{1}{20}=a^{2}+\frac{2 \sqrt{3}}{7} a b+b^{2} \frac{3}{49}=\left(a^{2}+b^{2} \frac{3}{49}\right)+\frac{2 \sqrt{3}}{7} a b$ with $a \neq 0, b \neq 0$.
Suppose $a=0$, then
$$
\frac{1}{20}=b^{2} \frac{3}{49} \Leftrightarrow 3 b^{2}= \frac{49}{20}
$$
(here I don't know how to conclude)
If $b=0$, then
$$
\sqrt{5}=10 a
$$
which is impossible because $\sqrt{5} \neq \mathbb{Q}$.
Comment: "here I don't know how to conclude": I know. $b^2=\frac{49}{60}$ has no rational solution.
Comment: $3b^{2} = \frac{49}{20} \implies 60b^{2} = 49 \implies 7$ divides $60b^{2}$, but $60$ and $7$ are coprimes, then $7$ divides $b$, as $49 = 7^{2}$ then $49$ divides $b^{2}$, then $60\dot q = 1$, with $q \in \mathbb{Z}$. Is a contradiction.
Comment: @Paul Yes but I still have to show that $a$ and $b$ are not zero, otherwise the argument that $\sqrt{3}$ is not rational does not hold.
Comment: True, sorry too quick to reply!
Comment: From your first row calculation you can conclude that $\sqrt{3}$ must be rational. Go from there rather than worrying about values of $a$ or $b$
Comment: @DietrichBurde Ok but how to show it?
Comment: You can say $\sqrt{15}=\frac{7}{2b}$ and if you are happy that $\sqrt{5} \neq \mathbb{Q}$ can you be happy that $\sqrt{15} \neq \mathbb{Q}$?
Comment: Re my answer, leave question after the answer, if you are unsure about proving that $k\sqrt{5}$ can not be an integer.  As long as your comment is posted after my answer, I will be notified.
Comment: This is same as proving that there are no rationals $a, b$ with $\sqrt{5}=a+b\sqrt{3}$. You should get an easy contradiction by squaring.
Answer:
Show that it is impossible to find $a,b \in \mathbb{Q}$ such that
$$
\frac{\sqrt{5}}{10}=a+b \frac{\sqrt{3}}{7}
$$

Alternative approach.
Lemma 1
$\sqrt{15}$ is not a rational number.
$\underline{\text{Proof}}$
Suppose that $~\displaystyle \sqrt{15} = \frac{p}{q} ~:$
$~p,q~$ relatively prime integers, and $~q > 0.$
Then $q\sqrt{15} = p \implies 15q^2 = p^2.$
However, since $p,q$ relatively prime, this implies that $15$ divides $p^2$.  However, by the fundamental theorem of arithmetic, this implies that the prime factorization of $p$ contains both $3$ and $5$.
This implies that $15$ divides $p$.
This implies that $(15)^2$ divides $p^2.$
This implies that $(15)$ divides $q^2,~$ since $15q^2 = p^2.$
This is a contradiction, because $p,q$ are relatively prime.
Lemma 2
If $~k \in \Bbb{Z_{\neq 0}},~$ then $k\sqrt{15}$ is not an integer.
$\underline{\text{Proof}}$
Suppose $k\sqrt{15} = n \in \Bbb{Z}.$
Then $~\displaystyle ~\sqrt{15} = \frac{n}{k}.$
This contradicts Lemma 1.
Lemma 3
If $R,S \in \Bbb{Z_{\neq 0}}$,
then $R\sqrt{3} + S\sqrt{5}$ is not an integer.
$\underline{\text{Proof}}$
Suppose $~R\sqrt{3} + S\sqrt{5} = n \in \Bbb{Z}.$
Then $3R^2 + 5S^2 + 2RS\sqrt{15} = n^2,$ which is also an integer.
This implies that $2RS\sqrt{15}$ is an integer.
This contradicts Lemma 2.

Suppose that $~\displaystyle a,b =  \frac{p_a}{q_a}, \frac{p_b}{q_b}~$ respectively,
where $p_a,q_a$ are relatively prime integers,
where $p_b,q_b$ are relatively prime integers,
and $q_a, q_b$ are both positive.
Then
$$\frac{p_a}{q_a} + \left(\frac{p_b}{q_b}\times \frac{\sqrt{3}}{7}\right) - \frac{\sqrt{5}}{10} = 0.\tag1 $$
In (1) above, you can ensure that each term has the common denominator of $(q_a \times q_b \times 7 \times 10).$
This implies that
$$\frac{70p_aq_b + 10q_ap_b\sqrt{3} - 7q_aq_b\sqrt{5}}{q_a \times q_b \times 7 \times 10} = 0. $$
This implies that
$$70p_aq_b + 10q_ap_b\sqrt{3} - 7q_aq_b\sqrt{5} = 0. $$
This implies that
$$\left(10q_ap_b\sqrt{3} - 7q_aq_b\sqrt{5}\right) ~~\text{is an integer}.  $$
This is a contradiction, by Lemma 3.
Edit
I overlooked that you could have $p_b = 0$.
However, this would result in $7q_aq_b\sqrt{5}$ being an integer.
The exact same analysis used in Lemmas 1 through 3 may be repeated on $\sqrt{5}$ to show that that would be impossible.
Comment: Nice answer +1!


How to extract latest reply text from email, and cut out previous messages?

Question: I am using OpenPop.dll to read emails in my application. I want to read only the reply of the email not original email which it was replied to. But email is read with previous emails in quotes. I want to remove those previous mail contents.
I tried using RegEx for this but that is not very robust way to read replies because different email clients have different reply format.
Is there any way by which I can read only the reply text from mail thread in OpenPop.dll or some other open source library.
Below is how the reply email text looks like when read from OpenPop.dll.

My phone number is 123456789.

On Fri, May 8, 2015 at 2:57 PM,  wrote:

>  Hi,
>
> This mail is regarding your *Phone*. Please reply to this email with your
> *Phone*.
>
> Thanks
>

This format is such that because it was replied from Gmail. Outlook has different format and so does yahoo.
I want to read only

My phone number is 123456789.

Is there any way I could achieve this? Any solution is welcome.
Comment: I fixed this by switching to different emailing API [mailgun](http://www.mailgun.com/) . This API allows you to get only the replied content from the incoming mail.
Answer: I faced with such a problem.I did data mining.I used naive Bayes algorithm.You need email data collection.Problem will be solved.
This is my project.
https://www.youtube.com/watch?v=jJShFuEEsQg
Comment: Could you please elaborate more your answer adding a little more description about the solution you provide?
Comment: Firstly,I collected  email reply data from gmail,hotmail,yahoo  etc. I used these email reply datas for  make text classification with Naive Bayes algorithm.I convert html email to text. I divide the text line by line.I did classification each line with Naive Bayes algorithm.I cleaned the unnecessary part inside the text.


How to customize the SQL Server connection ApplicationName property in Nhibernate for profiling

Question: I am trying to correlate SQL query activity in a SQL Server Studio profile trace with different client processes in a large application that I am new to. The connection ApplicationName column in the trace window is set to ".Net SQLClient Data Provider" for all profiled query activity.
I would like to override the ApplicationName property on each new NHibernate command or connection with more meaningful internal application names associated with the main processes of the large application.
I have set a custom ApplicationName before but is it possible with NHibernate?
Answer: the first method I found was to use the connection-string (see links), but that is per connection and not per command and you won't know when .Net/NHibernate/Connection-Pooling/... decides to make a new connection.
Change Application Name in Sql Server Profiler
https://www.connectionstrings.com/use-application-name-sql-server/#:~:text=Simply%20include%20%22Application%20Name%3DMyAppName,%2C%20%22SELECT%20APP_NAME()%3B%22.
I am trying to find an T-SQL-Command to change/set this value from within a connection, but wasn't lucky till now.
Greetings
Juy Juka


R remove elements based on several options

Question: I have data in a list, e.g.
MWE <- list("Argentina -2.0 1.4", "G20 6.9 0.7", "United Kingdom 1.3 2.3", "EU28 6.6 2.8")

Desired output :
[1] "Argentina"    "G20"           "United Kingdom" "EU28"

That is most of my identifier are only literal, but some have digits (G7, G20, EA15, ...) but a finite list.
I have tried to use OR conditions on  gsubbut have failed so far. For instance,
> MWE_1 <- gsub("[^([:alpha:]|G20|EU28)]", "",MWE)
> MWE_1
[1] "Argentina20"    "G200"           "UnitedKingdom2" "EU2828"

It seems I have not found a way to use the or condition properly
Ideally, it would separate spaces based on whether it is between characters (e.g. United Kingdom) or not (e.g. -2,0 1,4) but I am fine with UnitedKingdom as a result
Comment: If you want to remove the numbers, try `MWE_1 <- gsub(" [+-]?\\d+(?:\\.\\d+)(?: \\d+(?:\\.\\d+)*)*$", "",MWE)` See https://ideone.com/Y62kJQ
Comment: `[^([:alpha:]|G20|EU28)]` is a negated character class that matches any 1 char but a `(`, letter, `|`, `G`, `2`, `0`, `|`, `E`, `U`, `8` and `)`
Comment: Your regex should be this `^([:alpha:]|G20|EU28)`  not `[^([:alpha:]|G20|EU28)]`
Comment: You did not use any OR conditions in your regex, it is a single negated character class matching any chars but the ones in the class.
Comment: @WiktorStribiżew Could you elaborate a bit on your comment ?
Answer: You could use the first capturing group and match the rest of the line.
In the replacement use the first capturing group.
^([A-Za-z]+(?: [A-Za-z]+)*|G20|EU28)\b.*$

^ Start of string
( Capture group 1

[A-Za-z]+ Match 1+ A-Za-z
(?: [A-Za-z]+)* Repeat 0+ times matching a space and 1+ times a-zA-Z
| Or
G20 Match literally
| Or
EU28 Match literally

)\b Close group followed by a word boundary
.* Match any char except a newline 0+ times
$ End of string

Regex demo | R demo
For example
MWE <- list("Argentina -2.0 1.4", "G20 6.9 0.7", "United Kingdom 1.3 2.3", "EU28 6.6 2.8")
MWE_1 <- gsub("^([A-Za-z]+(?: [A-Za-z]+)*|G20|EU28)\\b.*$", "\\1",MWE)
MWE_1

Output
[1] "Argentina"      "G20"            "United Kingdom" "EU28"

Using :[[:alpha:]] the line of code would look like
MWE_1 <- gsub("^([[:alpha:]]+(?: [[:alpha:]]+)*|G20|EU28)\\b.*$", "\\1",MWE)

Answer: This pattern removes whitespace followed by a positive or negative numbers that might have a decimal:
gsub("\\s+\\-?\\d+\\.?\\d*", "", MWE)
[1] "Argentina"      "G20"            "United Kingdom" "EU28"

This returns the everything in the string up to whitespace followed by a number (positive or negative):
gsub("(.*?)\\s+\\-*\\d+.*", "\\1", MWE)
[1] "Argentina"      "G20"            "United Kingdom" "EU28"

Answer: My variant:
MWE <- list("Argentina -2.0 1.4", "G20 6.9 0.7", "United Kingdom 1.3 2.3", "EU28 6.6 2.8")

gsub("\\s+", "", gsub("[0-9\\-]+\\.+[0-9]+", "", MWE))
# [1] "Argentina"     "G20"           "UnitedKingdom" "EU28"

Here, the inner gsub() looks for patterns that:

contain one or more - or digits
followed by one or more .
followed by one or more digits

And removes the matched patterns (i.e., replaces them with "").
The outer gsub() then strips all whitespaces from this result.
Advantages: you're calling gsub().
Disadvantages: you're calling gsub() twice.
Answer: You can try with gsub("\\s\\-?\\d+.*","",MWE), such that
> gsub("\\s\\-?\\d+.*","",MWE)
[1] "Argentina"      "G20"            "United Kingdom" "EU28"


Como popular gráfico de linha do google charts com JSON

Question: Estou tentando popular um grafico do google-charts de linha, será bem simples apenas o nome do cliente no eixo x e a quantidade de chamados abertos no eixo y, estou retornando o seguinte array de JSON

[{"Name":"Cliente Teste","Tickets":6}]

para populá-lo estou usando o seguinte:
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);

function drawChart() {
    var jsonData = $.ajax({
        url: "/client/ajax",
        dataType: "json",
        async: false
    }).responseText;

    var data = new google.visualization.DataTable(jsonData);
    var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
    chart.draw(data, {width: 400, height: 240});
}

Porém me retorna dizendo que não tem nenhuma coluna =/, estou usando pela primeira vez o google charts, sou noob :(.
Alguém pode me dar uma luz? Obrigado desde já.
Answer: Da uma olhada nesse exemplo que eu peguei direto da página do line chart. O ideal era você trabalhar com um array para postar as colunas pro chart. Fica mais fácil e você consegue muitos exemplos.

google.charts.load('current', {packages: ['corechart', 'line']});
google.charts.setOnLoadCallback(drawBackgroundColor);

function drawBackgroundColor() {
      var data = new google.visualization.DataTable();
      data.addColumn('string', 'X');
      data.addColumn('number', 'Dogs');

      data.addRows([
        ["a", 0],   ["b", 10],  ["c", 23],
      ]);

      var options = {
        hAxis: {
          title: 'Time'
        },
        vAxis: {
          title: 'Popularity'
        },
        backgroundColor: '#f1f8e9'
      };

      var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
      chart.draw(data, options);
    }

Answer: Algo assim:

Fonte: http://www.devmedia.com.br/introducao-a-google-chart-tools/26453
Answer: Fiz da seguinte forma gente
google.charts.load('current', {packages: ['corechart']});
google.charts.setOnLoadCallback(drawChartTicketsByClient);

function drawChartTicketsByClient() {
    $.ajax({
        url: "/client/ajax",
        dataType: "JSON",
        success: function (jsonData) {
            var dataArray = [
                ['Name', 'Tickets'],
            ];

            for (var i = 0; i < jsonData.length; i++) {
                var row = [jsonData[i].Name, jsonData[i].Tickets];
                dataArray.push(row);
            }
            var options = {
                title: 'Tickets por cliente',
                curveType: 'function',
                series: {0: {"color": '#57c8f2'}}
            };

            var data = google.visualization.arrayToDataTable(dataArray);

            var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
            chart.draw(data, options);
        }
    });
}


NumPy - Excluding all zero 2D arrays from a 3D array

Question: I have multiple 3D arrays with different shapes but I'm going to assume I have an array named A with shape (53, 768, 768) for an example. It consists of 53 2D arrays and some of them may be empty images. Those empty images have only 0 pixel values.
If there are N slices with all 0 values, I want to slice A into a (53 - N, 768, 768) 3D array. Is this possible with indexing?
I tried something like this a[:, ~np.all(a == 0)], but it returns an array with shape (53, 1, 768, 768).
Answer: Use:
import numpy as np
A = np.array(A)                                 # if A is not a NumPy array
result = A[np.sum(A, axis = (-1, -2)) != 0]

This will do.
Comment: Thank you, this works perfectly but the other answer is more thorough so I accepted it.
Answer: Let's assume your data is something like this:
z = np.array([
    [[1, 2, 3], [4, 5, 6]],
    [[7, 8, 9], [10, 11, 12]],
    [[0, 0, 0], [0, 0, 0]],
    [[1, 1, 1], [1, 1, 1]]
])

The shape of z is (4, 2, 3). We therefore need a vector with shape 4, aggregating over the other dimensions. We can use the axis= parameter in most Numpy functions for this:
mask = np.all(z != 0, axis=(1, 2))
a[mask]

In this example, mask will be array([False, False,  True, False]).
Axes are numbered 0, 1, 2, etc. So we use 1 and 2 to refer to the 2nd and 3rd axes.
You can also use negative numbers as in the other answer; if you write axis=(-2, -1) that refers to the last and 2nd-to-last axes, i.e. axes 1 and 2 in this example.
In general, use axis= to specify which axes are to be collapsed by aggregating. Any axis not specified in axis= will not be aggregated.


Evaluating $\int_0^{\pi} \frac{x}{1+\sin^2{x}}dx$

Question:
Evaluate:
$$\int_0^{\pi} \frac{x}{1+\sin^2{x}}dx$$

My attempt:
Let $I = \int_0^{\pi} \frac{x}{1+\sin^2{x}}dx$
Using Identity:
$$\int_0^af(x)dx=\int_0^af(a-x)dx$$
I got:
$$I=\int_0^{\pi} \frac{\pi -x}{1+\sin^2{(\pi -x})}dx$$
$$I=\frac{\pi}{2}\int_0^{\pi} \frac{dx}{1+\sin^2{x}}$$
Dividing numerator and denominator by $\cos^2x$
$$I=\frac{\pi}{2}\int_0^{\pi} \frac{\sec^2x}{\sec^2x+\tan^2x}dx$$
$$I=\frac{\pi}{2}\int_0^{\pi} \frac{\sec^2x}{1+2\tan^2x}dx$$
Using Substitution method, let:
$$t =\sqrt2\tan x$$
$$\frac{dt}{\sqrt2} =\sec^2xdx$$
The limits also change upon substitution, so the integral I get is:
$$I=\frac{\pi}{2\sqrt2}\int_0^{0} \frac{1}{1+t^2}dt$$
But the answer isn't $I(0)-I(0)=0$.
So where did my solution go wrong?
I do know that I could have changed the upper limit of the integral to be $\frac{\pi}{2}$, and somehow it all works out. But why doesn't the integral work in the way I did?
Comment: Regarding the substitution: as $x$ runs from $0$ to $\pi$, your $t$ goes from $0$ to $+\infty$, then jumps to $-\infty$, and goes back to $0$. Thus you get $\int_{-\infty}^\infty$, not $\int_0^0$. In general, you can't blindly apply a substitution to integration bounds (unless the substitution is monotonic).
Comment: $\int_{0}^{a}f(x)\mathrm{d}x=\int_{0}^{a}f(a-x)\mathrm{d}x$
Comment: @metamorphy, Thank You, it finally makes sense now.
Comment: Another way to prepare your integral for that substitution is to translate to the symmetric interval $\left[-\frac\pi2,\frac\pi2\right]$ by substituting $x\to x+\frac\pi2$, so$$I=\pi \int_0^\tfrac\pi2 \frac{dx}{1+\cos^2x}$$
Comment: Use https://math.stackexchange.com/questions/439851/evaluate-the-integral-int-frac-pi2-0-frac-sin3x-sin3x-cos3x/439856#439856
Answer: It is easy to prove that:
$$\int_0^{\pi}{xf\left( \sin x \right)}dx=\pi \int_0^{\frac{\pi}{2}}{f\left( \sin x \right)}dx$$
then
$$
\begin{align*}
&\int_0^{\pi}{\frac{x}{1+\sin ^2x}}dx
\\
&=\pi \int_0^{\frac{\pi}{2}}{\frac{1}{1+\sin ^2x}}dx
\\
&=\pi \int_0^{\frac{\pi}{2}}{\frac{1}{2\tan ^2x+1}}d\tan x
\\
&=\frac{\pi}{\sqrt{2}}\mathrm{arc}\tan \frac{\tan x}{\sqrt{2}}\mid_{0}^{\frac{\pi}{2}}
\\
&=\frac{\pi ^2}{2\sqrt{2}}
\end{align*}
$$
Answer: As a hint : divide into two equal integral
$$\int_0^{\pi} \frac{x}{1+sin^2{x}}=\int_0^{\frac{\pi}{2}} \frac{x}{1+sin^2{x}}dx
+\int_{\frac{\pi}{2}}^{\pi} \frac{x}{1+sin^2{x}}dx\\=2\int_0^{\frac{\pi}{2}} \frac{x}{1+sin^2{x}}dx
$$ zero is cause of symmetry in the interval
Comment: @Crustocean01: it is a periodic function with $T=\pi$ so the integral of the function is periodic too, so the $F(\pi)-F(0)=0$ it doesn't about symmetry at all, but symmetry helps you to find it's value.
Comment: As I said, I already know about that method, answer should be pi squared by 2*root(2), I just want to know why is it necessary to convert the limit to pi by 2. It appears solvable in the way I approached but I cannot figure out why can't I solve it.
Comment: @Crustocean01: I added a picture that shows why $\int=F(\pi)-F(0)=0-0$  you did not anything wrong ,but the function symmetry on the interval causes zero , if you take twice on $[0,\pi/2]$ then your substitution works
Comment: Could you please elaborate what symmetry has to do with the integral becoming zero, also shouldn't the function have x in the numerator?
Comment: So it becomes mandatory to change limit from [0,pi] to [0,pi/2] in such integrals involving periodicity? I thought these properties of definite integrals were typically used to make complex problems simpler, but here it appears to be the only way to get the required solution.
Comment: The integrals  over $[0,\pi/2]$ and $[\pi/2,\pi]$ of the function ${x\over 1+\sin^2x}$ are not equal. The first one is less than the second one.
Answer: The mistake made when OP make the substitution:
Let

$$t =\sqrt2\tan x$$
$$\frac{dt}{\sqrt2} =\sec^2xdx$$
The limits also change upon substitution, so the integral I get is:
$$I=\frac{\pi}{2\sqrt2}\int_0^{0} \frac{1}{1+t^2}dt$$

where the domain of the substitution $t =\sqrt2\tan x$ should be $[-\frac{\pi}2, \frac{\pi}2]$ is bijective so that its inverse exists. To make the substitution works, we could use the symmetry of sine function on $[0,\pi]$ to reduce the integration interval as:
$$\begin{aligned}I&=\frac{\pi}{2}\int_0^{\pi} \frac{\sec^2x}{1+2\tan^2x}dx= \pi\int_0^{\frac \pi2} \frac{\sec^2x}{1+2\tan^2x}dx \\&= \pi \int_0^{\infty} \frac{d t}{1+2 t^2} \quad  (\textrm{ via }t=\sqrt 2 \tan x)\\&= \frac{\pi}{\sqrt{2}}\left[\tan ^{-1} \sqrt{2} t\right]_0^{\infty} = \frac{\pi^2}{2 \sqrt{2}} \end{aligned}$$
Answer:
An alternative to symmetry is to use method of residues.

Use $\sin(x) = \dfrac{e^{ix} - e^{-ix}}{2i}$ and map a contour defined by $C$, which corresponds to the unit circle (positive). So, define $z = e^{ix},\, dz = iz\cdot dx$. The integral then becomes
$$I = \frac{1}{2} \cdot \frac{\pi}{2}\int_{C}{\frac{1}{1 + \left(\frac{z - 1/z}{2i}\right)^2}}{\cdot\frac{dz}{iz}}
=\frac{i\pi}{4}\int_{C}{\frac{4z}{z^4 - 6z^2 + 1}}{dz}$$
Observe that $z^4 - 6z^2 + 1 = (z + \sqrt{2} + 1)(z - \sqrt{2} - 1)(z + \sqrt{2} - 1)(z - \sqrt{2} + 1)$. There are $2$ simple poles inside our semi-circle, $z = \pm(\sqrt{2} - 1)$. Hence,
$$I = 2\pi i \cdot\frac{i\pi}{4} \cdot \sum{Res(f(z), z_k)}
\\=\frac{-\pi^2}{2} \left( Res_{z \to \sqrt{2} - 1}(f(z)) +  Res_{z \to -\sqrt{2} + 1}(f(z))\right)
\\=\frac{-\pi^2}{2} \left(\lim_{z \to \sqrt{2} - 1}{\frac{4z(z - \sqrt{2} + 1)}{z^4 - 6z^2 + 1}} +  \lim_{z \to -\sqrt{2} + 1}{\frac{4z(z + \sqrt{2} - 1)}{z^4 - 6z^2 + 1}}\right)
\\= \frac{-\pi^2}{2}\left(\frac{-\sqrt{2}}{4} + \frac{-\sqrt{2}}{4}\right)
\\ = \frac{\pi^2\sqrt{2}}{4}$$


RegEx validation in XML schema

Question: <code><xs:simpleType name="Personalname">
<xs:restriction base="xs:string">
<xs:pattern value=".{0,0}|\w+([-]\w+)*( (\w)+)+"/>
</xs:restriction>
</xs:simpleType>
</code>
I am trying to restrict my XML Input Values to the above pattern.It can accept hyphen between two names.
This should except names like "Ankit Bansal" or "Ankit-Bansal Agarwal" 0r "Ankit Bansal Bansal" according to the logic in the pattern
But whenever I run with the following pattern it gives me an error like

[CDATA[The 'Personalname' element has an invalid value according to its data type. An error occurred at , (1, 329).]
Comment: `.{0,0}` -> It should be safe to throw this away (but leave the `|` alone) (not an answer to your problem)
Comment: Okay...That is anyways not the solution to the problem.The main part of the problem is with after the | symbol
Answer: <code>^((?:(?:\b[A-Za-z0-9]+[ -])+)\w+)$
</code>
You can try this.See demo.
http://regex101.com/r/xT7yD8/11
Comment: Thanks..Its validating successfully in the compiler.But in my code there is same error given.The original string which I am trying to change is ""
Comment: @AnkitBansal try removing `^` and `$` and try again
Comment: The expression you gave excepts "Ankit Bansal" but does not except "Ankit-Bansal bansal" etc...I think there is some other validation which is causing the issue...But according to my knowledge this error is only received when the xml validation fails.
Comment: @AnkitBansal it accepts `Ankit-Bansal bansal`as you can see in demo.There has to some other issue

RegEx validation in XML schema


How to compute the confidence coefficient

Question: Given the value of alpha (confidence level), how I can compute the he confidence coefficient?
The value of the confidence coefficient is given for 90%, 95% and 99%. My question is how to find the value of the confidence coefficient for 92% as example. Source of the picture is : link.
Answer: You can find the confidence coefficient from tables of the standard normal distribution. I don't know what style of table you may have at hand, but for a 92% confidence interval, you want the z-value that cuts 4% of the probability from the upper tail of
the standard normal distribution. (You may find a graph at the top of the table with a shaded area that gives an idea what probabilities are to be found in the table.)
Look in the body of the table for the nearest relevant value, then get the z-value from the margins of the table. By symmetry, the negative of that z-value will cut probability 4% from the lower tail, leaving 92% of the probability in the center. The answer is $z = 1.75$

If you're having trouble figuring out how the printed table works, remember that the confidence coefficient for a 95% confidence interval is $1.96.$ Look in the margins of the table
  for $1.96$ and then see how the corresponding value in the table is related to .9750 or .0250.$

Alternatively, you can use software. Software can be a little more accurate because you can get the exact value to several decimal places. (Using a normal table, you will find probabilities to four places in the body of the table, but you may not find an exact match to cut 4% from the upper tail; then without interpolation, you can get only two places behind the decimal point from the margins of the table.)
In R statistical software, the computation is as shown below.
(To get 4% above, you want 96% below.) You get 1.7507, rounding to 4 places.
<code>qnorm(.96)
[1] 1.750686
</code>
Either way,  $Z_{\alpha/2} = Z_{.08/2} = Z_{.04} = 1.76$ so that a 92% confidence interval is of the form $\bar X \pm 1.76\frac{\sigma}{\sqrt{n}.}$
In the figure below, the area (probability) under the standard normal curve  between the dotted vertical lines, at $\pm 1.75,$ is $0.92.$
Comment: I tried your solution and I found the value of the confidence coefficient. Thanks for your detailed explanation.


Image GridView display Large Image when user Click

Question: I am coding image gridview in android and I would like to question you how to show Large image when user click on small image in gridview and how can I make gridview able to scrolling by swipe because my gallery has a lot of images.
Here is my code:
<code>public class myalbum extends Activity {

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.myalbum);

    GridView gridView = (GridView) findViewById(R.id.gridview);
    gridView.setAdapter(new ImageAdapter(this));

    gridView.setOnItemClickListener(new GridView.OnItemClickListener()
    {
        public void onItemClick(AdapterView<?> parent, View v, int position, long id)
        {
            //Here I want to see Large Image???? How can i do?????
            Toast.makeText(myalbum.this, "" + position, Toast.LENGTH_SHORT).show();
        }
    });
}

public class ImageAdapter extends BaseAdapter {
    private Context mContext;

    public ImageAdapter(Context c) {
        mContext = c;
    }

    public int getCount() {
        return mThumbIds.length;
    }

    public Object getItem(int position) {
        return null;
    }

    public long getItemId(int position) {
        return 0;
    }

    HashMap<Integer, Matrix> mImageTransforms = new HashMap<Integer,Matrix>();
    Matrix mIdentityMatrix = new Matrix();
    //---returns an ImageView view---
 // create a new ImageView for each item referenced by the Adapter
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView;
        if (convertView == null) {  // if it's not recycled, initialize some attributes
            imageView = new ImageView(mContext);
            imageView.setLayoutParams(new GridView.LayoutParams(88, 88));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(2, 2, 2, 2);
        } else {
            imageView = (ImageView) convertView;
        }

        Matrix m = mImageTransforms.get(position);
        if ( null == m ) {
            m = mIdentityMatrix;
        }
        imageView.setImageMatrix(m);
        imageView.setImageResource(mThumbIds[position]);
        return imageView;
    }

    void setImageRotation(int position, int degrees) {
        Matrix m = mImageTransforms.remove(position);
        if ( degrees != 0 ) {
            if ( null == m ) m = new Matrix();
            m.setRotate(degrees);
            mImageTransforms.put(position, m);
        }
        notifyDataSetChanged();
    }

    private Integer[] mThumbIds = {
            R.drawable.p1, R.drawable.p2,
            R.drawable.p1, R.drawable.p2,
            R.drawable.p1, R.drawable.p2,
            R.drawable.p1, R.drawable.p2,
            R.drawable.p3, R.drawable.p4
    };
  }
}
</code>
Best Regards,
Virak
Answer: Actually i can't get where you actually want to display image.
By the way you need to add your grid view in FrameLayout so, after that you can create on layout programmatically(with background color transparent) add imageView to it in same way and add that layout to your frameLayout  and on image click you can set its visibility to visible so it displays image on top of your grid view as you simply view images on FB
and provide close button which sets the visibility of that layout to Gone.
Hope this helps you. let me know if any problem..
Comment: Dear Jay, I want the image on GrideView is able to click.. and after clicked full size of the image will be appear on the Top of same activity.
Comment: so, where is the problem the image you want supply it to that imageview in layout it solves your problem. explanation given it helps you to how to do what you want.


Reverse for 'date_detail' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['date/(?P[0-9]+)$']

Question: I have two models and a third model for a many-to-many relationship
the form should take a date from the first model that is the date model and the user will choose images from the second model and connect them
but when I'm making the form I'm getting this error
Reverse for 'date_detail' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['date/(?P[0-9]+)$']
my models.py
class MyDate(models.Model):
    english_date = models.DateField(auto_now=False)
    hebrew_date = models.CharField(max_length=20,unique=True)
    sof_zman_1 = models.TimeField(auto_now=False,blank=True,null=True)
    sof_zman_2 = models.TimeField(auto_now=False,blank=True,null=True)
    sof_zman_tefila = models.TimeField(auto_now=False,blank=True,null=True)

    def get_absolute_url(self ):
        return reverse('date_detail',kwargs={'pk':self.pk})

    def __str__(self):
        return self.hebrew_date

# images
class Images(models.Model):
    image = models.ImageField(unique=False,upload_to='images/')

    def get_absolute_url(self):
        return reverse("image_detail",kwargs={'pk':self.pk})

#connect days and images together
class DayImage(models.Model):
    date = models.ForeignKey('luach.MyDate',related_name='day',on_delete=models.CASCADE)
    image = models.ManyToManyField('luach.images',related_name='images')

    def __str__(self):
        return self.pk

my views.py
def create_day_image_view(request,pk):
    date = get_object_or_404(MyDate,pk=pk)
    if request.method == 'POST':
        form = DayImageForm(request.POST)
        if form.is_valid():
            dayimage = form.save(commit=False)
            dayimage.date = date
            dayimage.save()
            return redirect('date_detail',pk=date.pk)

    else:
        form = DayImageForm()
    return render(request, 'luach/dayimage_form.html',{'form': form})

my urls.py
urlpatterns = [
    path('admin/', admin.site.urls),
    path('date/<int:pk>',views.MyDateDetailView.as_view(),name='date_detail'),
    path('date/<int:pk>/add_image/',views.create_day_image_view,name='add_image')
]

and my dayimage_form.html
{% block content %}

            <form method="POST">
                {% csrf_token %}
                {{form.as_p}}
                <button type='submit' class='btn btn-success'>save</button>
            </form>
            cancel

{% endblock  %}

Comment: Where exactly is `mydate` in `return redirect('date_detail',pk=mydate.pk)` created? I see a reference, but no assignment to that variable.
Answer: It could be that this line causes the error

because I don't see anywhere that you pass the variable date to the template context, so it probably is None, which causes the error.
A solution could be to pass the variable to the context:
return render(
    request,
    'luach/dayimage_form.html',
    {
        'form': form,
        'date': date,
    })


Need help with a PMF example

Question: Was reading through my lecture slides and I saw this question

I am not sure what or how the prof approached this problem after step 6.
It'd be greatly appreciated if anyone can tell me what's going on here.
Answer: You have 12 in your sixth arrow should this be 1/2? If this is a typo (either in your slides or this post)  then the rest of the problem seems straightforward,  multiply by 2 to get $2y(x)=y(x+1) +y(x-1)$ then $2y(x) = y(x) + y(x)$ and rearrange to get the 7th arrow. Then the problem is a matter of fitting an affine function to 2 points.
Comment: yeah, the prof had a typo in his slides which confused me a lot! thanks

Need help with a PMF example


"Net Send" command into Windows Server 2012 R2

Question: I remember that in preceding versions of Windows server there was a command to send to the client (in this case all with Windows 7 -64 bit-) a message that appears on the screen.
Still exist for Windows 2012 r2? What can I adapt?
Thanks.
Comment: 2 people think this question shows research effort.
Comment: When I try "msg /server:nomepc * prova" from prompt, return the error " * inesistente o disconnesso". Why?
Answer: You may use the msg command on Windows Server 2012 R2 to trigger a popup message dialog box on a remote computer.
The syntax is as follows:
msg {<UserName> | <SessionName> | <SessionID>| @<FileName> | *} [/server:<ServerName>] [/time:<Seconds>] [/v] [/w] [<Message>]

For example, to send "Hello" to all logged on users of a PC "host.contoso.com", enter:
msg /server:host.contoso.com * Hello

For parameter explanations and examples, refer to the Msg article on MS TechNet.
Comment: Are all workstations and servers joined under the same domain? Did you log on as an domain admin? Also, check the 3 points raised by "That Brazilian Guy" here: http://superuser.com/questions/583649/send-msg-over-lan-wireless
Comment: I try:- msg /server:nomepc * Messaggio Test - and it run. I try to another workstation after set hklm\system\currentcotrolset\control\terminal server  -> AllowRemoteRPC =1 and give the error : - * inesistente o disconnesso-. Why this error? Thanks.


ASP.NET MVC. Check if user is authorized from JavaScript

Question: I'm using ASP.NET MVC Framework 3 and Forms Authentication. I know, how to check on servers side, if the user is authorized for some action (with [Authorize]) and I know, how to check this within an action or a view (with User.Identity.IsAuthenticated or other members of 'User').
What I'm trying to do - is to define some JavaScript code, that will be executed differently, depending if the user is authorized.
Consider such script on the page:

}
else
{

}

But it doesn't seems to me as a good approach. Are there any other ways?
Thanks in advance.
PS: This is a usability issue, of course I'm doing necessary checks on server.
Comment: how about including external javascript files for each case.
Comment: I don't think there's anything wrong with your approach.
Comment: Actually, I thought to do so, if there is no other way. Anyways, thanks for your comment.
Answer: I like the idea in @Gaby's comment, though I am not sure whether that's doable since I don't have the whole picture on your project.
At the very least you can simplify your code by doing...

Answer: Another couple of options would be to use a custom HTML data- attribute or create a simple ajax request that asks the server if the user is authenticated.