text:
Q: Calculate Entry of Strings in Huge TXT file I have a huge file of aroung 7 GB in .txt format which I'm processing using this thread Reading very large files in PHP.
The sample of the .txt file:
cat
dog
dog
mouse
cat
bird
dog
cat
...

Now, I need to organize this file into something like:
[cat] -> 3
[dog] -> 3
[mouse] -> 1
[bird] -> 1

Please guide where to search to solve this matter.
Thank you for your time and advices.

A: You can try with array_count_values
So you have to convert your .txt into an array. The main probelem is I don't know if the file size would lead to an issue ...
To convert your file into an array you can use explode().
If you need this file each time your script is executed, maybe store the result you need into a database. Thus you can simply get the data you need without executing all the file.
Have fun :)

A: This is a very basic example. It reads the text file, one line at a time and counts the lines that are the same.
<?php

$fn = fopen("my_very_large_file.txt","r");

$wordCounter = [];

while(!feof($fn)) {
    $word = fgets($fn);
    if (isset($wordCounter[$word])) {
        $wordCounter[$word]++;
    }
    else {
        $wordCounter[$word] = 1;
    }
}

fclose($fn);

echo "<pre>";
print_r($wordCounter);
echo "</pre>";

This will be exceedingly slow. However, that's not really a problem if you only need to use the code once. If you need it more often you need to find a way to speed it up.


text:
Q: Is my definition of a triangle center function "equivalent" to the usual definition? There's a definition of triangle center function already in existence, but I don't really understand it. Anyway, here's my attempt at defining this concept using ideas I'm more comfortable with.

Let $E$ denote a Euclidean space; wlog we can assume $E=\mathbb{R}^n$.
By a triangle center function on $E$, let us mean a mapping $$c : E \leftarrow E \times E \times E$$ satisfying the following axioms.
Interiality. $c(x,y,z) \in \mathrm{convexHull}\{x,y,z\}$
Commutativity. $c(x,y,z) = c(y,x,z) = \cdots$
Similarity. For all bijective similarity transforms $f : E \leftarrow E$, we have $$f(c(x,y,z)) = c(fx,fy,fz).$$

What I'd like to know is:

Question. Can anyone tell whether or not these definitions are somehow equivalent, and if so, in what sense?

A: Your first condition is not satisfied by some triangle centers: for example, the circumcenter of a triangle can lie outside it.
Wikipedia's definition might be a bit more understandable.

A: Types of Triangle Center Functions
A triangle center function, as defined on MathWorld, is a function $f_{1}:\mathbb{R}^{+}\times\mathbb{R}^{+}\times\mathbb{R}^{+}\to\mathbb{R}$. It must satisfy bisymmetry in the second and third arguments: $f_{1}\left(a,c,b\right)=f_{1}\left(a,b,c\right)$ and homogeneity: there is a number $m$ such that $f_{1}\left(ta,tb,tc\right)=t^{m}f_{1}\left(a,b,c\right)$. The intent is for $a,b,c$ to represent the side lengths of a triangle. By the law of cosines, we can permit a formula for $f_{1}$ to contain some trigonometric expressions such as $\cos A$, since $\cos A=\dfrac{-a^{2}+b^{2}+c^{2}}{2bc}$ is homogeneous of degree $0$ and bisymmetric in $b$ and $c$.
MathWorld also mentions a third property, "cyclicity", but that is not actually a property of $f_{1}$. Rather, given an $f_{1}$, there is a related function, which MathWorld also seems to call a "triangle center function", which outputs a triple of numbers (separated here by colons to emphasize their homogeneity): $\mathbf{f}_{2}\left(a,b,c\right)=f_{1}\left(a,b,c\right):f_{1}\left(b,c,a\right):f_{1}\left(c,a,b\right)$. Given a triangle with side lengths $a,b,c$, the triple $\mathbf{f}_{2}$ is intended to give the trilinear coordinates of a special point.
To avoid homogeneous coordinates (such as trilinear or barycentric), and to make a definition easier to understand, we can define the following related function on points in a Euclidean space: $\mathbf{f}_{3}:E\times E\times E\to E$
by $\mathbf{f}_{3}\left(\mathbf{A},\mathbf{B},\mathbf{C}\right)=$
"the point in the plane containing $\mathbf{A},\mathbf{B},\mathbf{C}$
whose trilinear coordinates with respect to $\triangle\mathbf{ABC}$ are given by $\mathbf{f}_{2}\left(\left\|\mathbf{C}-\mathbf{B}\right\|,\left\|\mathbf{A}-\mathbf{C}\right\|,\left\|\mathbf{B}-\mathbf{A}\right\|\right)$". Since this comes from $f_1$ in the standard way, I will call it "the Euclidean triangle center function associated to $f_1$ (in $E$)".
In the question, goblin defines another sort of function. As Qiaochu Yuan noted in their answer, "Interiality" (using the convex hull) is not a great axiom because of centers like the circumcenter. However, being charitable, we can make the minor change from "convex hull" to "affine hull" (a.k.a. "affine span") and consider the same question. $\mathbf{f}:E\times E\times E\to E$ is said to be a goblin center function if it's "commutative" (the function is invariant under all permutations of its arguments), "planar" ($\mathbf{f}$ always lies in the affine span of its arguments), and "similar" ($\sigma\left(\mathbf{f}(\mathbf{A},\mathbf{B},\mathbf{C})\right)=\mathbf{f}\left(\sigma(\mathbf A),\sigma(\mathbf B),\sigma(\mathbf C)\right)$ for all similarity transformations $\sigma$).

Theorem

Every Euclidean triangle center function is a goblin center function and vice versa.

Proof of first direction
For convenience, define the following implicit functions of $\mathbf{A},\mathbf{B},\mathbf{C}$: $a=\left\Vert \mathbf{C}-\mathbf{B}\right\Vert$, $b=\left\Vert \mathbf{A}-\mathbf{C}\right\Vert$, $c=\left\Vert \mathbf{B}-\mathbf{A}\right\Vert$. We can use facts about trilinear coordinates to write out $\mathbf{f}_{3}$ explicitly in terms of $f_{1}$. After choosing an origin (imagining $E$ as $\mathbb{R}^n$), we have: $$\mathbf{f}_{3}\left(\mathbf{A},\mathbf{B},\mathbf{C}\right)=\dfrac{af_{1}\left(a,b,c\right)}{\lambda}\mathbf{A}+\dfrac{bf_{1}\left(b,c,a\right)}{\lambda}\mathbf{B}+\dfrac{cf_{1}\left(c,a,b\right)}{\lambda}\mathbf{C}$$
where $\lambda=af_{1}\left(a,b,c\right)+bf_{1}\left(b,c,a\right)+cf_{1}\left(c,a,b\right)$ (assuming $\lambda\ne0$).
By definition, $\mathbf{f}_3$ is "planar". Next, we prove "commutativity".
Note that $a\left(\mathbf{A},\mathbf{C},\mathbf{B}\right)=a\left(\mathbf{A},\mathbf{B},\mathbf{C}\right)$, $b\left(\mathbf{A},\mathbf{C},\mathbf{B}\right)=c\left(\mathbf{A},\mathbf{B},\mathbf{C}\right)$, and $c\left(\mathbf{A},\mathbf{C},\mathbf{B}\right)=b\left(\mathbf{A},\mathbf{B},\mathbf{C}\right)$. Using $a,b,c$ to denote their values with arguments $\left(\mathbf{A},\mathbf{B},\mathbf{C}\right)$, we have $\lambda\left(\mathbf{A},\mathbf{C},\mathbf{B}\right)=af_{1}\left(a,c,b\right)+cf_{1}\left(c,b,a\right)+bf_{1}\left(b,a,c\right)$, which equals $\lambda\left(\mathbf{A},\mathbf{B},\mathbf{C}\right)$ after applying the bisymmetry of $f_{1}$. Similarly, $$\mathbf{f}_{3}\left(\mathbf{A},\mathbf{C},\mathbf{B}\right)=\dfrac{af_{1}\left(a,c,b\right)}{\lambda}\mathbf{A}+\dfrac{cf_{1}\left(c,b,a\right)}{\lambda}\mathbf{C}+\dfrac{bf_{1}\left(b,a,c\right)}{\lambda}\mathbf{B}=\mathbf{f}_{3}\left(\mathbf{A},\mathbf{B},\mathbf{C}\right).$$
In order to show that $\mathbf{f}_3$ is "commutative", it remains to show that $\mathbf{f}_{3}$ remains unchanged upon a cyclic permutation of $\mathbf{A},\mathbf{B},\mathbf{C}$ (since a transposition and a cyclic permutation generate $S_{3}$). Note that $a\left(\mathbf{B},\mathbf{C},\mathbf{A}\right)=b\left(\mathbf{A},\mathbf{B},\mathbf{C}\right)$, $b\left(\mathbf{B},\mathbf{C},\mathbf{A}\right)=c\left(\mathbf{A},\mathbf{B},\mathbf{C}\right)$, and $c\left(\mathbf{B},\mathbf{C},\mathbf{A}\right)=a\left(\mathbf{A},\mathbf{B},\mathbf{C}\right)$. Thus, $$\lambda\left(\mathbf{B},\mathbf{C},\mathbf{A}\right)=bf_{1}\left(b,c,a\right)+cf_{1}\left(c,a,b\right)+af_{1}\left(a,b,c\right)=\lambda\left(\mathbf{A},\mathbf{B},\mathbf{C}\right).$$ Hence, $$\mathbf{f}_{3}\left(\mathbf{B},\mathbf{C},\mathbf{A}\right)=\dfrac{bf_{1}\left(b,c,a\right)}{\lambda}\mathbf{B}+\dfrac{cf_{1}\left(c,a,b\right)}{\lambda}\mathbf{C}+\dfrac{af_{1}\left(a,b,c\right)}{\lambda}\mathbf{A}=\mathbf{f}_{3}\left(\mathbf{A},\mathbf{B},\mathbf{C}\right).$$
Finally, we show "similarity": let $\sigma$ be a similarity which multiplies all distances by $r$. Then $\lambda\left(\sigma\mathbf{A},\sigma\mathbf{B},\sigma\mathbf{C}\right)=raf_{1}\left(ra,rb,rc\right)+rbf_{1}\left(rb,rc,ra\right)+rcf_{1}\left(rc,ra,rb\right)=r^{m+1}\lambda\left(\mathbf{A},\mathbf{B},\mathbf{C}\right)$ by homogeneity of $f_{1}$. Hence, $$\mathbf{f}_{3}\left(\sigma\mathbf{A},\sigma\mathbf{B},\sigma\mathbf{C}\right)$$
$$=\dfrac{raf_{1}\left(ra,rb,rc\right)}{r^{m+1}\lambda}\sigma\mathbf{A}+\dfrac{rbf_{1}\left(rb,rc,ra\right)}{r^{m+1}\lambda}\sigma\mathbf{B}+\dfrac{rcf_{1}\left(rc,ra,rb\right)}{r^{m+1}\lambda}\sigma\mathbf{C}$$
$$=\dfrac{af_{1}\left(a,b,c\right)}{\lambda}\sigma\mathbf{A}+\dfrac{bf_{1}\left(b,c,a\right)}{\lambda}\sigma\mathbf{B}+\dfrac{cf_{1}\left(c,a,b\right)}{\lambda}\sigma\mathbf{C}.$$ Since the coefficients of $\sigma\mathbf{A}$,$\sigma\mathbf{B}$,$\sigma\mathbf{C}$ sum to 1 (by definition of $\lambda$), we have an affine combination, which commutes with affine transformations. Since similarity transformations on $\mathbb{R}^{n}$ are special cases of affine transformations, we have $\mathbf{f}_{3}\left(\sigma\mathbf{A},\sigma\mathbf{B},\sigma\mathbf{C}\right)=\sigma\mathbf{f}_{3}\left(\mathbf{A},\mathbf{B},\mathbf{C}\right)$. Note that this does not necessarily hold when $\sigma$ is affine but not a similarity (such as a shear), as we wouldn't have been able to apply the homogeneity of $f_{1}$ in that case.

Proof of second direction
Let $\mathbf{f}$ be a goblin center function. Since $\mathbf{f}$ is affine and every point in the plane is in the affine span of $\mathbf{A},\mathbf{B},\mathbf{C}$ when they are in general position, there are real-valued functions $f_{A},f_{B},f_{C}$ always summing to $1$ such that $\mathbf{f}\left(\mathbf{A},\mathbf{B},\mathbf{C}\right)=f_{A}\left(\mathbf{A},\mathbf{B},\mathbf{C}\right)\mathbf{A}+f_{B}\left(\mathbf{A},\mathbf{B},\mathbf{C}\right)\mathbf{B}+f_{C}\left(\mathbf{A},\mathbf{B},\mathbf{C}\right)\mathbf{C}$. Since $\mathbf{f}$ is "commutative", we have $\mathbf{f}\left(\mathbf{A},\mathbf{C},\mathbf{B}\right)=\mathbf{f}\left(\mathbf{A},\mathbf{B},\mathbf{C}\right)$, so that $$f_{A}\left(\mathbf{A},\mathbf{C},\mathbf{B}\right)\mathbf{A}+f_{B}\left(\mathbf{A},\mathbf{C},\mathbf{B}\right)\mathbf{C}+f_{C}\left(\mathbf{A},\mathbf{C},\mathbf{B}\right)\mathbf{B}$$ $$=f_{A}\left(\mathbf{A},\mathbf{B},\mathbf{C}\right)\mathbf{A}+f_{B}\left(\mathbf{A},\mathbf{B},\mathbf{C}\right)\mathbf{B}+f_{C}\left(\mathbf{A},\mathbf{B},\mathbf{C}\right)\mathbf{C}$$.
Since the coefficients on both sides sum to 1, we must have corresponding coefficients equal, so that $f_{A}\left(\mathbf{A},\mathbf{C},\mathbf{B}\right)=f_{A}\left(\mathbf{A},\mathbf{B},\mathbf{C}\right)$ ($f_{A}$ is bisymmetric in the second and third arguments), $f_{B}\left(\mathbf{A},\mathbf{C},\mathbf{B}\right)=f_{C}\left(\mathbf{A},\mathbf{B},\mathbf{C}\right)$ ($f_{B}$ becomes $f_{C}$ when the second and third arguments are swapped). By transposing other pairs, we find several other analogous relations. In conclusion, $f_{A}$ is bisymmetric, and $f_{B}\left(\mathbf{A},\mathbf{B},\mathbf{C}\right)=f_{A}\left(\mathbf{B},\mathbf{A},\mathbf{C}\right)$, $f_{C}\left(\mathbf{A},\mathbf{B},\mathbf{C}\right)=f_{A}\left(\mathbf{C},\mathbf{B},\mathbf{A}\right)$. Thus, we may write $\mathbf{f}\left(\mathbf{A},\mathbf{B},\mathbf{C}\right)=f_{A}\left(\mathbf{A},\mathbf{B},\mathbf{C}\right)\mathbf{A}+f_{A}\left(\mathbf{B},\mathbf{A},\mathbf{C}\right)\mathbf{B}+f_{A}\left(\mathbf{C},\mathbf{B},\mathbf{A}\right)\mathbf{C}$. Since $f_{A}$ is bisymmetric, we may also rewrite this in the more elegant form $\mathbf{f}\left(\mathbf{A},\mathbf{B},\mathbf{C}\right)=f_{A}\left(\mathbf{A},\mathbf{B},\mathbf{C}\right)\mathbf{A}+f_{A}\left(\mathbf{B},\mathbf{C},\mathbf{A}\right)\mathbf{B}+f_{A}\left(\mathbf{C},\mathbf{A},\mathbf{B}\right)\mathbf{C}$.
Let $\sigma$ be a similarity transformation. We should have $\sigma\mathbf{f}\left(\mathbf{A},\mathbf{B},\mathbf{C}\right)=\mathbf{f}\left(\sigma\mathbf{A},\sigma\mathbf{B},\sigma\mathbf{C}\right)$. Since $\mathbf{f}$, when written in terms of $f_{A}$, is an affine combination, we have $\sigma\mathbf{f}\left(\mathbf{A},\mathbf{B},\mathbf{C}\right)=f_{A}\left(\mathbf{A},\mathbf{B},\mathbf{C}\right)\sigma\mathbf{A}+f_{A}\left(\mathbf{B},\mathbf{C},\mathbf{A}\right)\sigma\mathbf{B}+f_{A}\left(\mathbf{C},\mathbf{A},\mathbf{B}\right)\sigma\mathbf{C}$. Setting this equal to $\mathbf{f}\left(\sigma\mathbf{A},\sigma\mathbf{B},\sigma\mathbf{C}\right)$ and equating coefficients, we have $f_{A}\left(\sigma\mathbf{A},\sigma\mathbf{B},\sigma\mathbf{C}\right)=f_{A}\left(\mathbf{A},\mathbf{B},\mathbf{C}\right)$ for all similarity transformations $\sigma$.
Intuitively, similarity transformations should be able to send a triangle to any similar triangle, so that $f_{A}$ may only depend on the length ratios $\dfrac{b}{a}=\dfrac{\left\Vert \mathbf{A}-\mathbf{C}\right\Vert }{\left\Vert \mathbf{B}-\mathbf{C}\right\Vert }$,$\dfrac{c}{a}$,$\dfrac{b}{c}=\dfrac{\frac{b}{a}}{\frac{c}{a}}$. But a function of $\dfrac{b}{a},\dfrac{c}{a}$ is equal to a homogeneous function of degree zero of $a,b,c$: we may write $f_{A}\left(\mathbf{A},\mathbf{B},\mathbf{C}\right)=\widetilde{f}\left(a,b,c\right)$ where $\widetilde{f}$ is homogeneous of degree zero.
[A bit more rigorously than the above: Once an origin is fixed, a similarity transformation has the form $\sigma\left(\mathbf{x}\right)=rM\mathbf{x}+\mathbf{t}$ where $M$ is orthogonal. After a translation, we may assume $\mathbf{A}$ is at the origin. After a potential reflection, we can assume that $\mathbf{B}-\mathbf{A}$, $\mathbf{C}-\mathbf{A}$ are a positively oriented basis for the plane they span. A rotation lets us choose the angle for $\mathbf{B}$, and then knowing the lengths tells us the angle for $\mathbf{C}$ by the law of cosines and the known orientation. Thus, $f_{A}$ can depend only on the lengths. However, dilations mean it can only depend on ratios of lengths (or immediately that it's a homogeneous-of-degree-zero function of the lengths).]
Note that $\widetilde{f}$ is bisymmetric since $f_{A}$ is. Finally, define $f\left(a,b,c\right)=\dfrac{1}{a}\widetilde{f}\left(a,b,c\right)$, which is still bisymmetric, and is homogeneous of degree $-1$ (and hence is a "triangle center function" in the sense of $f_{1}$). We have $$\mathbf{f}\left(\mathbf{A},\mathbf{B},\mathbf{C}\right)=f_{A}\left(\mathbf{A},\mathbf{B},\mathbf{C}\right)\mathbf{A}+f_{B}\left(\mathbf{A},\mathbf{B},\mathbf{C}\right)\mathbf{B}+f_{C}\left(\mathbf{A},\mathbf{B},\mathbf{C}\right)\mathbf{C}$$
$$=f_{A}\left(\mathbf{A},\mathbf{B},\mathbf{C}\right)\mathbf{A}+f_{A}\left(\mathbf{B},\mathbf{C},\mathbf{A}\right)\mathbf{B}+f_{A}\left(\mathbf{C},\mathbf{A},\mathbf{B}\right)\mathbf{C}$$
$$=af\left(a,b,c\right)\mathbf{A}+bf\left(b,c,a\right)\mathbf{B}+cf\left(c,a,b\right)\mathbf{C}$$
Since the coefficients of $\mathbf{A},\mathbf{B},\mathbf{C}$ sum to $1$ (by definition of $f_{A},f_{B},f_{C}$), we have $\lambda=af\left(a,b,c\right)+bf\left(b,c,a\right)+cf\left(c,a,b\right)\equiv1$, and so this says exactly that $\mathbf{f}$ is the Euclidean triangle center function associated to $f$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Shouldn't this be the standard way to prove that if $p>1$ then $p^n \to +\infty$? Proposition:
Let $p>1$. We have $$ \lim_{n\to +\infty} p^n = +\infty.$$
My professor proved this setting $p=1+\varepsilon$ for some $\varepsilon>0$ and then using Bernoulli's inequality and the comparison theorem.
Apart from using the definition of divergence, is this the standard way?
I guess my question sort of regards didactics. I'm asking because I feel like the following is more elementary:
$\{p^n\}$ is strictly increasing: $$p^{n+1}>p^n \iff \frac{p^{n+1}}{p^n} =p>1 $$ therefore if it doesn't diverge, it must approach $\alpha\in (1,+\infty)$. But then so does $\{p^{n+1}\}$, which implies $$\lim_{n\to\infty} \frac{p^{n+1}}{p^n}=p=\frac\alpha\alpha=1,$$ contradicting the assumption $p>1$.
I avoided using directly the ratio test as it seems to be more advanced, at least according to my book.


text:
Q: Converting coordinate ASC file (raster data) into a XY coordinate data frame I have read in an ASCII file with values that correspond to a UK coordinate grid, however, if I want to apply the which.closest() command I need to be able to specify the columns in terms of X and Y coordinates. So right now, below is an random example extract of the type of data frame I have:
           1000 2000 3000 4000 5000
    66000     1    2    3    4    5
    65000     1    2    3    4    5
    64000     1    2    3    4    5
    63000     1    2    3    4    5
    62000     1    2    3    4    5

Here is the script so you can reproduce this extract:
    a=c(1,1,1,1,1)
    b=c(2,2,2,2,2)
    c=c(3,3,3,3,3)
    d=c(4,4,4,4,4)
    e=c(5,5,5,5,5)
    df=data.frame(a,b,c,d,e)
    colnames_df=seq(1000,5000,1000)
    rownames_df=seq(62000,66000,1000)
    rownames_df=rev(rownames_df)
    colnames(df)=colnames_df
    rownames(df)=rownames_df
    df

and this is the data frame I want to be able to continue my analysis:
    X     Y      Z
    1000  62000  1
    1000  63000  1
    3000  64000  1
    1000  65000  1
    1000  66000  1
    2000  62000  2
    2000  63000  2
    2000  64000  2
    2000  65000  2
    2000  66000  2
    ...(etc.)

Is there a code that can do this easily rather than manually setting up a new data frame, specifying columns and rows, etc. because I have a data frame 1377 x 812 for 20 different air quality chemical measurements, so if there is a code it would make my life a lot easier. Any help is appreciated! Thank you!

A: If I understood correctly what you need :
library(dplyr)
library(tidyr)
df <- cbind(Y = rownames(df), df)
rownames(df) <- NULL
df <- df %>% gather(X, Z, -Y)

A: Here are two more traditional approaches (as compared to gather suggested by Thor6):
X <- as.integer(rep(colnames(df), each=nrow(df)))
Y <- as.integer(rep(rownames(df), nrow(df)))
a <- cbind(X, Y, Z = as.vector(as.matrix(df)))

With reshape (rather convoluted)
cn <- colnames(df)
b <- reshape(df, direction='long', varying=cn, v.names = "Z", times=cn, timevar = "X" )
b$Y <- rownames(df)
b <- b[, c('X', 'Y', 'Z')]
rownames(b) <- NULL

However, given that these are raster data, if these are stored in a standard file format, you would not need to make the data.frame in the first place, and you could do something like this:
library(raster)
r <- raster('raster data file')
d <- rasterToPoints(r)

If you also want the cells with NA
e <- cbind(xyFromCell(r, 1:ncell(r)), Z=values(r))

Working example
f <- system.file("external/test.grd", package="raster")
r <- raster(f)
d <- rasterToPoints(r)
e <- cbind(xyFromCell(r, 1:ncell(r)), Z=values(r))


text:
Q: How to create an order using mock object in phpunit in Magento? I am preparing phpunit tests. I need to create an order using mocking and that order i need to pass in my function.
Please suggest, How can i achieve this ?

A:  $orderMock = $this->getMockBuilder(Order::class)->disableOriginalConstructor()->getMock();
        $orderMock->expects($this->once())->method('getState')->willReturn('pending');

        return $orderMock;


text:
Q: Creating whole new view based on current user's group sharepoint 2013 I am trying to generate a view based on the current user's group name. Group Name I am gathering from the custom list.
My question is how to apply the gathered group name to 'Group Name' column as a view parameter.

The only solution I figured:
I have created a view with a parameter.
I have added an HTML Form Web Part into the same page and connected it to the list view (sending the value to the parameter via web part connection). Then with a window.onload function I gather the current user's group name and pass this value via Form Postback function. But since the Postback function triggers full page reload, it falls into the endless loop of form submission > page reload.
Another way I have tried is attaching a click event listener to the BY MY GROUPS tab and it works perfectly, but the only disadvantage is that the page reloads each time user clicks on this tab, which I would like to avoid.
So the solution that I need is a way to post the form without a page reload.
Another option suggested here is to use CSR (client side rendering), but that has its own problems:

*

*This code does not work as it is supposed to. In the console it shows me correct items, but the view appears untouchable.

*Even if it worked, the other column values are still viewable in the column filter, as in this screenshot:
So, it seems that CSR just hides items from the view (and they are still available). In other words its behavior is different from, for example, a CAML query.
Or am I getting it wrong and there's something wrong with my code?
Below you can find my CSR code:
<script type='text/javascript'>
(function() {
    function listPreRender(renderCtx) {
        SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function() {
            var currUserID = _spPageContextInfo.userId;
            var cx = new SP.ClientContext('/sites/support');
            var list = cx.get_web().get_lists().getByTitle('Group Members');
            var items = list.getItems(SP.CamlQuery.createAllItemsQuery());
            cx.load(items, 'Include(_x006e_x50,DepID)');
            cx.executeQueryAsync(
                function() {
                    var i = items.get_count();
                    while (i--) {
                        var item = items.getItemAtIndex(i);
                        var userID = item.get_item('_x006e_x50').get_lookupId();
                        var group = item.get_item('DepID').get_lookupValue();
                        if (currUserID === userID) {
                            var rows = renderCtx.ListData.Row;
                            var customView = [];
                            var i = rows.length;
                            while (i--) {
                                var show = rows[i]['Group_x0020_Name'] === group;
                                if (show) {
                                    customView.push(rows[i]);
                                }
                            }
                            renderCtx.ListData.Row = customView;
                            renderCtx.ListData.LastRow = customView.length;
                            console.log(JSON.stringify(renderCtx.ListData.Row));
                            break;
                        }
                    }
                },
                function() {
                    alert('Something went wrong. Please contact developer')
                }
            );
        });
    }
    function registerListRenderer() {
        var context = {};
        context.Templates = {};
        context.OnPreRender = listPreRender;
        SPClientTemplates.TemplateManager.RegisterTemplateOverrides(context);
    }
    ExecuteOrDelayUntilScriptLoaded(registerListRenderer, 'clienttemplates.js');
})();
</script>


text:
Q: Putty SSH Session closes immediately after login with latest ubuntu 18.04.2 LTS Update The session disconnects after about 5 seconds with putty. If I type the password really fast I can get the welcome screen before the connection is dropped. I do weekly updates so this is something pretty recent. I noticed with the new update it says "Using keyboard-interactive authentication". So something got changed and now my server is effectively bricked. Ideas??

A: Guess I asked prematurely. Not sure what was going on after the update, but CPU and network usage spiked. After it stopped I rebooted a second time and now it's working correctly.


text:
Q: How to find button inside of table row in protractor js?
I am using protractor js for testing. Here i want to click on delete button which inside of table row but when i try to find by id i am unable to find it.

Code:
it('should delete the batch successfully when admin is logged in', function(){
  element(by.repeater('batch in batches.list').row(0)).element(by.id('delete')).click();
  ptor.sleep(500);
  ptor.actions().sendKeys(protractor.Key.ENTER).perform();
}

Error:
    1) Batch modal should delete the batch successfully when admin is logged in
   Message:
     Error: No element found using locator: by.repeater(batch in batches.list").row("0")"

How can i make it work. Could anyone provide suggestions?

A: Here i am not sending delay so what happen i am checking for the button which is not loaded
ptor.sleep(500); fixes my problem. It took so much time to identify


text:
Q: Whenever running every 2 hours I am currently facing some problem to make whenever running as I wish. For example now it is 2:45pm and I want to my task run every 2 hours from now. So it should run at 4:45pm , 6:45pm, 8:45pm, 10:45pm ...
Thank for your help.

A: Have you tried official docs? Add (or create that file if it doesn't exist) to config/schedule.rb:
every 2.hours do
  #your task here
end

Or use raw cron syntax, somthing like that should be fine:
every '45 */2 * * *' do
  #task
end

This should run job every two hours at xx:45, i.e, 00:45, 2:45, etc.


text:
Q: Vb.net Webkit.net error "System.ComponentModel.Win32Exception" In my application, I was going to use the webkit browser. Unfortunatly, as soon as I downloaded it and placed it in my code, I get this error.
I have it referneced , in toolbox, please help.


text:
Q: Google Maps API not working on Kubernetes deployment Laravel application deployed on Kubernetes and making requests to https://maps.google.com/maps/api/geocode/json failing with:
SSL routines:tls_process_server_certificate:certificate verify failed

The same application works when running on Docker.
I have appended Google's Root CA certs from here https://developers.google.com/maps/root-ca-faq#what_is_happening to the server's trust store but no luck there either.
I can disable verification but that's not the correct approach.
Any ideas would be much appreciated.
Thanks.

A: According to the OP, the solution was:

The issue was that our security team scans external certificates and
re-package them with the company's own cert. Once I added the
company's cert to the trust store, everything worked fine. It seems
it's only an internal issue.


text:
Q: Elasticsearch 7.4 unable to update doc with the same query When I run this in Elasticsearch version 7.13.2 in one server, it works as expected:
POST user/_update/AEBFECC4FECC4
{
  "doc": {
   "name": "updated name"
  }
}

Response:
{
 "_index": "user",
 "_type": "_doc",
 "_id": "AEBFECC4FECC4",
 "_version": 9,
 "result": "updated",
 "_shards": {
  "total": 2,
  "successful": 1,
  "failed": 0
 },
 "_seq_no": 89,
 "_primary_term": 1
}

However when I do the same query with equivalent index in a different server with version 7.4.1, it returns this:
{
    "error": {
        "root_cause": [
            {
                "type": "action_request_validation_exception",
                "reason": "Validation Failed: 1: script or doc is missing;"
            }
        ],
        "type": "action_request_validation_exception",
        "reason": "Validation Failed: 1: script or doc is missing;"
    },
    "status": 400
}

What did I miss? Is there a hidden setting somewhere that prevents updating? I read the docs but the update method for version 7.4 is the same as 7.13.


text:
Q: K5 Graph Avoidance Coloring Game Graph Avoidance Game
Two players take turns coloring the edges of the complete graph, $K_5$. The first player colors edges blue and the second player colors edges red.  To win, the player must force their opponent to create a triangle with their colors.
I want to prove that the second player can always win.
Also, is it possible that some player can always force a red and blue C5?

A: (This is not an answer, but I need to post a graph.)
The question poser is not correct "that a draw isn't possible under $K_5$" as the following example illustrates:


text:
Q: Javascript: Subtract date to date. Today.getDate() is not a function I have been trying to subtract date format (yyyy-MM-dd) to another date format but to no avail. I looked up online but it's confusing and I got this error which says that is it not a function for today.getDate(). Could anyone provide me with a solution in subtracting? I am at my wits end.
Thanks in advance.

for (var i = 0; i < 3; i++) {
  var startDate = "2020-08-19"
  var today = new Date();
  var dd = today.getDate();
  var mm = today.getMonth() + 1; //January is 0!
  var yyyy = today.getFullYear();
  if (dd < 10) {
    dd = '0' + dd;
  }
  if (mm < 10) {
    mm = '0' + mm;
  }
  today = yyyy + '-' + mm + '-' + dd;
  today.setDate(today.getDate() - startDate);
  console.log(today.getDate() - startDate);
  if ((startDate - today) >= 30) {
    console.log("hello");
  } else if ((startDate - today) <= 30) {
    console.log("bye");
  }

};

A: You are mixing a few concepts:
var today = new Date();

This creates a Date object that wraps the number of milliseconds from 1/1/1970 at midnight UTC.
today = yyyy + '-' + mm + '-' + dd;

This is creating a string.
If your goal is to find out how many days are between two dates, your best bet is to use milliseconds since Unix epoch, sometimes called "Unix timestamps." With these timestamps, subtracting is straightforward since they're just numbers; you'll get the number of milliseconds between the two points of time. Getting from timestamps to number of days then becomes a matter of division:
const diff = Date.now() - Date.parse("2020-08-19");
const numDays = diff / (1000 * 60 * 60 * 24);


text:
Q: guessing a random numer i am learning javascript and i am trying to get a small number guessing "game", I guess you could call it.
A prompt shows up and asks you what your number will be. That input gets stored in a variable and then you can generate a random number.
I want to make it so if your guess is equal to the randomly generated number, the console logs a message.
HTML

Random Number Generator

Generate a random number between and

        <button id="generate" onclick="generateNumber();">Generate</button>

Your random number is:

JS:
let guess = prompt("What is your guess?");
let num1 = document.getElementById("num1");
let num2 = document.getElementById("num2");
let result = document.getElementById("result");

num1 = 1;
num2 = 10;
result.innerText = 0;

function generateNumber() {
    result.innerText = (Math.floor(Math.random() * num2) +1 );
    console.log(result);

    if (result == guess) {
        console.log("Your guess was correct!")
    };
}

A: Was such a result necessary? In addition, I added the number of matches :) The line is Number of matches.

let guess = prompt("What is your guess?");
let num1 = document.getElementById("num1");
let num2 = document.getElementById("num2");
let result = document.getElementById("result");
let result_matches = document.getElementById("matches");

num1 = 1;
num2 = 10;
result.innerText = 0;
number_matches = 0;

function generateNumber() {
    random_number = (Math.floor(Math.random() * num2) +1 );
    result.innerText = random_number;
    result_matches.innerText = number_matches;

    if (random_number == guess) {
        number_matches++;
        console.log(result.innerText + " --- " + "Your guess was correct!")
    } else {
        console.log(result.innerText);
    }
}

Random Number Generator

Generate a random number between and

        <button id="generate" onclick="generateNumber();">Generate</button>

Your random number is:

Number of matches:

A: Here's a demo

const stringToIntegerNumber = (inputString) => {
  if(inputString == null) return;

  const number = Number.parseInt(inputString, 10);
  if(!Number.isInteger(number)) return;

  return number;
};

const promptIntegerStringTemplate = ({min, max} = {}) => {
  const existMinMax = min != null && max != null;

  const promptString = [
    'Enter a integer',
    ` [${min}-${max}]`,
    ': '
  ];

  return existMinMax ? promptString.join('') : promptString[0] + promptString[2];
}

const askIntegerNumber = ({min, max} = {}) => {
  let number, input;

  const promptString = promptIntegerStringTemplate({min, max});
  do {
    input = prompt(promptString);
    number = stringToIntegerNumber(input);
  } while(number == null);

  return number;
};

const isValidIntegerNumberInRange = (number, min, max) => {
  if(number == null || min == null || max == null
     || ( !Number.isInteger(number) )
     || ( !Number.isInteger(min) )
     || ( !Number.isInteger(max) )
    ) return;

  return number >= min && number <= max;
};

const generateRandomIntegerNumber = ({min = 0, max = 10} = {}) => {
  if( ( !Number.isInteger(min) )
     || ( !Number.isInteger(max) ) ) return;

  return min + Math.floor(Math.random() * max);
};

const makeGuess = (min, max) => {
  let guess, validatedNumber;
  do {
    guess = askIntegerNumber({min, max});
    validatedNumber = isValidIntegerNumberInRange(guess, min, max) ? guess: null;
  } while(validatedNumber == null);

  return validatedNumber;
};

const updateNumber = (min, max) => {
  const num1 = document.querySelector('#num1');
  const num2 = document.querySelector('#num2');

  num1.textContent = min;
  num2.textContent = max;
};

const playGame = (min, max, randomInteger) => {
  const guess = makeGuess(min, max);
  if(guess === randomInteger)
    console.log(`Guess ${guess} is correct.`);
  else
    console.log(`Guess ${guess} is incorrect.\nCorrect answer is ${randomInteger}`);

  //Visuals
  const result = document.querySelector('#result');
  result.textContent = randomInteger;
}

const domainControler = () => {
  const [min, max] = [1, 10];
  const randomInteger = generateRandomIntegerNumber({min, max});

  //Visuals
  updateNumber(min, max);

    //Play
  setTimeout(() => playGame(min, max, randomInteger), 5);

};

const setup = () => {
  const generate = document.querySelector('#generate');
  generate.addEventListener('click', domainControler);
};

window.addEventListener('load', setup);

Random Number Generator

Generate a random number between and

        <button id="generate">Generate</button>

Your random number is:


text:
Q: create new dataframe based on group by and aggregates I have a pandas dataframe matches containing match results as follows:
year    winner      loser   score
1990    A           B       6-0
1990    B           C       5-0 RET
1990    A           B       4-0 RET
1990    C           C       6-0
1991    A           B       6-1
1991    A           C       4-1 RET
1991    B           A       6-4
1991    C           A       3-0 RET

I want to create a new dataframe containing wins, losses, and wins by retirement for each player per year.
The final output shoud look like:
year    player      wins    losses      rets
1990    A           2       0           1
1990    B           1       2           1
1990    C           1       2           0
1991    A           2       2           1
1991    B           1       1           0
1991    C           1       1           1

For wins and losses I can do this successfully.
I do:
w_group = matches.groupby(['year', 'winner']).size()
l_group = matches.groupby(['year', 'loser']).size()

And then create a new dataframe:
scores = pd.DataFrame({'wins' : w_group, 'losses' : l_group}).fillna(0)
#name the index
scores.index.names = ['year','player']

However, for calculating the wins via retirement I dont know how to achieve the column. I tried this:
ret_group = matches.groupby(['year', 'winner']).apply(lambda x: x[(x['score'].str.contains('RET').fillna(False))].count())

But this gives me the following exception:
raise KeyError('%s not in index' % objarr[mask])
KeyError: '[ 0.] not in index'

Your solution is highly appreciated

A: I changed
ret_group = matches.groupby(['year', 'winner']).apply(lambda x: x[(x['score'].str.contains('RET').fillna(False))].count())

to
ret_group = matches.groupby(['year', 'winner']).apply(lambda x: (x['score'].str.contains('RET').fillna(False)).sum())

Now it works.


text:
Q: HTML template doesn't see the variable passed from views I am trying to pass a variable from views.py to my login.html template.
This is my views.py
from django.shortcuts import render

# Create your views here.
def home(request):
    numbers = [1, 2, 3, 4, 5]
    context = {
        'numbers': numbers
    }

    return render(request, 'accounts/login.html', {'title': 'Login'}, context)

and this is my login.html
{% extends 'accounts/base.html' %}
{% block content %}

Welcome

Please log in to continue

    <button href="#" class="btn btn-outline-primary mt-1">Log in</button>
    {{ numbers }}
{% endblock content %}

also, this is my urls.py file inside of my application
from . import views
from django.urls import path

urlpatterns = [
    path('', views.home, name="home"),
    path('home/', views.home, name="home"),
]

I expect the list [1, 2, 3, 4, 5] to show on login.html, when the address is localhost:8000/myappname/home

A: You have two dictionaries for some reason. You only need one, which should contain all the values you want to pass.
def home(request):
    numbers = [1, 2, 3, 4, 5]
    context = {
        'numbers': numbers,
        'title': 'Login'
    }

    return render(request, 'accounts/login.html', context)


text:
Q: Change element style without JavaScript Is there a way to change CSS style for specified element without using JavaScript?
I don't want to use JS because of some browsers which do not support, or have disabled it...
Concrete example:
I have 2 DIVs (#menu and #content) and I want to set min-height CSS property of #content to actual height property of #menu (so if the #menu would be longer than #content, #content's and #menu's heights would be equal).

A: You problem can be solved with simple plain CSS. For the purpose of demonstration I am going to assume that you have a menu on the left side of your web page and with the rest of the page to follow its height. That behavior is easily achieved by combining floats and overflows.
HTML

Homepage

Hello world!

CSS
.content {
    width: 98%;
    overflow: hidden;
}

.menu {
    float: left;
    width:30%;
}

The trick is in using overflow:hidden on the outside wrapper which will make the content height always adjust to the height of the menu.


text:
Q: Installation Problem Magento 2.3.5p1 on Centos 7 I have been trying to install Magento on Centos 7 with Nginx and Maria Db for the past 2-3 days now but each time I got errors. I have tried several ways and changed Nginx configuration file and tried many possible solutions available on stackoverflow and Magento docs.
I was only able to install it correctly once, but that was giving me server level error i.e. php-fpm security.limit_extensions. Therefore, I made the necessary changes to Nginx and I am not getting this error anymore. However, now my installation has 404 error on all the CSS and other files. As shown in the image below.
Store Home Page:

Store Admin Panel

Nginx logs are full of errors like:
> 2020/07/05 08:23:45 [error] 8864#8864: *94 open()
> "/var/www/user/pub/static/version1593936946/adminhtml/Magento/backend/en_US/css/styles.css"
> failed (2: No such file or directory), client: x.x.x.x, server:
> www.domain.com, request: "GET
> /pub/static/version1593936946/adminhtml/Magento/backend/en_US/css/styles.css
> HTTP/1.1", host: "www.user.com", referrer:
> "https://www.user.com/index.php/admin_h7r4ak/admin/index/index/key/57fe0e9d24ad111c0afbf63b34a7fd456106047e74662ae8a/"

I have tried to give magento directory permissions with both, `files and & dir as 777' and also as mentioned in Magento docs i.e.

find var generated vendor pub/static pub/media app/etc -type f -exec
chmod g+w {} + find var generated vendor pub/static pub/media app/etc
-type d -exec chmod g+ws {} +

But this does not help. I have tried to install with both users i.e. nginx:nginx and user that i added to nginx group user:nginx. The result is same, as shown in the above images.
My Nginx.conf file:

    server {
    listen   80;
    server_name  example.com;
    root /var/www/example;
    return   301 https://www.example.com$request_uri;
    }
    server {
    listen   80;
    server_name  www.example.com;
    root /var/www/example;
    return   301 https://www.example.com$request_uri;
    }
    server {
    listen   443 ssl http2;
    server_name example.com;
    keepalive_timeout    70;
    root   /var/www/example;
    return   301 https://www.example.com$request_uri;

    gzip    on;
    ssl_certificate  /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key  /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
    ssl_protocols   TLSv1.2;
    ssl_ciphers     EECDH+AESGCM:EDH+AESGCM:ECDHE-RSA-AES128-GCM-SHA256:AES256+EECDH:DHE-RSA-AES128-GCM-SHA256:AES256+EDH:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:ECDHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES128-SHA256:DHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES256-GCM-SHA384:AES128-GCM-SHA256:AES256-SHA256:AES128-SHA256:AES256-SHA:AES128-SHA:DES-CBC3-SHA:HIGH:!aNULL:!eNULL:!EXPORT:!DES:!MD5:!PSK:!RC4:!3DES;
    ssl_dhparam     /etc/nginx/conf.d/dhparam.pem;
    ssl_prefer_server_ciphers   on;
    ssl_session_tickets     off;
    ssl_session_cache       shared:SSL:10m;
    }

    server {
    listen   443 ssl http2;
    server_name www.example.com;
    keepalive_timeout    70;

    gzip    on;
    #       modsecurity on;
    #       modsecurity_rules_file /etc/nginx/modsec/main.conf;

    ssl_certificate  /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key  /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
    ssl_protocols   TLSv1.2;
    ssl_ciphers     EECDH+AESGCM:EDH+AESGCM:ECDHE-RSA-AES128-GCM-SHA256:AES256+EECDH:DHE-RSA-AES128-GCM-SHA256:AES256+EDH:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:ECDHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES128-SHA256:DHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES256-GCM-SHA384:AES128-GCM-SHA256:AES256-SHA256:AES128-SHA256:AES256-SHA:AES128-SHA:DES-CBC3-SHA:HIGH:!aNULL:!eNULL:!EXPORT:!DES:!MD5:!PSK:!RC4:!3DES;
    ssl_dhparam     /etc/nginx/conf.d/dhparam.pem;
    ssl_prefer_server_ciphers   on;
    ssl_session_tickets     off;
    ssl_session_cache       shared:SSL:10m;

    add_header   X-Frame-Options "DENY";
    add_header   X-Content-Type-Options nosniff;

    access_log  /var/log/nginx/example.access.log;
    error_log   /var/log/nginx/example.error.log;

    set $MAGE_ROOT /var/www/example;      root $MAGE_ROOT/pub;
          charset UTF-8;      autoindex off;

    location / {
            root   /var/www/example;
            #try_files $uri $uri/ = /404.html;
            if ($request_uri ~ ^/(.*)\.html$) {  return 302 /$1;  }
            try_files $uri $uri/ $uri.html $uri.php?$args;
            #try_files $uri $uri/ /index.php$is_args$args;
            index  index.php index.html;
            add_header   Strict-Transport-Security "max-age=63072000; includeSubdomains" always;
    }

    error_page 404 403 = /errors/404.php;
    # redirect server error pages to the static page /50x.html
    #
    error_page  500 502 503 504  = /errors/50x.php;

  # PHP entry point for update application
  location ~* ^/update($|/) {
      root $MAGE_ROOT;
      index  index.php;
      location ~ ^/update/index.php {
          fastcgi_split_path_info  ^(/update/index.php)(/.+)$;
          fastcgi_pass   php-fpm;
          fastcgi_index  index.php;
          fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
          fastcgi_param  PATH_INFO        $fastcgi_path_info;
          include        fastcgi_params;
      }

      # Deny everything but index.php
      location ~ ^/update/(?!pub/). {
          deny all;
      }

      location ~ ^/update/pub/ {
          add_header X-Frame-Options "SAMEORIGIN";
      }       }

  location /pub/ {
  location ~ ^/pub/media/(downloadable|customer|import|custom_options|theme_customization/.*\.xml)
  {
          deny all;
      }
      alias $MAGE_ROOT/pub/;
      add_header X-Frame-Options "SAMEORIGIN";        }

  location /static/ {
      # Uncomment the following line in production mode
      # expires max;

      # Remove signature of the static files that is used to overcome the browser cache
      location ~ ^/static/version {
          rewrite ^/static/(version\d*/)?(.*)$ /static/$2 last;
      }

      location ~* \.(ico|jpg|jpeg|png|gif|svg|js|css|swf|eot|ttf|otf|woff|woff2|html|json)$
      {
          add_header Cache-Control "public";
          add_header X-Frame-Options "SAMEORIGIN";
          expires +1y;

          if (!-f $request_filename) {
              rewrite ^/static/(version\d*/)?(.*)$ /static.php?resource=$2 last;
          }
      }

      location ~* \.(zip|gz|gzip|bz2|csv|xml)$ {
          add_header Cache-Control "no-store";
          add_header X-Frame-Options "SAMEORIGIN";
          expires    off;

          if (!-f $request_filename) {
                  rewrite ^/static/(version\d*/)?(.*)$ /static.php?resource=$2 last;
          }
      }
          if (!-f $request_filename) {
          rewrite ^/static/(version\d*/)?(.*)$ /static.php?resource=$2 last;
      }
      add_header X-Frame-Options "SAMEORIGIN";        }

  location /media/ {
      try_files $uri $uri/ $uri.html $uri.php?$args;

      location ~ ^/media/theme_customization/.*\.xml {
          deny all;
      }

      location ~* \.(ico|jpg|jpeg|png|gif|svg|js|css|swf|eot|ttf|otf|woff|woff2)$ {
          add_header Cache-Control "public";
          add_header X-Frame-Options "SAMEORIGIN";
          expires +1y;
          try_files $uri $uri/ $uri.html $uri.php?$args;
      }
      location ~* \.(zip|gz|gzip|bz2|csv|xml)$ {
          add_header Cache-Control "no-store";
          add_header X-Frame-Options "SAMEORIGIN";
          expires    off;
          try_files $uri $uri/ $uri.html $uri.php?$args;
      }
      add_header X-Frame-Options "SAMEORIGIN";        }

  location /media/customer/ { deny all; }

  location /media/downloadable/ { deny all; }

  location /media/import/ { deny all; }

  location /media/custom_options/ { deny all; }

  location /errors/ {
      location ~* \.xml$ { deny all; }        }

  # Deny access to sensitive files
  location /.user.ini { deny all; }

  ######################################################################
  ######################################################################

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    location ~* \.php$ {
            root           /var/www/example;
            fastcgi_pass php-fpm;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            if ($request_uri ~ ^/([^?]*)\.php($|\?)) {  return 302 /$1?$args;  }
            try_files $uri = 404;
            fastcgi_split_path_info  ^(.+\.php)(/.+)$;
            fastcgi_param QUERY_STRING  $query_string;
            fastcgi_param REQUEST_METHOD  $request_method;
            fastcgi_param CONTENT_TYPE  $content_type;
            fastcgi_param CONTENT_LENGTH  $content_length;
            fastcgi_intercept_errors  on;

            fastcgi_param  PHP_FLAG  "session.auto_start=off \n suhosin.session.cryptua=off";
            fastcgi_connect_timeout  600s;
            fastcgi_read_timeout  600s;
            fastcgi_buffers 1024 4k;
            include  fastcgi_params;
    }

  gzip_disable "msie6";
  gzip_comp_level 6;
  gzip_min_length 1100;
  gzip_buffers 16 8k;
  gzip_proxied any;
  gzip_types
      text/plain
      text/css
      text/js
      text/xml
      text/javascript
      application/javascript
      application/x-javascript
      application/json
      application/xml
      application/xml+rss
      image/svg+xml;      gzip_vary on;

  # Banned locations (only reached if the earlier PHP entry point regexes don't match)
  location ~* (\.php$|\.phtml$|\.htaccess$|\.git) {
      deny all;       }

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    location ~ /\.ht {
            deny  all;
    }
    }

I have set memory_limit to 3G and execution timeout to 18000. What am I missing here?

A: In development mode (the default after installing magento2) the app deploys assets to pub/static and also uses var/view_preprocessed to generate files. Try rm -rf pub/static/* && rm -rf var/view_preprocessed/*
Personally, i make a user called magento and add it to the www-data group, with a php-fpm pool configured for that user. I then sudo su - magento (for user magento) and deploy in there, saves problems with permissions every deployment. Happy to help if have issues still, for now though, add your user to www-data, then chown -r user:www-data the entire magento dir, and clear the static and view_preprocessed dirs

A: Try:
php bin/magento setup:static-content:deploy -f

A: go to your magento root directory navigate to app/etc/di.xml
search for symlink and replace it with Copy
now just flush:cache and check


text:
Q: Why would a programmer want to separate each function to its own assembly or project? I was just wondering why would a programmer want to have one class library or project per function? I have a client and want it to be in separate assembly for each function.
I am not sure of the purpose but can anybody tell me the advantage? purpose or benefit of it?
ex. SearchPerson(){} and GetAllEmails(){} are different function but why not just put it in the same solution just different class?

A: One advantage of high modularity, is that (given the code is written for high reuseability) you could easily restructure the final build, patch a production envrionment, by only affecting a small part of the solution etc.
It is always a trade off. One large solution might be easier to manage in the development phase.


text:
Q: Let $W$ be a subspace of a vector space $V$, then which of the following are correct
I think $W=0$. But I have not been able to prove mathematically.

A: Your guess is right. Every subspace contains $0$. Suppose $W$ contains some nonzero vector $e_1$. Extend this vector to a basis $\{e_1,e_2,...,e_n\}$ an define $f(\sum a_ie_i)=a_1$. This gives an element $f$ of $V^{*}$ and $f(e)=1$ contradicting the hypothesis.  Hence $W=\{0\}$.


text:
Q: How to recorder a video in android with Unity3D and vuforia integration I am developing an android application which should record a video. This application has Unity3D(5.3.5f1) and Vuforia(5.x) integration.
I looked into several plugins and C# code but the only thing i found it was like video playback but I need record the video.
Does anyone know how to do that?


text:
Q: apply the edge detection in an image segmentation I have two questions about snake edge detection.
The first question is, in openCV there is a function cvSnakeImage(src,points,.......), what does the points parameter mean?
The second questions is: I want to  apply this function on the part surrounded by an edge that I have already made, how can I do this?
This is my code for edge detection:
cvCanny(img_bw, img_canny , thresh, thresh * 50, 3);

cvFindContours(img_canny, contour, &contours, sizeof(CvContour), CV_RETR_TREE,    CV_CHAIN_APPROX_SIMPLE);

A: points parameter is the pointer to the snakes point array
https://fossies.org/dox/opencv-2.4.8/snakes_8cpp_source.html
Here is an example of how to use snakes
http://download.andol.info/cvsnakeimage.cpp


text:
Q: Azure function app failed to deployment because of spacy-transformer module torch is not installing and getting failed and I need that module so is there any option to get it done with requirement.txt

A:
Torch is not installing and getting failed, and I need that module so is there any option to get it done with requirement.txt:

This seems to be an issue with oryx build releases and that is why deployment patch is failing with an error oryx deployment files doesn't exists and unable to fetch the logs also.
After I've done a workaround,
To avoid this, I added ENABLE_ORYX_BUILD = false in function app->Configuration-> Application Settings (App that will deploy my function) Portal as shown:

After doing it, I've installed torch & torchvision modules with the compatible versions by using:
pip install torch===1.8.0 torchvision===0.9.0 -f https://download.pytorch.org/whl/torch_stable.html

Note: If the provided torch & torch_vision versions are not compatible then it throws an error asking us to check the dependencies to avoid conflicts.

And
pip install -r requirements.txt
requirements.txt:
azure-functions==1.12.0 //Give latest version
requests==2.28.1
torch==1.8.0
torchvision==0.9.0
typing_extensions==4.4.0

Sometimes requirements.txt file will not get properly configured.
To avoid that, Freeze the requirements by using terminal:
pip freeze > requirements.txt
I created an Azure function with python runtime stack, it worked for me and deployment got succeeded:

Triggered successfully after deployment and function app is running:

Verification in Azure Portal:

Version_check:
Python_Version:  Python 3.9.3 (taken)
Upgrade pip to the latest version if prompted.
PyTorch: pytorch.org
Restart the Visual Studio code (ctrl + shift + p) by viewing command palette -> Reload the window and clear cache to avoid module conflicts if needed.


text:
Q: Подключение к почтовому ящику отключённого пользователя при помощи API EWS Здравствуйте!
Подскажите, пожалуйста, как можно подключиться при помощи API EWS к почтовому ящику отключённого пользователя (сервисный почтовый ящик), права на который имеет другой пользователь.
Что надо прикрутить к данному методу?
private static ExchangeService connect(ExchangeService service, string user, string pass, string domain, string server) //User - пользователь имеющий права на ящик, password - его пароль
{
    if (domain != "")
    {
        service.Credentials = new NetworkCredential(user, pass, domain);
    }
    else
    {
        service.Credentials = new NetworkCredential(user, pass);
    }
    service.UseDefaultCredentials = false;
    Uri url = new Uri(@"https://" + server + "/EWS/Exchange.asmx");
    service.Url = url;
    return service;
}

A: Поковырявшись в англоязычном стаковерфлоу нашёл ответ.
FolderId NeedMailbox = new FolderId(WellKnownFolderName.Inbox, "user2@domain.ru"); //user2 - отключённый пользователь
Folder Mailbox = Folder.Bind(service, NeedMailbox);

Дальше уже можно в нём рыться поиском.
var itemView = new ItemView(1000);
var result = Mailbox.FindItems(searchFilter, itemView); //searchFilter - фильтр поиска, можно и без него


text:
Q: Empty UITableView scrolls slowly on iPhone 4 running ios 7 Ok, I'm at a loss.  I have a tableview that works fine in iPhone 5/5S, but can only manage 4 fps on an iPhone 4.  I've tried every trick in the book to optimize the cells (opaque, misaligned frames, no blending, render uilabels into images, static cell heights, etc), but it didn't even move the needle.  Thinking that the root cause could be somewhere else, I decided to strip out all my custom cell code so that cellForRowAtIndexPath: returns an empty (but re-used) UITableViewCell, and even that runs slow...  I've tried profiling the app while scrolling the tableview, but nothing stands out at all.  The only thing that seems suspicious is that if turn on CoreAnimation's Color Hits Green and Misses Red, the status bar will constantly flash between green and red as I scroll the tableview.  This leads me to believe that the status bar is being redrawn every frame (or every couple of frames), but even hiding the status bar didn't improve the fps by much (maybe 4 -> 7).
So.... I'm at a loss.  Anyone out there experience something like this and can point me in the right direction?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:__inboxCell];
    if (! cell)
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:__inboxCell];
    return cell;
}

Here's when I run a time profiler and get around 6 fps:

When I remove the system libraries, it's pretty useless.  If I keep scrolling for a few minutes, the % of Parent for cellForRowAtIndexPath: will greatly exceed that of didFinishLaunchingWithOptions: (which obviously only runs once).


text:
Q: How does melting ice change the mass of the ocean? In the paper, Ocean Bottom Deformation Due To Present-Day Mass Redistribution and Its Impact on Sea Level Observations, the authors state that:

Due to changes in the land ice mass balance and land hydrology, the
  oceans have gained mass over the past decades (Chambers et al., 2016),
  which results in an increase of the total load on the ocean bottom.

and

We use realistic estimates of mass redistribution from ice mass loss and land water storage
The largest differences can be found in the Arctic Ocean: due to the location close to many melt sources, the relative sea level in the Arctic drops, while geocentric sea level rises,

I don't understand how melting ice increases the mass of the ocean? Are they referring to ice normally residing on land, not the ice shelves that rest in the ocean?

A:
Are they referring to ice normally residing on land, not the ice shelves that rest in the ocean?

Yes, glaciers and such. Remember Antarctica, Siberia, Northern Canada, and Greenland aren't floating.


text:
Q: Simplify sum of unnatural conditional functions generated by derivative I try to use Mathematica to evaluate:
$$\frac{\partial}{\partial A_{abc}} \sum_{j=1}^{J}\sum_{k=1}^{K}\log\left(\sum_{l=1}^{L}A_{jkl}B_{jkl}\right)$$
I get:
$$\sum_{j=1}^J \sum_{k=1}^K \frac{\begin{array}&\begin{cases} B(j,k,c) & a-j=0\land b-k=0 \\ 0 & \text{True} \\ \end{cases} \\ \end{array}}{\sum_{l=1}^L A(j,k,l) B(j,k,l)}$$
Instead of
$$\frac{B_{abc}}{\sum _{l=1}^L A_{abl} B_{abl}}$$
How to make Mathematica simplify the sum of conditional functions?
Alternatively, how to avoid the conditional functions in the first place?
The expression is part of a non-linear objective function containing multiple matrices. I am trying to evaluate the gradient and Hessian.
Thanks.
$Assumptions =
  Element[a | b | c, Integers] && 1 <= a <= J && 1 <= b <= K &&
   1 <= c <= L;
expr = Sum[
  Log[Sum[A[j, k, l]*B[j, k, l], {l, 1, L}]], {j, 1, J}, {k, 1, K}]
Simplify[D[expr, A[a, b, c]]]

Update:
Try to simplify Kronecker delta with rules, as suggested by chris.
Simplify[D[expr, A[a, b, c]]]/. Sum[y_ KroneckerDelta[s_, r_],
{s_, 1, p_}] :> (y /. s -> r) /. Sum[y_ KroneckerDelta[s_, r_]
KroneckerDelta[s1_, r1_], {s_, 1, p_}, {s1_, 1, p1_}
] :> (y /. s -> r /. s1 -> r1)

Unfortunately, Mathematica doesn't even give Kronecker delta in this case.

A: Using Mathematica 11.3
expr = Sum[
   Log[Sum[A[j, k, l]*B[j, k, l], {l, 1, L}]], {j, 1, J}, {k, 1, K}];
dexpr = Simplify[D[expr, A[a, b, c]]]

So with a bit of help with the Kroneckers
dexpr /. Sum[
    y_ KroneckerDelta[s_, r_], {s_, 1, p_}] :> (y /. s -> r) /.
 Sum[y_ KroneckerDelta[s_, r_] KroneckerDelta[s1_, r1_], {s_, 1,
    p_}, {s1_, 1, p1_}] :> (y /. s -> r /. s1 -> r1)


text:
Q: Roots of a complex number, solutions I have to find the roots of this complex number.
$z^6-\frac{1-2i}{2-i}=0$
I simplified:
$z=\sqrt[6]{\frac{4}{5}-\frac{3}{5}i}$
Are the solutions these?
$z=\cos{\frac{\arctan{\frac{3}{4}}+2kπ}{6}+i\sin{\frac{\arctan{\frac{3}{4}}+2kπ}{6}}}$
(For k=0,1,2,3,4,5)


text:
Q: Routes with react-router 1.0.0-rc1, express, web pack I am fairly new to react and express, so sorry for the newb questions.
In react-router v013.3, I used the below config and "this.context.router.transitionTo(payload.route);" to switch routes, and it worked fine.
However, in react-router v1.0.0-rc1, I've tried both "this.props.history.pushState(null, payload.route);" as well as "replaceState", but they don't render my route.
I cannot use the  class since I have to switch routes programmatically.
This suggests that I add some code to my express config (please see below): https://github.com/rackt/react-router/blob/master/docs/guides/basics/Histories.md#createbrowserhistory
I also added 'historyApiFallback: true' to my webpack dev server config.
Although via console.log message I see history is receiving the route change request, my requested routes do not render.
Can anyone see what I'm missing?
Thanks!!!
// react-router v013.3
const AppRoutes = (
    <Route path="/" handler={App}>
        <DefaultRoute handler={Home} />
        <Route name="myFieldMapping" handler={MyFieldMapping} />
        <Route name="myValidation" handler={MyValidation} />
    </Route>
);

Router.run(AppRoutes, Router.HashLocation, (Root) => {
    React.render(<Root />, document.getElementById('content'));
});

// react-router v1.0.0-rc1
const myHistory = useBasename(createHistory)({
    basename: '/myApp'
});

let unlisten = myHistory.listen(function (location) {
    console.log('---...---   CALL TO history: ', location.pathname)
});

React.render((
    <Router history={myHistory}>
        <Route path="/" component={App} >
            <IndexRoute component={Home} />
            <Route path="myFieldMapping" component={MyFieldMapping} />
            <Route path="myValidation" component={MyValidation} />
        </Route>
    </Router>
), document.getElementById('content'));

// express config
app.get('/myApp/*', function(request, response){
    response.sendFile(path.resolve(__dirname, publicPath, 'index.html'))
});


text:
Q: Action on group $\operatorname{Ext}^i(\mathcal{L}, \mathcal{M})$ by scalar multiplication Let $X$ be a proper scheme over field $k$ and $\mathcal{L}, \mathcal{M}$ two invertible $\mathcal{O}_X$-modules. Then $Hom_{\mathcal{O}_X}(\mathcal{L}, \mathcal{M}) \cong Hom_{\mathcal{O}_X}(\mathcal{O}_X, \mathcal{M}\otimes  \mathcal{L}^{\vee}) \cong H^0(X, \mathcal{M}\otimes  \mathcal{L}^{\vee})$.
Therefore derived functors coinside as well as we assumed $X$ sufficiently nice:
$\operatorname{Ext}^i(\mathcal{L}, \mathcal{M}) \cong H^i(X, \mathcal{M}\otimes  \mathcal{L}^{\vee})$.
The right hand side has $ H^i(X, \mathcal{M}\otimes  \mathcal{L}^{\vee})$ a natural structure of a $k$ vector space, therefore we can talk about subspaces, multiplication by scalars form $k$ and the whole other basic linear algebra stuff.
On the other hand the Abelian group $\operatorname{Ext}^1(\mathcal{L}, \mathcal{M})$ has an interpretation as set of all extension classes
$$0 \to \mathcal{L} \to ? \to \mathcal{M} \to 0$$
where two classes are considered in  $\operatorname{Ext}^1(\mathcal{L}, \mathcal{M})$ as equal if there exist commutative diagram between the two exact sequences such that the vertical arrows between $\mathcal{L}$ and $\mathcal{M}$ are identities and the middle vertical arrow a isomorphism of $\mathcal{O}_X$-modules.
QUESTION 1: by $\operatorname{Ext}^1(\mathcal{L}, \mathcal{M}) \cong H^1(X, \mathcal{M}\otimes  \mathcal{L}^{\vee})$ the Ext-group is also endowed with structure of a $k$ vector space and I'm asking if there is a nice description how two extension classes in $\operatorname{Ext}^1(\mathcal{L}, \mathcal{M}) $ differ from each other /or related to each other if their corresponding elements in $H^1(X, \mathcal{M}\otimes  \mathcal{L}^{\vee})$ differ by a multiplication by a scalar $a \in k^*$:
in other words if
$$0 \to \mathcal{L} \to E_1 \to \mathcal{M} \to 0$$
and
$$0 \to \mathcal{L} \to E_2 \to \mathcal{M} \to 0$$
are two representers of two extension classes in $\operatorname{Ext}^1(\mathcal{L}, \mathcal{M})$ and the vectors $v_{E_1}$ and $v_{E_2} \in H^1(X, \mathcal{M}\otimes  \mathcal{L}^{\vee})$ lie on the same line $k \cdot v_{E_1}$:
i.e. there exist a $a \in k^*$ with $v_{E_2}=a \cdot v_{E_1}$, is there a meaningful contruction between $E_1$ and $E_2$ in $\operatorname{Ext}^1(\mathcal{L}, \mathcal{M})$ relating them to each other in dependence of $a$?
In other words how the two exact sequences of $E_1$ and $E_2$ are in this case related to each other in sophisticated way reflecting that their corresponding vectors in $v_{E_1}$ and $v_{E_2} \in H^1(X, \mathcal{M}\otimes  \mathcal{L}^{\vee})$ are only differ by a scalar.
Or more generally, how the action of $k$ on by scalar multiplication
$H^1(X, \mathcal{M}\otimes  \mathcal{L}^{\vee})$
can be transfered to an action on
the exact sequences representing extension classes
from $\operatorname{Ext}^1(\mathcal{L}, \mathcal{M})$?
QUESTION 2:
How to see that the $0$  in
$\operatorname{Ext}^1(\mathcal{L}, \mathcal{M})$
(the neutral element of this
Abelian group)
corresponds to the class of splitting extension
$$0 \to \mathcal{L} \to \mathcal{L} \oplus \mathcal{M}
 \to \mathcal{M} \to 0$$
I often saw in comments/ remarks on this issue that
people just say 'that's because the two objects are
canonical' from both viewpoints: in a vector space
as well extension classes.
But I nowhere found a "clean" constructive argument
why this identification is true diving in explicit
machinery how thegroup elements of the Ext^1
group are identified with extension classes.

A: Remark. Exact sequence $0 \to L \to E \to M \to 0$ corresponds to $Ext^1(M,L)$, not to $Ext^1(L,M)$.
Q1. $a \in k^\times$ acts on $Ext^1(L,M)$ via pullback along $a:L \to L$ or via pushout along $a: M \to M$.
Q2. There are two options: either one can check that the split sequence is the neutral element for the addition, or that in the long exact sequence
$$
0 \to Hom(L,M) \to Hom(L,L \oplus M) \to Hom(L,L) \to Ext^1(L,M)
$$
the element $1_L \in Hom(L,L)$ goes to 0.

A: That is we start with an arbitrary extension $0 \to M \to e_2 \to L \to 0$ represented by the class of the image $\Phi_{e_2}:=\delta(id_L)$ with respect the delta-map in lower row in second diagram below and it's pullback extension $e_2$ in the upper row. Now we want determine that the extension $\overline{e_1}$ is represented by multiplication $a \cdot \Phi_{e_2} =: \Phi_{e_1}$.
We apply $Hom(L,-)$ to diagram
$$
\require{AMScd}
\begin{CD}
0 @>  >> M @>  >> e_1 @>a^{-1} >>  L @> >> 0\\
@VVV  @VVV  @VVV  @VV\cdot{a}V \\
0 @>  >> M @>  >> e_2 @> >>  L @> >> 0
\end{CD}
$$
and obtain
$$
\require{AMScd}
\begin{CD}
Hom(L, E) @>  >> Hom(L,L) @>\delta  >> Ext(L,M) @> >>  \\
@VVV  @VV\cdot{a}V  @VVV  \\
Hom(L,\overline{E}) @>  >> Hom(L,L) @>\delta  >> Ext(L,M) @> >>
\end{CD}
$$
That's a diagram of $k$-vector spaces. As you explaned in the answer the extension $e_1$ is forced to be the pullback of $e_2$: i.e. $e_1= a^*e_2$. $k$-linearity and commutativity of the maps imply $a \cdot \Phi_{e_2}=a \cdot \delta(id_L) = \delta(a \cdot id_L) = \Phi_{e_1}$. So $e_1=a e_2$. Is this the correct result of the $k^*$ action by scalar multiplication on $Ext(L,M)$? Or do I have somewhere implemented your hints on my question 1) in wrong way?


text:
Q: Display element not found and add it to the list in angular2 In my Heroes app, I have an input text that checks the service if the hero is present or not. If present, it displays it in a drop down.
What I want is to display the hero name if it is not present and also add a button to add the hero to the the array.
My hero-search.component.html

Hero Search

  <input #searchBox id="search-box" (keyup)="search(searchBox.value)" />

 // this div is not working
      no element found

      {{hero.name}}

my hero-search.component.ts
import { Component, OnInit } from '@angular/core';
import { Router }            from '@angular/router';
import { Observable }        from 'rxjs/Observable';
import { Subject }           from 'rxjs/Subject';
import { HeroSearchService } from './hero-search.service';
import { Hero } from './hero';
@Component({
  selector: 'hero-search',
  templateUrl: 'hero-search.component.html',
  styleUrls: [ 'hero-search.component.css' ],
})
export class HeroSearchComponent implements OnInit {
  heroes: Observable<Hero[]>;
  private searchTerms = new Subject<string>();
  constructor(
    private heroSearchService: HeroSearchService,
    private router: Router) {}
  // Push a search term into the observable stream.
  search(term: string): void {
    this.searchTerms.next(term);
    console.log("Heroes"+this.heroes);
  }
  ngOnInit(): void {

    this.heroes = this.searchTerms
      .debounceTime(300)        // wait for 300ms pause in events
      .distinctUntilChanged()   // ignore if next search term is same as previous
      .switchMap(term => term   // switch to new observable each time
        // return the http search observable
        ? this.heroSearchService.search(term)
        // or the observable of empty heroes if no search term
        : Observable.of<Hero[]>([]))
      .catch(error => {
        // TODO: real error handling
        console.log(error);
        return Observable.of<Hero[]>([]);
      });
  }
  gotoDetail(hero: Hero): void {
    let link = ['/detail', hero.id];
    this.router.navigate(link);
  }
}

The *ngIf is not working as well as adding a button to add the hero back to array.
The div is always there in the page no matter the heroes array is populated.
Please help. I am new to angular 2.

A: heroes is Ovservable<Hero[]> and as I see you want to display the div in question only when the array is empty. So your condition should be *ngIf="(heroes | async)?.length == 0". In the current implementation the div always shows up because *ngIf evaluates to true  as heroes has a value, i.e.  it's not undefined.


text:
Q: Can't retrieve values between attributes, Scraping I'm trying to retrieve a value from a site yet I get no value between the attributes.(except for id=Avg Played). I've tried using both Scrapy and Beautiful Soup to no avail!
Here's my BeautifulSoup/Urllib2 code:
import urllib2
from bs4 import BeautifulSoup

site = "http://www.lolking.net/champions/singed?#/overview"
request= urllib2.Request(site, headers={'User-Agent':'Chrome/44.0.2403.107'})
response = urllib2.urlopen(request)
html = response.read()

soup = BeautifulSoup(html, 'lxml')

champ_stats = soup.findAll('div', attrs={"class" : "champ-stats"})

champ_stats2 = soup.findAll('strong', attrs={"class" : "champ-stats"})

for x in champ_stats:
    print x.text, x

print '\n now showing more specifically: \n'
for x in champ_stats2:
    print x.text, x

I've also made a scraper using Scrapy(got the same results):
import scrapy

class StatsSpider(scrapy.Spider):
    name = "stat_spider"
    start_urls = ["http://www.lolking.net/champions/singed?#/overview"]
    def parse(self, response):
        selector = '.champ-stats'
        for stats in response.css(selector):
            stat_selector = 'strong ::text'
            name_selector = 'span ::text'
            yield {
                'stat': stats.css(stat_selector).extract_first(),
                'name' : stats.css(name_selector).extract_first()
            }

This is what the html looks like in the browser(what I want to retrieve):
html = """

                48.3%
                Win Rate

                0.8%
                Popularity

                0.5%
                Ban Rate

                10.2
                Avg Played

 """

I'm guessing the site has a method for preventing people from scraping this data? If so, is there a way around that?

A: You'd be better off using the requests module, rather than urllib2; it's just simpler to use. I should mention though that BeautifulSoup might not be enough to fully scrape this page depending on what you want from it. You might need to resort to selenium or scrapy.
>>> import requests
>>> page = requests.get('http://www.lolking.net/champions/singed?#/overview').content
>>> import bs4
>>> soup = bs4.BeautifulSoup(page, 'lxml')
>>> champ_stats = soup.findAll('div', attrs={"class" : "champ-stats"})
>>> for x in champ_stats:
...     x.text, x
...
('\n%\nWin Rate\n',

%
Win Rate

)
('\n%\nPopularity\n',

%
Popularity

)
('\n%\nBan Rate\n',

%
Ban Rate

)
('\n10.2\nAvg Played\n',

10.2
Avg Played

)

Edit:
I'm not sure this is entirely apposite. If I understand you correctly, those values can be scraped using selenium.
>>> from selenium import webdriver
>>> driver = webdriver.Chrome()
>>> driver.get('http://www.lolking.net/champions/singed?#/overview')
>>> for item in driver.find_elements_by_xpath('.//div[@class="champ-stats"]/strong'):
...     item.text
...
'48.4'
'0.8'
'0.4'
'10.2'


text:
Q: Is DotNetopenAuth good to get user credentials? I want to ccreate a website that reads one's Gmails headers.
If I use dotNetopenAuth to authenticate -
will I eventually get the user user and password for my applications' needs?
It seems that the answer is no- for security reasons that's why OpenId is for.
But then, I know website that do so. How?

A: If you use protocols like OpenID or OAuth, you will not have access to the user's userid nor password.
Instead you will receive a unique identifier for the user, which does nothing more than tell you that the trusted provider has validated that the user logged into their provider's account successfully. It is your job to match that unique identifier with your application's user record.
Depending on the provider you use for authentication (Google, Yahoo, MyOpenId, Twitter, etc.), you may request additional information such as the user's email address and name, but you are not guaranteed to get even that.
Under no circumstances will you ever get to see their password, though. If you want that, then you will have to write your application to use your own authentication provider, like the built-in ASP.NET Membership provider.

A: The point of OpenID is as you say: delegate authentication to another so that you don't have to deal with the password (if there even is one).
Sites that have the user log in with Google, and then gain access to that user's data at Google aren't just using OpenID.  They're also using another authorization protocol.  Google supports a proprietary one and a more common standard one called OAuth.  OpenID and OAuth can be combined such that the user visits Google just once to log in, and then your site gains the access it needs (if the user approves).
If you take a look at the DotNetOpenAuth sample OpenIdRelyingPartyWebForms\loginPlusOAuth.aspx you'll see an example of the user logging into Google, and by doing that giving the site the ability to download the user's Google address book.  This can be easily changed to include permissions to do other things (like read email headers) but you'll need to read Google documentation (GData) to learn what scope to use and APIs to call to obtain this information.
Under no circumstances should you be collecting the user's Google password yourself.  I suspect that would be a violation of the Google terms of service anyway.


text:
Q: Why does casting PSCustomObjects to custom type with DateTime in PowerShell fails? I would like to cast PSCustomObjects to custom types. Casting does work for simple types, but it doesn't work if I use e.g. DateTime within the type definition. Casting from a HashTable to custom type does work. Why does casting from PSCustomObject does not work as expected?
Here's an example:
Add-Type @"
using System;
public struct Test {
    public DateTime date;
}
"@

$Properties = @{date=(Get-Date)}
$CustomObject = New-Object -TypeName PSCustomObject -Property $Properties

# Returns correct date:
$TestObjectCastFromProperties = [Test]$Properties
$TestObjectCastFromProperties
$TestObjectCastFromProperties.GetType()

# Returns wrong date
$TestObjectCastFromCustomObject = [Test]$CustomObject
$TestObjectCastFromCustomObject
$TestObjectCastFromCustomObject.GetType()

A: I can't tell you why this doesn't work. Even the explicit conversion fails:
[System.Management.Automation.LanguagePrimitives]::ConvertPSObjectToType(
    $CustomObject, [test], $true, [cultureinfo]::InvariantCulture, $false)

Output:
date
----
01.01.0001 00:00:00

However, you could use a handcrafted function to convert a PSCustomObject to a Type:
function Cast-CustomObject
{
    Param
    (
        [PsCustomObject]$obj,
        [Type]$castType
    )
    $properties = ($obj.PSObject.Properties | % { @{$_.Name = $_.Value}})
    [System.Management.Automation.LanguagePrimitives]::ConvertTo($properties, $castType)
}

Usage:
Cast-CustomObject -obj $CustomObject -castType ([Test])

Output:
date
----
06.07.2016 08:52:01


text:
Q: How to get return value to eclipse function from java script function which get data from ajax request using SWT browser? I have tried below....
I have this in eclipse : I have a button in java which triggers this function in javascript
    Object status =  browserCtrl.evaluate("return atm.java.webToJavaPerspective()");

Then I have this function in javascript
function atm.java.webToJavaPerspective(){
  returnData = {};
  //ajaxRequest = some ajaxRequest variable
  $.when(ajaxRequest).then(function( data, textStatus, jqXHR ) {
    //modify the data
    returnData.textStatus = textStatus;

    //this return statement should return data to java function
    return returnData;
  });

//this will return empty object
return returnData;
}

But I am always getting empty object. Because the ajax request takes few seconds, and my javascript function returns the empty object insted waiting for request to return data.
How can I achieve this..?

A: When dealing with Ajax calls, you'll have to call a so-called BrowserFuntion from your Javascript code when you have the result.
Here's an example of how to define a BrowserFunction and how to call it from Javascript:
public static void main(String[] args)
{
    final Display display = new Display();
    final Shell shell = new Shell(display);
    shell.setLayout(new FillLayout());

    Browser browser = new Browser(shell, SWT.NONE);
    browser.setText("Click me!");

    new BrowserFunction(browser, "theJavaFunction")
    {
        @Override
        public Object function(Object[] objects)
        {
            System.out.println("Call from Javascript");

            return null;
        }
    };

    shell.pack();
    shell.open();

    while (!shell.isDisposed())
    {
        if (!display.readAndDispatch())
        {
            display.sleep();
        }
    }
}

Furthermore, an excellent tutorial about Browser from Vogella here:
http://blog.vogella.com/2009/12/21/javascript-swt/


text:
Q: How to change font in Framebuffer in Linux using C? I have a graphic application under development but I am unable to change the font in that. If anyone knows about any page or link explaining the method to change fonts in framebuffer on linux, it will be very helpful.

A: Linux frame buffer is a memory location which is mapped to your display area. What ever you write in to this memory area that reflects on the display. Coming to your question, For frame buffer there is nothing like font. every thing is a binary data. For making your own font, first you need to get hexadecimal values corresponding to your characters then write that data into frame buffer at required location. Or you can use some api like X11, MiniGUI or Qt, which provides simple way to write data into frame buffer devices.


text:
Q: SQL where, case between or equal date vs datetime I'm trying to figure out if there are too many moving pieces in this query or not. I need check that if a date is on a Friday, the corresponding value is from the following Monday. Any other day, it is the next day. I can get the 'next day' part to work with no problems, but the Friday to Monday piece fails. Making it a little tougher is that a.Change_Date is in Date format and the b.Load_Date is in DateTime format.
SELECT *
  FROM a, b
  where a.account_number = b.account_Number
  and a.Change_date
  case  when datepart(dw, a.Change_date) = 5
            then BETWEEN (CAST(DATEADD(dd, -4, b.Load_Date) AS DATE)) AND (CAST(DATEADD(dd, -3, b.Load_Date) AS DATE))
        else
            = CAST(b.Load_Date) AS DATE) and CAST(DATEADD(dd, -1, b.Load_Date) AS DATE)
    end
  and a.Account_Number in
(XXXXX.....)

Any thoughts on how to make this happen appreciated. This should return all rows where the account_numbers exist in the last and statement. I've looked at this too long today and not made enough progress.

A: I don't know your full schema, but here is a quick example with some local variables.
declare @somedate datetime = '2016-04-15 15:17:00.497'--getdate()
declare @nextDate datetime

select @nextDate = case when datepart(dw,@somedate)=6 then @somedate+3 else @somedate+1 end

select @nextDate NextDate


text:
Q: Url not open in android webview how can i open this url in web view in android
https://web150.secure-secure.co.uk/ftpeditor.net/core/homepage.php

A: try to use the chrome client:
    vw = new MyWebView(this);
    vw.setWebChromeClient(new WebChromeClient() {
        public void onProgressChanged(WebView view, int progress)
        {
            activity.setTitle("Loading...");
            activity.setProgress(progress * 100);

            if(progress == 100)
                activity.setTitle(R.string.app_name);
        }
    });
    vw.setWebViewClient(new WebViewClient() {
        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
        {
            // Handle the error
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url)
        {
            view.loadUrl(url);
            return true;
        }
    });

A: this is the completed code
package com.myapp;

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;

public class MainActivity extends Activity {
WebView webview;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    webview = (WebView) findViewById(R.id.webview);

    webview.loadUrl("https://web150.secure-secure.co.uk/ftpeditor.net/core/homepage.php");

}
}


text:
Q: How can I split text on commas not within double quotes, while keeping the quotes? So I'm trying to split a string in javacript, something that looks like this:
"foo","super,foo"

Now, if I use .split(",") it will turn the string into an array containing [0]"foo" [1]"super [2]foo"
however, I only want to split a comma that is between quotes, and if I use .split('","'), it will turn into [0]"foo [1]super,foo"
Is there a way I can split an element expressing delimiters, but have it keep certain delimiters WITHOUT having to write code to concatenate a value back onto the string?
EDIT:
I'm looking to get [0]"foo",[1]"super,foo" as my result. Essentially, the way I need to edit certain data, I need what is in [0] to never get changed, but the contents of [1] will get changed depending on what it contains. It will get concatenated back to look like "foo", "I WAS CHANGED" or it will indeed stay the same if the contents of [1] where not something that required a change

A: Try this:
'"foo","super,foo"'.replace('","', '"",""').split('","');

A: For the sake of discussion and benefit of everyone finding this page is search of help, here is a more flexible solution:
var text = '"foo","super,foo"';
console.log(text.match(/"[^"]+"/g));

outputs
['"foo"', '"super,foo"']

This works by passing the 'g' (global) flag to the RegExp instance causing match to return an array of all occurrences of /"[^"]"/ which catches "foo,bar", "foo", and even "['foo', 'bar']" ("["foo", "bar"]" returns [""["", "", "", ""]""].)


text:
Q: Python - Plotting several learning curves with scikit-learn on the same figure I'm writing this program to plot learning curves of SVM and NB on differents datasets,this is the function that plot the learning curves of the passed dataset:
import numpy as np
import matplotlib.pyplot as plt
from sklearn import cross_validation
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC
from sklearn.datasets import load_digits
from sklearn.datasets import fetch_mldata
from sklearn.learning_curve import learning_curve

def plot_learning_curve(plotter, X, y, ylim=None, cv=None,
                    n_jobs=1, train_sizes=np.linspace(.1, 1.0, 5)):
    if ylim is not None:
        plt.ylim(*ylim)

estimator1 = GaussianNB()
estimator2 = SVC(kernel='linear')
train_sizes1, train_scores1, test_scores1 = learning_curve(
    estimator1, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes)
train_sizes2, train_scores2, test_scores2 = learning_curve(
    estimator2, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes)
test_scores_mean1 = np.mean(test_scores1, axis=1)
test_scores_mean2 = np.mean(test_scores2, axis=1)

plotter.plot(train_sizes2, test_scores_mean2, 'x-', color="b", label="linear SVM")
plotter.plot(train_sizes1, test_scores_mean1, 'x-', color="r",
             label="NB")

plt.legend(loc="best")
return plotter

This is the function call on 2 different datasets:
plt.figure()
plt.xlabel("Training examples")
plt.ylabel("Score")
plt.title("Comparison between NB(Naive Bayes) and SVM(Support Vector Machine)")
labels = ['sonar', 'iris']
plt.grid()
sonar = fetch_mldata('sonar', target_name='target', data_name='data',        transpose_data=True)
iris = fetch_mldata('iris', target_name='target', data_name='data', transpose_data=True)
X, y = sonar.data, sonar.target
x1, y1 = iris.data, iris.target

cv = cross_validation.ShuffleSplit(sonar.data.shape[0], n_iter=10,
                               test_size=0.2, random_state=0)

ax1 = plt.subplot(211)
plot_learning_curve(ax1, X, y, ylim=(0.5, 1.01), cv=cv, n_jobs=1)

cv = cross_validation.ShuffleSplit(iris.data.shape[0], n_iter=10,
                               test_size=0.2, random_state=0)
ax2 = plt.subplot(212, sharex=ax1)
plot_learning_curve(ax2, x1, y1, ylim=(0.5, 1.01), cv=cv, n_jobs=1)

plt.show()

The plotting function work pretty well, the problem is that the program plots the graphs of the two calls in the same image.Now i want to run it on several datasets and it should show a grind of images , one for each iteration of the function , in the same windows.
I really don't understand how subplot or add_subplot works, so if someone could help me out i would be very grateful.


text:
Q: 80's(?) time travel trilogy with a one-armed war veteran dragged to the future with World War III and telepath wars The main character was a war veteran who had lost an arm and used a sword to strengthen his other arm.  He is caught in a time probe from the far future and accidentally dragged forward (in the first book).  This future has already had WWIII and a couple of telepath wars.
He meets and falls in love with one of the scientists' daughters (there are two). The future people produce or clone a new arm and hand for our main character. I think there are war concerns, as I remember there being "eternal" highways that were indestructable and being used by both sides to mobilize. I don't remember all the plot twists.
I think there were three books, but it may have been four. I'm pretty sure I first read this back in the early 80's.

A: It could be "With Fate Conspire" by Mike Shupp,  its the first book of the "Destiny Makers" series. There's 5 books in total, it's been a long time since I read them but what you've described sounds familiar.
From FantasticFiction:

Vietnam veteran and MIT student Tim Harper uses his new invention, a time machine, to travel ninety thousand years into the future, where he is captured by Alghera clansmen who seek to use his discovery to change the course of history.

*

*With Fate Conspire (1985)

*Morning of Creation (1986)

*Soldier of Another Fortune (1988)

*Death's Gray Land (1991)

*The Last Reckoning (1991)


text:
Q: Weird results when I iterate through string with "ñ" char I have a string of characters and one of those possible characters is the letter "ñ". My problem is, my string seems to behave in a weird way when I try to modify it or iterate through the string. For example if I have the code:
std::ifstream infile (argv[1]);
std::string texto_crudo((std::istreambuf_iterator<char>(infile)), std::istreambuf_iterator<char>());
for (int i = 0; i<texto_crudo.length(); i++){
    if(es_enie(texto_crudo[i])) {
        texto_crudo[i] = '$';
    }
}

Where es_enie returns true if texto_crudo[i] = ñ. It seems like in the cell where ñ is located it behaves as if it has two values instead of one.

A: I managed to find a solution to my exact problem. As Some programmer dude commented, it was because my text was in UTF-8 and I needed to convert it to iso-8859-1 in order to be able to use "ñ" correctly.
Convert string from UTF-8 to ISO-8859-1