2 Dimensional Array Pointer

Question: I am following an example to implement threads in C: http://ramcdougal.com/threads.html.
This example is using a 1-dimensional array. I need a dynamic 2 dimensional array.
What would it look like if in the main() it was int **array instead of int array[ARRAYSIZE]?
My problem is how to pass a pointer to a 2-dimensional array to the struct.
The idea is, that I have a big array, and each thread should only fill a certain area of that array.
Thanks a lot !
Here's the code from the example:
struct ThreadData {

    int start, stop;
    int* array;

};

void* squarer(struct ThreadData* td) {

    struct ThreadData* data=(struct ThreadData*) td;
    int start=data->start;
    int stop=data->stop;
    int* array=data->array;
    int i;

    for (i=start; i<stop; i++) {
        array[i]=i*i;
    }

    return NULL;
}

int main(void) {

    int array[ARRAYSIZE];
    pthread_t thread[NUMTHREADS];
    struct ThreadData data[NUMTHREADS];
    int i;

    int tasksPerThread=(ARRAYSIZE+NUMTHREADS-1)/NUMTHREADS;

    for (i=0; i<NUMTHREADS; i++) {
        data[i].start=i*tasksPerThread;
        data[i].stop=(i+1)*tasksPerThread;
        data[i].array=array;
    }
    /* the last thread must not go past the end of the array */
    data[NUMTHREADS-1].stop=ARRAYSIZE;

    /* Launch Threads */
    for (i=0; i<NUMTHREADS; i++) {
        pthread_create(&thread[i], NULL, squarer, &data[i]);
    }

    /* Wait for Threads to Finish */
    for (i=0; i<NUMTHREADS; i++) {
        pthread_join(thread[i], NULL);
    }

    /* Display Result */
    for (i=0; i<ARRAYSIZE; i++) {
        printf("%d ", array[i]);
    }
    printf("\n");

    return 0;
}

Answer: to dynamically allocate 2-dimensional array use something like this:
int** array = malloc(sizeof(int*)*ARRAYSIZE);

Here you allocate an array of pointers to int, now you should allocate memory for each pointer:
for(int i = 0;i<ARRAYSIZE;i++)
    array[i] = malloc(sizeof(int)*INNER_ARRAYSIZE);

And now fill every entry with your actual data:
for(int i = 0;i<ARRAYSIZE;i++)
    for(int j = 0;j<INNER_ARRAYSIZE;j++)
        array[i][j]=(i+j);//just for example

And update your ThreadData struct to use two-dimensional arrays:
struct ThreadData {

int start, stop;
int** twoDimArray;//note one more * here

};
And just pass pointer here:
struct ThreadData data;
data.twoDimArray = array;
data.twoDimArray[0][0] = data.twoDimArray[0][0]*data.twoDimArray[0][0]; //access element at 0,0 and square it

Comment: doing so make all data non contiguous, thus giving you poor cache performance. better use an Iliffe vector strategy.
Comment: topic starter is trying to follow simple tutorials, let's just keep all the scary C things away for now :)
Comment: it's not a scary C thing, it's basic computer architecture.
Answer: Think of it this way:
When working with a one dimensional array, start and stop are one dimensional vectors representing coordinates in 1-D space (And a 1-D vector can be represented with an integer, which is what the original code uses.)
So in a 2-D array, start and stop ought to be 2-D vectors:
struct ThreadData
{
  int start[2], stop[2];
  int **array;
}

Then, you split rectangular blocks amongst the threads. And each thread gets the position of the top left corner of its block in start, and the position of the bottom right corner of its block in stop.

Remember that the blocks, being rectangular, can be tall strips (1 column per thread), or long (one row per thread), or square, or anywhere in between. You have to decide which shape works faster, by benchmarking.
In a sense, tasksPerThread also has two dimensions. With the actual number of tasks becoming tasksPerThread[0] * tasksPerThread[1].

2 Dimensional Array Pointer


Removing quotation marks and comma from array of tuples

Question: I created an array of tuples from a column in a dataframe as such:
 subset = df[['sRGB']]
 tuples = [tuple(x) for x in subset.values]

Although, in the data frame, the values in the 'sRGB' column are 3 consecutive numbers separated by a comma, the array of tuples comes out as the following with additional quotation marks and a comma:

I am looking for a way to remove the quotation marks and the unnecessary comma inside each tuple, so that the array of tuples looks like this:
[(45,21, 31), (54, 14, 33)...]
I would greatly appreciate any guidance as I have already spent 2 hours on this!
Thanks in advance!
Answer: Try this:
tuples = [tuple([int(y) for y in x[0].split(",")]) for x in tuples]

Answer: You can do:
tuples = [tuple( map(int, val[0].split(','))) for val in tuples]


Server with scalability for real-time collaboration and editing

Question: I am here, to ask for absolute input. I have setup a local Apache Server with PHP 7.2 (currently), I am aware newer PHP exists. I know PHP and Python, I also know Node.js (server/back-end).
With Node.js, I can get most of the packages through npm command line. I been reading, Node.js vs. PHP and it all depends on what you are going to develop. In addition, I know that Golang programming can also be used in the cloud. Now I want to be able to utilize the full power of cloud computing capacity.
Requirements: architecture that is scalable, modular, maintainable, secure, and reliable. Fault tolerance.
Now the site must be able to handle multiple users operating in real-time, chatting, editing content in real-time. I know that Html5 provides all the following APIs: WebRTC, WebSocket, Local Storage, and a number of options. However, I cannot decide if I shall go with: PHP, Golang, or just Node.js with Vue.js, skipping React.js and Angular.js.
Any tips, suggestions based on other's experience from doing this, is fully welcome. The web servers will be running Linux/Ubuntu.
Answer: Given the requirements you outlined, it sounds like Node.js may be the best choice for building your real-time collaboration and editing application. Node.js is well-suited for building real-time web applications that require bidirectional communication between the client and server. It has a large ecosystem of packages and tools available via npm, making it easy to build scalable and maintainable applications.
In terms of front-end frameworks, Vue.js is a good choice. It is a progressive JavaScript framework that is lightweight and easy to use. It is well-suited for building real-time applications and has a large and active community.
Comment: Hi Salim, thanks for your response. I plan on using the MySQL database, I seen that Node.js can handle this. What other arguments can you share, for not using PHP and/or Golang?


How to obtain the Frobenius series solution to ODE when one term is multiplied by $x$ to fractional power?

Question: This is an ode from an old book, which I am stuck solving, since there is a term in front of $y''$ which does not have a power series. Here is the problem
$$
    x^{\frac{3}{2}} y'' + y = 0
$$
Expansion is at $x=0$. The book shows the solution using standard form, but I do not know how they obtained it. Here is a screen shot of the book with the solution it gives

I set $a=1$ for simplicity.     Here is my attempt
Solve
$$
x^{\frac{3}{2}}y^{\prime\prime}+y=0
$$
Since $x=0$ is regular singular point, then Frobenius power series must be
used. Let the solution be represented as Frobenius power series of the form
$$
y=\sum_{n=0}^{\infty}a_{n}x^{n+r}
$$
Then
\begin{align*}
y^{\prime} &  =\sum_{n=0}^{\infty}\left(  n+r\right)  a_{n}x^{n+r-1}\\
y^{\prime\prime} &  =\sum_{n=0}^{\infty}\left(  n+r\right)  \left(
n+r-1\right)  a_{n}x^{n+r-2}
\end{align*}
Substituting the above back into the ode gives
\begin{align}
x^{\frac{3}{2}}\left(  \sum_{n=0}^{\infty}\left(  n+r\right)  \left(
n+r-1\right)  a_{n}x^{n+r-2}\right)  +\left(  \sum_{n=0}^{\infty}a_{n}
x^{n+r}\right)   &  =0\nonumber\\
\sum_{n=0}^{\infty}\left(  n+r\right)  \left(  n+r-1\right)  a_{n}
x^{n+r-\frac{1}{2}}+\sum_{n=0}^{\infty}a_{n}x^{n+r} &  =0\tag{1A}
\end{align}
To make all powers on $x$ the same, the above becomes
\begin{equation}
\sum_{n=0}^{\infty}\left(  n+r\right)  \left(  n+r-1\right)  a_{n}
x^{n+r-\frac{1}{2}}+\sum_{n=\frac{1}{2}}^{\infty}a_{n-\frac{1}{2}}
x^{n+r-\frac{1}{2}}=0\tag{1B}
\end{equation}
The indicial equation is obtained for $n=0$. From the above this gives
$r(r-1)=0$. Hence the roots are $r_{1}=1$ and $r_{2}=0$. The roots differ by
integer. Therefore we can construct two linearly independent solutions
\begin{align*}
y_{1}\left(  x\right)   &  =x^{r_{1}}\sum_{n=0}^{\infty}a_{n}x^{n}\\
y_{2}\left(  x\right)   &  =Cy_{1}\left(  x\right)  \ln\left(  x\right)
+x^{r_{2}}\left(  \sum_{n=0}^{\infty}b_{n}x^{n}\right)
\end{align*}
Or
\begin{align*}
y_{1}\left(  x\right)   &  =x\sum_{n=0}^{\infty}a_{n}x^{n}\\
y_{2}\left(  x\right)   &  =Cy_{1}\left(  x\right)  \ln\left(  x\right)
+\sum_{n=0}^{\infty}b_{n}x^{n}
\end{align*}
Or
\begin{align*}
y_{1}\left(  x\right)   &  =\sum_{n=0}^{\infty}a_{n}x^{n+1}\\
y_{2}\left(  x\right)   &  =Cy_{1}\left(  x\right)  \ln\left(  x\right)
+\sum_{n=0}^{\infty}b_{n}x^{n}
\end{align*}
Where $C$ above can be zero.  Let us find $y_{1}\left(  x\right)  $ first.
From Eq(1B), where now $r=r_{1}=1$
$$
\sum_{n=0}^{\infty}\left(  n+1\right)  \left(  n\right)  a_{n}x^{n+\frac{1}%
{2}}+\sum_{n=\frac{1}{2}}^{\infty}a_{n-\frac{1}{2}}x^{n+\frac{1}{2}}=0
$$
$n=0$ is skipped since used to find the roots. Let $a_{0}=1$. But how to find
$a_{1},a_{2},\cdots$ since the index $n$ are not integers?
The whole problem starts because $x^\frac{3}{2}$ does not have power series expansion. This cause the index to become fractional. So I have no idea how to handle this case.
Maple claims there is no series solution to this ode
<code>ode:=x^(3/2)*diff(y(x),x$2)+y(x)=0
infolevel[dsolve]:=3;
dsolve(ode,y(x),series)
dsolve/series/ordinary: vector Y of initial conditions at x0 = 0 [y(0) (D(y))(0)]
dsolve/series/ordinary: trying Newton iteration
dsolve/series/direct: trying direct subs
dsolve/series/froben: trying method of Frobenius
dsolve/SERIES: Warning: no solutions found
</code>
Then how did the book obtain one? How to handle such case?
Answer: As you have a fractional power in the equation, you have to assume that the series expansion also needs a fractional power of $x$ as the basis. So try
$$
y(x)=\sum a_nx^{r+sn}\\
y'(x)=\sum (r+sn)a_nx^{r-1+sn}
\\
y''(x)=\sum (r+sn)(r-1+sn)a_nx^{r-2+sn}
\\
x^{3/2}y''(x)+y(x)=\sum (r+sn)(r-1+sn)a_nx^{r-1/2+sn}+\sum a_nx^{r+sn}
$$
To get a solvable system, the second term of the first series has to be compatible with the first term of the second, which gives $s=\frac12$. The indicial equation for the lowest power is then $0=r(r-1)$, and for $r=1$ one gets the recursion for the coefficients
$$
a_{n+1}=-\frac{a_n}{(n+1)/2(1+(n+1)/2)}=-\frac{4a_n}{(n+1)(n+3)}.
$$
This directly gives the $A$ basis solution in the cited book.
Comment: Thanks. But you are using new form I have not seen before. Normally it is $y=\sum_{n=0}^{\infty}a_{n}x^{n+r}$  but now you have $y=\sum_{n=0}^{\infty}a_{n}x^{s\,n+r}$ so you added a new term $s$. Is this because the original ode had fractional powers on $x$? I have never seen this before. i.e. adding an $s$ times $n$ there. Do you know of examples where this notation is used?  I need to look more into your solution also.  I also do not see how you arrived at `the second term of the first series has to be compatible with the first term of the second`.  But will try to figure it out.
Comment: You could also first insert $y(x)=u(x^s)$ with the intent to find a normal Frobenius series for $u$. Then you get that $1/2$ has to be an integer multiple of $s$, so in the simplest case $s=1/2$.
Comment: sorry, I am not following your method. Lets say $s=\frac{1}{2}$. This is not the issue for me now. Assume it is given OK. But before doing anything, we need to make all powers on $x$ the same in all the sums. Only after that, we find $r$ and next find the recursive equation. I do not see anywhere how to made all powers of $x$ the same in all sums. Because this is the problem for me. When making all the powers the same, then the sum now start from $n=\frac{1}{2}$ which makes no sense.   This is what I did in Eq(1B).  Do you know reference that solves such a problem with fractional powers? Thank
Comment: I'll try to find a better formulation. It is not that the coefficient system becomes unsolvable. Choosing $s$ as some part of $1/2$, from the exponent equality $r-1/2+n_0s=r$, introduces sub-sequences of zero coefficients where the non-zero parts corresponds to the $n_0=1$, $s=1/2$ case.


If you have ten boxes and each one has a 10% chance to contain a prize what's the probability to win at least one prize

Question: This question has been haunting me for quite some time now. I would love to learn the answer.
The Question again:
If you have ten boxes and each one has a 10% chance to contain a prize what's the probability to win at least one prize
Comment: Fun fact.  About 65 percent.  If the prob is 1/n and you do it n times the probability will get closer and close to about 62% the larger n is.  At n = 10 the problem is just over 65%
Answer: The probability of winning at least one prize is $1$ minus the probability of winning no prizes.
Assuming you open all the boxes, the probability that none of the boxes contain a prize is $(0.9)^{10}$, so therefore the probability of winning at least one prize is $1 - (0.9)^{10}$.


Create a redirect from the attachments directory to index.php with the slug as a url parameter

Question: When a user directly accesses the uploads directory I need to be able to redirect the user to index.php?file=$1. For example:
someurl.com/uploads/sites/17/2018/10/image.jpg

to
someurl.com/index.php?file=/sites/17/2018/10/image.jpg

From this url I will be able to check against the current logged in users meta.
Comment: Do you want to prevent direct access to the entire uploads directory or just images (or other files)?
Comment: @Jamie_D I think the rule needs to be like: have we directly visited a file grab the part after the word upload and add it to the query string. Once there I can run a function to check user permissions.
Comment: Updated answer for accessing user info and file parmeters ...
Answer: Edited from this answer :
RewriteCond %{REQUEST_URI} \.(pdf|zip|jpeg|jpg|png)$ [NC]
RewriteCond %{REQUEST_FILENAME} -s
RewriteRule ^wp-content/uploads/(.*)$ index.php?file=$1 [QSA,L]

Updated for template redirect function:
function check_access_metadata()
{
    $dirCheck = pathinfo($_SERVER['REQUEST_URI']);
    $requestFile = $dirCheck['basename'];
        if( strpos ( $dirCheck['dirname'] , 'uploads' ) > 0  ){
            if ( is_user_logged_in() ) {
                //Do something with registered user
            } else {
                //Do something with guest
            }
        }
}
add_action( 'template_redirect', 'check_access_metadata' );

Comment: Works, but is a little too harsh, is there any way to only use this rule if the file is accessed directly / downloaded and not just used in an image tag?
Comment: I'm still a bit hazy on what you want to accomplish. Can you clarify the best possible outcome? Do you actually want to redirect users, or do you want to run a function when they access an object in the uploads directory?
Comment: If someone directly goes to the attachment url / right click downloads then I want to run a function that checks if the user is logged in.If they are then download away, else 404.However I want the images to display on the website, in an image tag for example, even if the user is not logged in.
Comment: Check [this solution](https://wpguru.co.uk/2012/01/how-to-prevent-direct-file-access-in-your-wp-content-directory/)
Comment: Hmm, this is for hot linking. It doesn't redirect if I view the attachment URL.


Why is this creation of a new pandas column causing a change in the original column?

Question: The DataFrame:
import pandas as pd
import numpy as np

df = pd.DataFrame({'col1': [2, 6, 7, 8, 2]})

col1

0
2

1
6

2
7

3
8

4
2

A function to create a new column being a cumulative sum (I'm aware of cumsum(), this was just a simple test before doing more complex functions):
def funcadd(inputarr):
    for i in range(1, len(inputarr)):
        inputarr[i] = inputarr[i] + inputarr[i-1]
    return inputarr

df['new'] = funcadd(df['col1'].values)

col1
new

0
2
2

1
8
8

2
15
15

3
23
23

4
25
25

As you can see, for some reason col1 gets modified despite never issuing a command to change it (?)
I've tried:

immediately doing arr1 = inputarr in the function then only using arr1 in the rest of the function
doing arr2 = df['col1'].values before calling the function with arr2
swapping .values with .to_numpy
Comment: try `df['new']=funcadd(df['col1'].copy())` and   col1 get modified is due to the fact that you are passing shallow copy of `df['col1']` into function for more info regarding copies refer to [What is the difference between shallow copy, deepcopy and normal assignment operation?](https://stackoverflow.com/questions/17246693/what-is-the-difference-between-shallow-copy-deepcopy-and-normal-assignment-oper)
Answer: There are better ways to do the cumulative sum in Pandas, as shown in the other answer but just to solve the issue here.
In this line
inputarr[i] = inputarr[i] + inputarr[i-1]

You are updating the values back to the original one, and since you haven't created the copy, it is writing back to the original dataframe.
if you want to avoid this, just create a copy, like this.
def funcadd(inputarr):
    c_inputarr = inputarr.copy()
    for i in range(1, len(inputarr)):
        c_inputarr[i] = c_inputarr[i] + c_inputarr[i-1]
    return c_inputarr

df['new'] = funcadd(df['col1'].values)

which returns
col1    new
0   2   2
1   6   8
2   7   15
3   8   23
4   2   25

Comment: how come `df['col1'].values = 0` doesn't work? do i only need to do `.copy()` if i'm passing it to a function?
Comment: do you want to assign 0 to all `df['col1'].values`
Comment: no, just wondering why i can't change the `df['col1'].values` outside the function but can when inside a function. just realised `df['col1'].values = 0` doesnt work inside function either, but for instance `df['col1'].values += 1` doesnt work outside the function, but if you pass it to a function as the arg `input` you can change it with `input += 1`


Sequential hostnames and auto-scaling?

Question: Is there a logical way to have sequentially numbered hostnames with servers that are autoscaling but not sequentially killed?
So if server13 is killed and server14/15 are alive, and the cluster upscales with 2 servers it will add a server with hostnames server13 and server16?
Answer: If hostname refers to only the output of the hostnamecommand (on the instance itself), assign a instance profile that allows for the instance to query existing autoscaling group members and their tags using AWS CLI. Then use a tag to denote the server hostname or index, and upon autoscaling adding a new instance, have it look at the current list of servers and assign a missing hostname to it. You can use UserData to fire up this script.
If hostname refers to an actual DNS name (in Route 53): you could maybe utilize an autoscaling lifecycle hook and have it fire a lambda that does the appropriate Route 53 record set changes (similar logic as above).

Sequential hostnames and auto-scaling?


Why do we need note names like B♭, D♭ etc.? Why not use only A♯, C♯ and so on?

Question: The very same sharp/flat tones can be written in two ways:

C♯ is the same as D♭
D♯ is the same as E♭
…and so on

This is so confusing. What is the reason for it? Wouldn't it be easier to use only X♯ or only X♭?
Answer: The equivalences you mention---C♯/D♭, D♯/E♭, etc.---aren't actually the same note.  They're called enharmonically equivalent pairs, but only in Equal Temperament are they tuned to the same frequency.  See this question for more information on why they're not the same note.
As for why we need flatted notes at all, let's look at the how major scales are put together. We need to agree on these things:

Every major scale has seven notes.  They all start on a root note and proceed to go up in the following pattern: Whole Step, Whole Step, Half Step, Whole Step, Whole Step, Whole Step, and then a final Half Step returns to the root note (an octave above where we started).
A major scale names each of its seven notes using the letters A, B, C, D, E, F, and G exactly once.  It's important not to use the same letter twice because otherwise notation would be really inconvenient.  Imagine if your major scale had both an F and an F♯ in it.  Then every time you wrote a note in the first space of the treble clef, you'd also have to explicitly tag it with an accidental, either natural or sharp.  What a pain, both for the composer and the reader.  Key signatures avoid this problem, but they only work if we agree on this no-using-the-same-letter-twice rule.

With these two principles in mind, let's build an F Major scale:
We start with F.  A whole note up and we get to G.  Another whole note, and we have A.  Now the first half-step.  What is this note?  It can't be an A♯, because we've already used A.  It can't be a B♮, because B is a whole step up from A.  It has to be some kind of B, but a half-step lower than B♮.  And so: B♭.
Now that we've invented B♭, let's create the B♭ Major scale: B♭, C, D,... uh-oh.  Guess we need an E♭.  And when we create the E♭ Major scale, we'll have to create an A♭, etc. etc.
Of course this same idea justifies the existence of sharped notes as well.  Create the G Major scale, and when you get to the seventh note you find that you've used up all the letters except F, yet you need a note a whole step up from E (or, if you like, a half step down from G).  And so you're forced to create F♯.
One could ask why it is that the interval from E to F need be a half step.  If E to F were a whole step and F to G a half step, then we wouldn't need an F♯ to make the G Major scale.  This is true, but it's also robbing Peter to pay Paul: then the D Major scale would still require a C♯, while the C Major scale would now require an F♭.
Comment: Equal Temperament only means that the relative differences in frequency are the same. Well Temperament, for example, has unequal distances between the 12 tones, but it still allows playing in all keys because since enharmonics are tuned to the same frequency (you still only have 12 keys on the keyboard). See http://en.wikipedia.org/wiki/Musical_temperament
Comment: @NReilingh: You make an excellent point that often goes overlooked. It's a common misunderstanding that Equal Temperament is the same as Well Temperament.  In fact, when Bach wrote the Well-Tempered Clavier, he wasn't thinking of Equal Temperament, and he wrote the mood of each piece to match the character of the particular key in which it was set.
Comment: Indeed; I was qualifying your first paragraph: `only in Equal Temperament are they tuned to the same frequency`
Comment: Technically you should say 12-equal temperament, since in e.g. in 19-ET they are 1 step apart (except B#=Cb and E#=Fb).
Answer: C# is not the same as Db any more than the English word "hear" is the same word as "here".
Understanding why there is a difference is an important foundation to Western melody and harmony. It's important to understand the following:

the vast majority of western music involves 12 notes in an octave
the vast majority of western music is based around a scale consisting of 7 of those notes specific to the choice of key (the notes are called the diatonic notes for that key)
each letter name is only used once amongst the diatonic notes
a particular note in a piece is functioning either as a diatonic note or as a note a semitone higher or lower than a diatonic note
when expressing a note that is functioning as a raised or lowered note, you use the same letter name as the diatonic note you are raising or lowering. e.g. a raised G is G♯ and a lowered G is G♭.
if the diatonic note is already written with a sharp, the raised note has a double sharp and the lowered note has a natural symbol
if the diatonic note is already written with a flat, the raised note has a natural and the lowered note has a double flat
but in all cases, the letter part of the note name stays the same

So, imagine you're in the key of A major. The diatonic notes are: A B C♯ D E F♯ G♯. What does C♯ mean? It means the third note of the scale. What does D♭ mean? It means you've taken the fourth note of the scale and lowered it it.
In 12-tone equal temperament, they may sound the same; you may play them the same on the piano or the guitar. But if the function of the note at a particular point in the piece is as the third note in the A major scale, you can only write it C♯ and not D♭. C♯ means something completely different.
In non-12-et tunings, they won't even sound the same.
Comment: It's worth noting that with handbells, the C# above middle C will be played with the same bell as would the Db, but the former note would generally be played by one person's right hand while the latter would be played by the next person's left hand.  Assigning each person's left hand to a note written on a "line" and the right to the note written on a "space" will ensure that each person in the middle of a diatonic scale will play two notes--one with each hand.
Answer: The flats and sharps came about separately as modulations toward the subdominant and the dominant, respectively. The subdominant is more important in older western music and church music. The dominant modulation was a more recent development.
So going from C to F is a modulation toward the subdominant. To modify the lydian mode (C scale starting on F, w-w-w-h-w-w-h) into the Ionian mode (F scale starting on F, w-w-h-w-w-w-h) means the fourth (B) has to be flattened (B♭).
To go from C to G is a modulation toward the dominant. To modify the myxolydian mode (C scale starting on G, w-w-h-w-w-h-w) into the Ionian mode (G scale starting on G, w-w-h-w-w-w-h) means the seventh (F) has to be raised (F♯).
Additional sharps and flats in the key signature represent further deviations from the C-Major scale; but always they are patching the fours and sevens to realign the modes.
Answer: Because they are not really the same, only in equal temperament tuning they are. Look here: http://en.wikipedia.org/wiki/Enharmonic.
Comment: "only in equal temperament tuning they are": this is not correct.  They are the same in every 12-tone temperament.  Any tuning system that has different frequencies for enharmonically equivalent pitches is not a 12-tone system.  The article mentions that "G♯ and A♭ are not the same note" in meantone temperament, but faced with a 12-tone keyboard, one must in fact choose some single pitch for the single key that sits between G and A, so in an actual 12-tone meantone temperament, they *will* have the same frequency.  That's why split-key keyboards exist, but those have more than 12 tones.
Answer: Another example of an instrument where the distinction between enharmonic notes is important is a handbell choir.  A typical three-octave handbell choir will have eleven people.  Starting with the C below middle C, the first performer will play C and C# with the left hand, and Db, D, and D# with the right.  The second performer will play Eb and E with the left hand; F and F# with the right.  The third performer will take Gb, G, and G# with the left; Ab and A with the right, etc.
If part of a piece is in Eb major and part is in E major, the D#/Eb chime would be played by the second performer's left hand when it was used as an Eb, and by the first performer's right hand when it was used as a D#.  The same bell is used for both D# and Eb, but who plays it depends upon which note is used for it.  While there are occasions when that pattern doesn't work out optimally, in most cases it works out well since a D# is more likely to be played near an E natural than a D natural, but an Eb is more likely to be played near a D natural than by an E natural.


Is there any other means to achieve scroll position state without using indexed stack?

Question: I am currently using IndexedStack in a project, and the reason I decided to go with it is that:
If I want to change tabs or even navigate to other parts of the app from a screen with a scrollable widget, when I switch/come back to the screen, the screen will still maintain the scroll position it was.
What I noticed and don't like is how all the screens attached to IndexedStack as children are initialized, even before accessing them.
BottomNavigationBar does a better in handling screens.
What is the way around this?
Answer: Pass a ScrollController to your scrollable widget, and then call this controller to scroll to the top when you come back or right before you come back.


Responsive Form without await

Question: Suppose you are doing a lot of stuff inside a form.
while(true)
{
    DoStuff();
}

This results in problems: while the loop is executing the form stops redrawing and locks up.
The goto solution is to use async/await.
while(true)
{
    await Task.Run(DoStuff);
}

...or some variation on that.
However if the cycle period is small this will result in new task objects popping up and GC struggling to  disintegrate them. Though a modern machine can handle this without a problem, I think it is still desirable to avoid that.
I have found that you can solve the redraw problem with Control.Invalidate(). It will redraw the form, as long as it stays in focus.
while(true)
{
    DoStuff();
    MyControl.Invalidate();
    //or
    MyForm.Refresh();
}

However I have no idea how to avoid the locking.
As far as I know forms run on one thread, so while my code is executing the form is unable to process windows messages. In a cpp program you would just go through the message buffer every cycle yourself. But what can you do here?
Comment: You should follow the async/await path.
Comment: Can't you put the while loop inside the `Task` ?
Comment: Yes, in winforms it is `Control.Invoke()`.
Comment: @Ackdari Yes, but if you use async/await wise enough that will all be done behind the scenes
Comment: @Ackdari You can use Task.Run for cpu-bound code to run in background without blocking and await that task. Read https://blog.stephencleary.com/2013/11/taskrun-etiquette-examples-dont-use.html
Comment: An alternative to `async/await` would be to use the `BackgroundWorker` which can be nice for instances where you want it to be running all the time and still get UI updates.
Comment: Read [Stephen Cleary: Task.Run vs. BackgroundWorker](https://blog.stephencleary.com/2013/09/taskrun-vs-backgroundworker-round-5.html)
Comment: @Cid you can only modify the form from the main thread.
Comment: In WPF one can dispatch some task to the main-thread from any other thread, is this also possible in winforms?
Comment: _"In a cpp program you would just go through the message buffer every cycle yourself. But what can you do here?"_ well what do you do in `DoStuff()`? I think you approch is generelly illsuited for the winforms framework.
Comment: @SirRufo doesn't this depends on whether `DoStuff()` can be made _truely_ async, I mean if is does CPU heavy stuff then is needs to be performed on another thread and then I would suggest to use `Control.Invoke()` to dispatch any UI related task back to the UI-Thread.
Comment: @WSC Yes, thank you. It works just as I need, as far as I can tell. There was an answer that recommended this option, but it was deleted for some reason.
Answer:
However if the cycle period is small this will result in new task objects popping up and GC struggling to disintegrate them. Though a modern machine can handle this without a problem, I think it is still desirable to avoid that.

Allow me to quote Donald Knuth:

Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.

In other words, use await Task.Run. If and only if performance analysis indicates that there are performance problems, then explore alternative solutions. And if performance analysis does indicate a problem, the first alternative solution I would suggest is increasing the amount of code within the Task.Run.
Answer: If you want to go old school and use manual threading, your code would look similar to your original idea.  I've placed some comments in key areas to bring your attention to caveats.  The BackgroundWorker control takes care of this type of stuff for you:
private System.Threading.Thread T;

private void Form1_Shown(object sender, EventArgs e)
{
    T = new System.Threading.Thread(new System.Threading.ThreadStart(backgroundThread));
    T.IsBackground = true; // optional: allows program to close even when T is running
    T.Start();
}

private void backgroundThread()
{
    while (true)
    {
        DoStuff();

        this.Invoke((MethodInvoker)delegate() {
            // It's safe to update the UI from within this block
            //
            // This should be done sparingly or it negates the
            // whole process of using a separate thread!
        });

        System.Threading.Thread.Sleep(100); // slight CPU break
    }
}

private void DoStuff()
{
    // foo();
    // bar();
    // stuff();
}

Answer: What I wanted is:
while(true)
{
    DoStuff();
    MyForm.Invalidate();
    Application.DoEvents();
}

Though arguably a better solution would be not to use C# for my problem...

Responsive Form without await


Is it bad to play wind instruments with clean teeth?

Question: Since I started playing the saxophone, I've always been told that you are to never play the saxophone if you have eaten recently. I was told the reason for this was that (if any) the sugar on your teeth would damage the mouthpiece and reed.
This makes sense to me, so every time, before I play, I brush my teeth. However, I started to wonder if that was an equally bad idea.
Is toothpaste and/or mouthwash bad for the reed or mouthpiece?
Answer: My son plays saxophone and his band teacher is very careful about giving instructions for home practice.  He hasn't said anything about risks coming from toothpaste or mouthwash.  Also this sax forum stresses getting rid of the food particles but doesn't warn about damage from the cleaning substances: http://forum.saxontheweb.net/showthread.php?7159-Proper-Reed-Care-and-Cleaning
My son's band teacher told me that the most important things to maximize the life of a reed are to soak it for a few minutes before playing, and to handle it carefully.
How about if you make sure to rinse your mouth thoroughly after brushing?
Answer: I don't think this is a big deal.  I don't think that brushing/using mouthwash is necessary, just washing out your mouth to get the food out of your mouth should be enough.  In fact, it's sometimes recommended to soak your reed in mouthwash if it starts to smell bad.
As long as you aren't using a VERY sugary/basic substance, it should be fine.
Answer: Mouthwash contains alcohol, right? That makes me worry that alcohol vapor in my breath may break down the glue that holds the pads in place over time. Maybe a way round this would be to wash 15-20 minutes in advance of playing so the alcohol can evaporate.
Also, if any of the residual abrasive in toothpaste gets into your instrument and builds up... it can't be good, right? Thoroughly rinsing out your mouth with water several times before playing is probably a good idea in the case of both mouthwash and toothpaste.
All that being said, I do not know, I'm just voicing my fears, and I'm going to have to do more research.
Comment: These are interesting points. I'd like to see if anyone has the same thoughts.
Answer: I'd like to contribute, that for double reed instruments you are recommended to brush your teeth before playing. It is not in any way to prevent chemical reactions, but to avoid blowing remainders of your meal into the instrument (so more physical reasons). I never heard of any damage to reed, pad glue (which would be sealing wax in most cases I know of) or instrument by alcohol / tooth paste / mouthwash, and given the amount of air one dilutes that chemistry with, I can't imagine the concentration is significant.
Answer: Not sure if the chemicals would damage the instrument, but for brass instruments which use metal mouthpieces it has never been a problem for me.  Incidentally I have found I play better when I brush my teeth, or maybe it just feels better to be clean.
Sweet drinks are definitely a no-no while I play though.


io error on no-match glob within cifs OSX -> debian jessie mount

Question: Using a wildcard/glob (at least * and ?) in bash causes an input/output error when there are no matches on a samaba cifs mount in Debain Jessie 8.2. On other filesystems, the expected No such file error is given.
The same samaba mount point on an archlinux box and has no io error. The Archlinux machine's mount.cifs understands mapposix. I suspect that mount.cifs on jessie does not allow/understand mapposix has something to do with this.
Is there away around io errors for *?

 ## works as expected on cifs mount from centos server
 ls /data/Luna1/*adfadf*
 # ls: cannot access /data/Luna1/*adfadf*: No such file or director

 ### unexpected io failure on osx mounted on debian
 mkdir /Volumes/Phillips/testdir

 ## no files match in empty directory: io error
 ls /Volumes/Phillips/testdir/*
 #  ls: reading directory /Volumes/Phillips/testdir/*: Input/output error

 ## glob matches, ls results
 touch /Volumes/Phillips/testdir/file
 ls /Volumes/Phillips/testdir/*
 #  /Volumes/Phillips/testdir/file

 ## glob matches, ls results
 ls /Volumes/Phillips/testdir/*il*
 # /Volumes/Phillips/testdir/file

 ## no files match: io error
 ls /Volumes/Phillips/testdir/*foobar*
 #  ls: reading directory /Volumes/Phillips/testdir/*foobar*: Input/output error

 # fails as expected
 ls /*filedoesnotexist*
 #  ls: cannot access /*filedoesnotexist*: No such file or directory

 ## zsh handles this correctly
 zsh -c "ls /Volumes/Phillips/*dne*"
 #  zsh:1: no matches found: /Volumes/Phillips/*dne*

System info:
cat /etc/debian_version
   8.2
dpkg -l cifs-utils
   ii  cifs-utils     2:6.4-1      amd64        Common Internet File

mount |grep cifs
//gromit/Luna1/ on /data/Luna1 type cifs (rw,relatime,vers=1.0,cache=strict,username=foranw,domain=GROMIT,uid=1000,forceuid,gid=1000,forcegid,addr=10.145.64.52,unix,posixpaths,serverino,nobrl,acl,rsize=61440,wsize=65536,actimeo=1)

//skynet/Phillips/ on /Volumes/Phillips type cifs (rw,nosuid,nodev,noexec,relatime,vers=1.0,cache=strict,username=lncd,domain=SKYNET,uid=1000,forceuid,gid=1000,forcegid,addr=10.145.64.109,file_mode=0755,dir_mode=0755,nounix,nobrl,rsize=61440,wsize=65536,actimeo=1)

Answer: My current workaround is to touch a file that matches the glob to avoid an error
This works particularly well for FSL's bet where rm is called with a glob that matches nothing. Interestingly, it throws "directory exists" (when it does not) instead of IO error.
bet 002_mprage_hpf 002_mprage_hpf_brain -m -f 0.1
# /bin/rm: cannot remove '002_mprage_hpf_brain_tmp*': Is a directory.
[ $? -ne 0 ] && echo failed
# failed

vs
touch 002_mprage_hpf_brain_tmp_hackyhackhack
bet 002_mprage_hpf 002_mprage_hpf_brain -m -f 0.1
[ $? -ne 0 ] && echo failed
# $? == 0


PHP if requested URL like

Question: I would like to know how to do an 'if requested URL like' statement. For example, I currently have the following code, but I want to the base, icon and logo applied on all locations after route=checkout/
What is the wildcard value? Am I on the right lines?
<?php
if($_SERVER["REQUEST_URI"]=="/index.php?route=checkout/checkout")
$base='https://domain.co.uk/>';
$icon='/image/data/favicon.png';
$logo='/image/data/logo.png';
?>

Comment: Your question is a bit unclear. Can you reword it?
Answer: Strpos is perhaps what you want?
if (strpos($_SERVER['REQUEST_URI'], '/index.php?route=checkout') !== false) {
// Do your stuff here.
}

Comment: That's great, thanks!

What if I want multiple values such as

    '/index.php?route=checkout'
    '/index.php?route=account'
    '/index.php?route=affiliate'

How could I do that?
Comment: You could use a regular expression to do the matching (preg_match(/(checkout|affiliate|account)/, $_SERVER['REQUEST_URI']) (note: I didn't test that), or you could parse out the uri bits using parse_url: http://php.net/manual/en/function.parse-url.php and then check the query parameters on their own.

PHP if requested URL like


Geometry - really hard trapezium problem.

Question: Can anyone explain me how to find the area of this trapezium if we have a base and radius of the circle?
Comment: Something is wrong, you can shift the top to the left and maintain  the right angle with the radius and maintain parallel top and bottom, yet making the right side as long as you want.  So the trapezoid could have arbitrarily large area.
Comment: The two angles on the left need not be right angles to maintain a trapezoid, you just need to maintain two parallel sides.  A trapezoid does not need to have any right angles.
Comment: Assuming the two angles are right, this is solvable using the Pitot theorem:  http://en.wikipedia.org/wiki/Pitot_theorem.  Let $x$ be the length of the non-$b$ base in excess of 3 such that the length of that base is $3 + x$.  Then $3 + 3 + x = 4 + \sqrt{x^2 + 16}$.
Comment: Do you know anything about the angles of the trapezoid?  Two of them look like right angles, can we assume that?  If not, I don't think it has a unique solution.
Comment: No, only the base b and the radius (the only angles I know are 2 angles on the left, they are right angles because this is a right trapezium).My teacher somehow solved the problem this way http://i.imgur.com/ayVlWe5.png  he found out that HF and FI equal 1 and after a while he made an equation which contained x+1 and x-1, that's all i remember.
Comment: If the angle are assumed to be 90 as shown is diagram then the area can be $\dfrac{rb^2}{b-r}$ and hoping no careless mistake ofcouse.
Comment: Mann that is correct but how did you solve this problem?
Answer: So, you know a little more than just the top base and the radius.

Using the letters in the plot that you attached in the comment, you also know

that the circle is inscribed in the trapezium
that the angles in D and C are right angles
that the angle AIF is right too
that the height DC is 2r
that the segment HF=1, because it is $CF-r=3-2$

Since the circle is inscribed in the polygon, the two angles $\widehat{FAI}$ and $\widehat{HAF}$ are equal and so are the two triangles, since you also know that $AH=AI$ and $AF$ is shared. So, since the two triangles are equal, the two segments $HF$ and $FI$ are qual too, giving $IF=b-r=1$.
Now, name $x$ the piece of the lower base that we need to find, $x=GE$. If you draw the perpendicular form A to the side DE and, as before, draw also the bisector of the angle $\widehat{GEF}$ you will see (with an argument identical to the previous one) that $IE=x+b-r=x+1$, so that the hypotenuse $FE=x+2(b-r)=x+2$.
Using Pythagora's theorem for the triangle GEF you will have:
$$x^2+4^2=(x+2)^2$$
or in more general terms
$$x^2+(2r)^2=(x+2(b-r))^2$$
This means
$$x=\frac{r^2-(b-r)^2}{b-r}=3$$
which is in agreement with what obtained with the Pitot theorem, mentioned by others.
Finally, your area is
$$A=2r\frac{b+(b+x)}{2}=18$$
in agreement with Mann's comment.
Answer: Theorem
For every pair of tangents meeting at a point $A$, $AB=AB'$, where $B,B'$ are the tangential points.
Problem
Let $GC=a$ and $G'E=u$. Applying the theorem we have $BG=BH=3-a$, $GC=G'C=a$,
$G'E=H'E=u$ and $HD=H'D=a+1$. Notice $BH=GA\implies a=1$.
Observe $CE^2=(GH')^2+(u-a)^2\implies(u+1)^2=4^2+(u-1)^2\implies u=4$.
The area is $\displaystyle \frac{4[3+(a+1+u)]}{2}=18$
Answer: Sorry for the crummy drawing (I wouldn't object if someone replaced it with a better one!), but hopefully it gets the point across:

The key triangles are similar, so
$${L\over r}={r\over b-r}$$
This gives $L=r^2/(b-r)$, so the area of the trapezium is
$${1\over2}(2r)(b+(r+L))=r\left(b+r+{r^2\over b-r}\right)={rb^2\over b-r}$$
Answer: area of the trapezium is
$$=(r)(2r)+(r)(b-r)+(r)\left(\frac{r^2}{\sqrt{b^2+r^2-2br}}\right)=r^2+br+\frac{r^3}{b-r}=\frac{rb^2}{b-r}$$
Now, setting the values $r=2$ & $b=3$, we get area of trapezium
$$=\frac{2(3)^2}{3-2}=18 \space sq. units$$
Answer: Similar triangles, similar triangles...

Drawing lines out from the centre of the circle $O$ as shown, we see that

$\triangle OEB$ and $\triangle OBF$ are congruent right triangles and also that
$\triangle OFC$ and $\triangle OCG$ are congruent right triangles.

We can also see that $2\alpha + 2\beta$ forms a straight line, so - the key insight for me

$\alpha + \beta$ is a right angle.

This means that $\triangle OBF, \triangle OBC$ and $\triangle OFC$ are all similar, and thus, since $|OE| = 2|EB|, \: |CG| = 2|OG| = 4$ and $|CD|=6$, giving the area of the trapezium:
$$\text{Area} = |AD|\frac{|AB|+|CD|}{2}= 4\frac{3+6}{2} = 18$$
Answer:
By Pythagoras' Theorem, $$
\begin{aligned}
\because 4^{2}+(x-1)^{2}=(x+1)^{2} & \Leftrightarrow x=4 \\
\therefore \text { Area of the trapezium } &=\frac{1}{2}(4)(3+3) =18
\end{aligned}
$$


What is the sum of this series: $\frac{2}{\pi}\sum_{k=1}^{\infty}\frac{(-1)^{k-1}}{2k-1}$

Question: Can anyone help me with this?
What is the sum of this series:
$\frac{2}{\pi}\sum_{k=1}^{\infty}\frac{(-1)^{k-1}}{2k-1}$
I got it after plugging $x=-1$ in a Fourier series
Thank you!
Comment: $$\frac{2}{\pi}\left(1 - \frac13 + \frac15 - \frac17 + \ldots \right) = \frac{2}{\pi}\int_0^1 (1 - t^2 + t^4 - t^6 + \ldots) dt\\ = \frac{2}{\pi}\int_0^1 \frac{1}{1+t^2} dt = \frac{2}{\pi}\tan^{-1}1 = \frac12$$
Comment: You are probably supposed to use the original Fourier series to figure out the value of the sum! Are you familiar with Dirichlet's theorem?
Answer: Substitute $u=k-1$. Then the sum becomes:
$$\sum_{u=0}^\infty \frac{(-1)^u}{2u+1}$$
Which we can recognize as the Leibniz formula for $\frac{\pi}{4}$.
Thus your result is $$\frac{2}{\pi} \cdot \frac{\pi}{4} = \frac{1}{2}.$$
Answer: $\newcommand{\+}{^{\dagger}}
 \newcommand{\angles}[1]{\left\langle\, #1 \,\right\rangle}
 \newcommand{\braces}[1]{\left\lbrace\, #1 \,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\, #1 \,\right\rbrack}
 \newcommand{\ceil}[1]{\,\left\lceil\, #1 \,\right\rceil\,}
 \newcommand{\dd}{{\rm d}}
 \newcommand{\down}{\downarrow}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}
 \newcommand{\fermi}{\,{\rm f}}
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}
 \newcommand{\half}{{1 \over 2}}
 \newcommand{\ic}{{\rm i}}
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}
 \newcommand{\isdiv}{\,\left.\right\vert\,}
 \newcommand{\ket}[1]{\left\vert #1\right\rangle}
 \newcommand{\ol}[1]{\overline{#1}}
 \newcommand{\pars}[1]{\left(\, #1 \,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\vphantom{\large A}\,#2\,}\,}
 \newcommand{\sech}{\,{\rm sech}}
 \newcommand{\sgn}{\,{\rm sgn}}
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}
 \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}
 \newcommand{\wt}[1]{\widetilde{#1}}$
\begin{align}
\color{#66f}{\large\sum_{k = 1}
{\pars{-1}^{k - 1} \over 2k - 1}}&
=\sum_{k = 1}^{\infty}\pars{-1}^{k - 1}\int_{0}^{1}
t^{2k - 2}\,\dd t
\\ & =
\int_{0}^{1}\sum_{k = 1}^{\infty}\pars{-t^{2}}^{k - 1}
\,\dd t =
\int_{0}^{1}{1 \over 1 -\pars{-t^{2}}}\,\dd t
\\[3mm] & =
\int_{0}^{1}{\dd t \over 1 + t^{2}} =
\color{#66f}{\large{\pi \over 2}}
\end{align}


cucumber jvm close browser after running all features

Question: I'm testing a Spring Boot app using Cucumber-JVM and Selenium. I'm defining a web driver bean and passing a destroy method to quit (shutdown the webdriver and all instances of Chrome) but it is leaving the browser open.
@Configuration
@ComponentScan(basePackages = "com.rodmccutcheon.pensionator.bdd")
public class CucumberConfig {

    @Bean(destroyMethod = "quit")
    public WebDriver webDriver() {
        System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");
        return new ChromeDriver();
    }

}

I've basically copied an example from the Cucumber for Java book. The difference is they use xml configuration and I've opted for Java configuration.
<bean class="org.openqa.selenium.support.events.EventFiringWebDriver" destroy-method="quit">
    <constructor-arg>
        <bean class="org.openqa.selenium.firefox.FirefoxDriver" />
    </constructor-arg>
</bean>

How do I get the browser to close at the end of all tests?
Comment: Shouldn't you pass the destroy method to quit to a separate function other than `public WebDriver webDriver()` as here you are creating the driver instance?
Comment: I think it should work. I've basically copied an example from the Cucumber for Java book. The difference is they use xml configuration and I've opted for Java configuration. See edit above for code snippet.
Comment: IMO, it shouldn't as `public WebDriver webDriver()` is returning a `WebDriver` instance where as to destroy or quit the browser instance you need to invoke `quit()` explicitly.
Answer: I thought the default bean scope was singleton, but the browser is correctly shut down if I add @Scope("singleton"). eg:
@Bean(destroyMethod = "quit")
@Scope("singleton")
public WebDriver webDriver() {
    System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");
    return new ChromeDriver();
}

Comment: Not sure why you've been downvoted, this is exactly what fixed it for me too!
Answer: do you have the following code in your java class ?
public void quit()  {
      driver.quit();
    }

In your bean definition, you are initialising the driver. By convention , you should use init-method attribute for setup and destroy-method attribute for teardown.
the bean should look like this.
WebDriver driver;

public void initDriver(){
System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");
driver = new ChromeDriver();
}

public void quit(){
driver.quit();
}

@Bean(init-method="initDriver" , destroy-Method = "quit")
    public void testUrl() {
    driver.get("https://www.stackoverflow.com");
    driver.getTitle();
    }

Answer: It probably just that you picked the wrong attribute of the annotation (or simply a typo). Instead of using destroyMethod you should use destroyMethodName. Refer to this.
@Configuration
@ComponentScan(basePackages = "com.rodmccutcheon.pensionator.bdd")
public class CucumberConfig {

    @Bean(destroyMethodName = "quit")
    public WebDriver webDriver() {
        System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");
        return new ChromeDriver();
    }

}


Fullpage.js disable autoscroll on mobile

Question: I am pretty new at the coding, just so you know.
I am using the Fullpage.js for my portfolio, and its working great..
But i want to disable the autoscroll when the site is shown on a mobile device.
I have searched a lot, and found some answers but dont know where to put them/adjust them, so i never got it to work sadly..
When i change autoScrolling: true, - to autoScrolling: false, it works fine, but i only wont it to be false on a mobile device.
Can anybody help me? I haven't learned much about Js btw.
Comment: I found this code; var isPhoneDevice = [ WHATEVER FUNCTION YOU WANT TO USE ]

//if it is not a phone device...
if(!isPhoneDevice){
    //initializing fullpage...
    $.fn.fullpage();
}
Comment: So there you go.. Use your `autoScrolling` init function in there ?
Comment: or even better, use `autoScrolling: !isPhoneDevice()` ?
Comment: So i just have to put autoscrolling: false into the [ WHATEVER FUNCTION YOU WANT TO USE ]?
Answer: What is a mobile phone for you? Why only on a mobile phone and not in a small viewport?
Usually the approach nowadays is to style the website based on the dimensions of the screen/viewport and not in the type of device.
You should be using the responsiveWidth or responsiveHeight options provided by fullpage.js.
Comment: Well it is a small viewport in my eyes, i just got used to say mobile, tablet or desktop. the Responsivewidth does not have anything to with the autoscroll, does it?
Comment: Erm.... it does?? Read [the docs](https://github.com/alvarotrigo/fullPage.js): *responsiveWidth: (default 0) A normal scroll (autoScrolling:false) will be used under the defined width in pixels. A class fp-responsive is added to the body tag in case the user wants to use it for his own responsive CSS. For example, if set to 900, whenever the browser's width is less than 900 the plugin will scroll like a normal site.*
Comment: AHH! I see that now, it makes more sense. Now my only problem is, how do i write this into my js correctly?
Comment: As right now, i have this;

     var isTouch = "ontouchstart" in document.documentElement;
            $(document).ready(function() {
        if(isPhoneDevice){
            autoScrolling: false,
        };
            else{
                //desktop
                $.fn.fullpage();
            }
        });
Comment: Check [the demo online](http://alvarotrigo.com/fullPage/examples/responsive.html). The source code is available in [the fullpage.js example files](https://github.com/alvarotrigo/fullPage.js/tree/master/examples) that come with the download.
Comment: I have already checked it out the demo before i downloaded it. there isnt a source code for the autoscroll:false for mobile devices, as far as i can see.. But thanks a lot.


create hyperlink with unique id while iterating a model in asp.net mvc

Question: <%var i=1;%>
<%foreach (var commentitem in item.commentsModelList)
   {

           <%: Html.DisplayFor(modelItem => commentitem.CommentClob)%>

        <%var rid = "reply" + i;%>
          <input id="<%:rid %>" type="button" value="reply"/>

      <%--addded--%>
        <div id="<%:rboxid %>">
            <input id="Text1" type="text" />
            <input id="postreply" type="button" value="postreply" />

<% i++;}%>

I have the following query
1.
I  want to display alert boxes when different hyperlink with different reply id is clicked.
Edited
2.
i want a to hide these div on page load and show div with id replybox1 when link with id reply1 is clicked and same for other divs
3.Is there any way to create div dymaically and performing the same functionality
Answer: Use modelItem.Id for disambiguating links instead of for loop counter;

        <%var rid = "reply" + modelItem.Id ;%>
          <input id="<%:rid %>" type="button" value="reply"/>

Answer: You have defined the variable i inside the for loop. This means you are allocating a new integer with value 1 for each iteration.
Try moving the definition of i outside of the loop.
Comment: yes i have done it .....thks can u help me how to display alertbox when a particular hyperlink with particular id is clicked
Answer: To get an alert of the id when clicking on the input button, you can use this script. ( Assuming you have jQuery available in your page)
   $(function(){
      $(".commentbox input[type='button']").click(function(){
        var id=$(this).attr("id");
        alert(id);
      });
    });

As Hasan already mentioned. you should probably use the comentItemId instead of using the i variable
EDIT  As per the update in question, This script will hide all divs in the page load and show only those div with id replybox1 when input with reply1 being clicked.
   $(function(){
      $(".commentbox div").hide();
      $(".commentbox input[type='button']").click(function(){
        var id=$(this).attr("id");
        var replyBoxId=id.substring(5);
        $("#replybox"+replyBoxId).show();
      });
    });

Comment: yes its working but i have another query i have edited my question please have a look
Comment: yes it is working but is there any way if i can div dyamically and then do this functionlity
Comment: @prerna: What you mean by that ? I guess, you should better post another question specific to that with relevant code for that
Comment: i have posted new quesition on the link http://stackoverflow.com/questions/10163305/create-div-dynamically-on-click-of-a-hyperlink-in-asp-net-mvc


MLE for two-parameter exponential distribution

Question: I have to find the parameters of a two-parameter exponential distribution using the MLE. But imposing first order conditions, I do not find enough conditions to found both the paramenters.
Any hint?
Thanks!
Comment: What does your second parameter do?  Shifted exponential?  Something else?  A good starting point is to define the pdf ...
Comment: Please expand abbreviations (in this case, "FOC") on first use. Please add the `self-study` tag and read its [tag wiki](http://stats.stackexchange.com/tags/self-study/info), modifying the question as needed.
Comment: https://stats.stackexchange.com/questions/298874/mle-for-2-parameter-exponential-distribution
Answer: Assuming you mean the shifted exponential distribution with p.d.f $$\lambda e^{\lambda(t_i-\gamma)}$$ The maximum likelihood estimate for a sample $(t_1, \ldots, t_n)$ is given by $$\gamma = \min_i t_i$$ and $$\lambda = \frac{n}{\sum_{i=1}^n (t_i-\gamma)}$$.
You'd probably be better off with a prior on $\gamma$ though.


How can I load a theme template to render $submitted

Question: I'm trying to replace the output of $submitted in my nodes. I have found how to replace the value which is fine. The problem I'm facing is how to load a template file properly.
function pod_preprocess_node(&$vars) {
  $vars['submitted'] =  t('!datetime ', array(
    '!datetime' => include_once(__DIR__.'/system/submitted.tpl.php')
  ));
}

As you can see above, I've just included a template file and in there I can use $vars but this is clearly sub optimal. What I'd like to do is just load a template file from my theme which has some sensibly named variables in.
I've looked at hook_theme() which now allows me to call theme('pod_submitted', $vars) but I don't know how to make pod_submitted() include the right file etc.
I assume that somewhere I need to do the following
$vars['theme_hook_suggestions'][] = 'system__submitted';

But I'm not sure how my template function relates to/knows which template to call.
Comment: It sounds like you're treating 'submitted' as a field, but it is not a field. It's just a variable defined in the node module. As I think you know, it doesn't contain much but text giving the username and date it was submitted. Tell us why you want a separate template to display that info, and the smart people of drupal.stackexchange might give you a better way to architect a solution.
Comment: I need to put some HTML in the submitted variable consistently across all nodes, even those with overridden templates. For example I can split the various bits of information in `$submitted` into lots of variables and output them in node.tpl.php individually but I want to just change the output across the board. At the moment my HTML is in my hook_preprocess_node() method which is not ideal. I want to put it in a template file so that it can be themed more appropriately.
Answer: Well, what you're looking for is hook_theme. With hook_theme you can declare new theme implementations, which can be either functions or templates. I'll stick with templates for this answer. Just define it in YOURTHEME's template.php file:
function YOURTHEME_theme($existing, $type, $theme, $path) {
  return array(
    'YTsubmitted' => array(
      'template' => 'YTsubmitted',
      'variables' => array('whom' => NULL, 'when' => NULL),
    ),
  )
};

I'm calling the theme hook YTsubmitted and the template file  YTsubmitted. Those names don't need to be the same, but I'm prefixing to avoid collisions. Now, whenever you call theme('YTsubmitted'), Drupal will look for YTsubmitted.tpl.php in your theme and use it for rendering. You can pass variables to it when calling, just like theme('YTsubmitted', array('whom' => 'Jake the dog')). Variables will default to values set when defining the theme hook in hook_theme (NULL in our example). But you can also preprocess variables:
function YOURTHEME_preprocess_ytsubmitted(&$vars, $hook) {
  $vars['extra'] = 'Mathematical!';
}

And now you can use it in your template file (YTsubmitted.tpl.php):

Submitted by <?php print $whom ?> right after <?php print $when ?>. <?php print $extra ?>!

That's precisely how Drupal sets several of the templates and its variables. For instance, node.tpl.php will print the $submitted variable, which can be redefined in your template.php file:
function YOURTHEME_preprocess_node(&$vars, $hook) {
  $vars['submitted'] = theme('YTsubmitted', array('whom' => 'Finn the human'));
}

AAAaaand you're done.
Comment: DO NOT FORGET TO CLEAR CACHES!
Answer: Is system/submitted.tpl.php in your theme directory?
Your method is not the correct way to accomplish what you are trying to do. I hope this clears it up.
hook_preprocess_node is pretty close. Do override the 'submitted' variable. Do add extra variables (you can name them how you please). Don't include a template file.
function themename_preprocess_node(&$vars) {
  $vars['submitted'] = "foo";
  $vars['foo'] = "bar";
  $vars['bar'] = "xyz";
}

Template override. You don't need to add a submitted template. Simply copy the node.tpl.php file from either your parent theme's directory, or the node module in core, and place it in your theme directory. Flush you caches. Edit that file and make your changes in there. For example adding in the $foo variable from above (note: All $vars['foo'] are exposed both as $vars['foo'] and $foo for convenience).
cp modules/node/node.tpl.php sites/all/mytheme/node.tpl.php

--
  <?php if ($display_submitted): ?>

      <?php print $submitted; ?>
      Foo:
      <?php print $foo; ?>
      Bar:
      <?php print $bar; ?>

  <?php endif; ?>

Comment: The problem with this is that I have lots of overridden node--content-type.tpl.php files which means that everywhere I need to do this. If i make a change to it, then i have to edit the markup in each node-- tpl override. I would like to abstract the theming of the output of `$submitted` in order to allow a single place to update the markup. At the moment my markup is in my theme_preprocess_node() function.
Comment: The above answer is correct. You can add html tags and conditions to the $sumitted output as you like. There is no need to do these on your tpl.php file, this preprocess function is fine. If you need a template for a variable you need to create a module and use hook_theme. An example [here](http://stackoverflow.com/questions/4749416/drupal-7-and-using-custom-templates-with-theme). In any case if you have hard customized $sumitted on your node.tpl.php files you can do nothing else that changing this code.
Comment: I think if you wanted you could do some sort of include in all your node--*.tpl.php files. Then make your submitted changes in there. I've not done that but it shouldn't be too hard. What about this?
https://drupal.org/node/1056074#comment-4075372
Comment: There's no need for includes if you can use hook_theme to create new templates. I don't think includes will play nice with sub-themes, for instance.


Inserir dados de um array em um banco mysql

Question: Recebo um json de uma aplicação android. Esse json é uma classe java que foi convertida com Gson do java para uma string. Apos o web server em php receber esse json eu converto para uma array.
Quero fazer um insert genérico no meu web server, onde que automaticamente ele percorre o array e insere na tabela passada por parâmetro.
ex:
<code>public function create($array){

    /*
     * O nome da tabela é recebida por um post e é passada por um construtor
     * $condição: Aqui eu teria que pegar os nomes das keys e deixar assim por exempo: nome, idade, sexo
     * $valores: tenho que pegar o conteudo dos arrays. Ai tenho que verificar se é uma string ou data ou float para deixar entre aspas.Ex: 'rafael', 18, '1987-12-12'
    */
    $query = "INSERT INTO $this->tabela ( $condicao ) VALUES ( $valores )";

    $flag = mysqli_query($this->con, $query);

    if($flag === TRUE){
        $json['flag'] = TRUE;
    } else {
        $json['flag'] = FALSE;
    }

    mysqli_close($this->con);
    return $json;

}
</code>
não sei se tem uma maneira mais fácil de fazer isso que pretendo, ou se existe alguma api pronta.
Toda ajuda é bem vinda!
Comment: Possível duplicata de [Como salvar array em db?](https://pt.stackoverflow.com/questions/204760/como-salvar-array-em-db)
Comment: Por que você converte os dados JSON para Array? Por que não inserir os dados do json direto no banco de dados? É muito mais simples.
Comment: Porque tenho relacionamentos no banco de dados.
Comment: Como assim relacionamentos? Pode explicar e dar um exemplo?
Comment: por exemplo: um paciente tem um tipo e também é relacionado com pagamento. Como eu faria esse relacionamento entre eles?
Comment: esses relacionamentos você criar no próprio banco de dados. Através do Inner Join ( left join, full outer join) . Desse jeito quando você aplicar um select, você poderá obter resultados relacionados. Eu poderia responder melhor, mas isso sairia do tema da sua pergunta.
Comment: mas eu teria que ter o conceito de chaves no banco... se eu tiver uma tabela Paciente com um campo json onde salvo o json paciente, e outra tabela Pagamento tambem com um campo json onde salvo o json pagamento. caso eu precise listar todos os pagamentos que um certo paciente fez, como irei fazer esse filtro?
Comment: E acho que não foge do tema, pois você esta propondo uma nova solução para o meu problema. Pelome nos penso assim.
Comment: Então eu posso enviar uma resposta dizendo que seria melhor você utilizar o próprio objeto JSON? Eu recomendo você abrir uma nova pergunta quanto aos relacionamos de Banco de dados, porque com certeza eu vou receber uma flag se eu responder.
Comment: Acho que isso daí vai te abrir uma falha de segurança. Veja isso: [*Mass assignment vulnerability*](https://en.wikipedia.org/wiki/Mass_assignment_vulnerability) e isso: [*SQL injection*](https://en.wikipedia.org/wiki/SQL_injection).
Answer: Voce pode usar um código como este, é um modelo para vc ter uma base
<code>$campos      = implode(', ', array_keys($array));
$valores     = '"'.implode('", "', $array).'"';
$query       = "INSERT INTO $this->tabela
                              ( $campos )
                       VALUES ( $valores )";
</code>
Answer: Uma sugestão para solucionar seu problema. Você disse que precisa recuperar os valores de um JSON e que para isso deseja transforma-los em array.
Existe uma função no PHP, que recupera dados de um JSON e os transforma em objetos.
Segue um exemplo
<code>$obj = json_decode($json_recebido);

echo "nome: " . $obj->$nome . " idade: " $obj->$idade . " sexo: " . $obj->sexo;
</code>


Como utilizar Stream.reduce() de forma apropriada

Question: Meu problema: Tenho um ArrayList do tipo de Rotas (primeiro valor é o nome da cidade, segundo valor é a cidade destino e o terceiro valor a distancia),
quero criar um novo mapa organizando essas rotas em suas devidas cidades origem.
exemplo:
tenho uma lista de rotas assim = [AB6, AE4, BA6, BC2, BD4, CB3, CD1, CE7, BD8, EB5, ED7]
e o mapa final que eu quero seria {A=[AB6, AE4], B=[BA6 , BC2, BD4, BD8], C=[CB3, CD1, CE7]}
Minha lista de rotas:
List<Route> routes = new ArrayList<Route>();
            routes.add(new Route("A","B",6));
            routes.add(new Route("A","E",4));
            routes.add(new Route("B","A",6));
            routes.add(new Route("B","C",2));
            routes.add(new Route("B","D",4));
            routes.add(new Route("C","B",3));
            routes.add(new Route("C","D",1));
            routes.add(new Route("C","E",7));
            routes.add(new Route("B","D",8));
            routes.add(new Route("E","B",5));
            routes.add(new Route("E","D",7));

            Stream data = Stream.of(routes);

dessa lista que possuo tentei fazer um reduce, onde eu passo um mapa vazio e de acordo com a função que eu passei vou preenchendo este mapa, mas não to conseguindo andar...
data.reduce(new HashMap<String,List<Route>> (), (map, current) -> {
    if (map.containsValue(current.getSource()/* seria o primeiro valor da rota */)) {
                map.get(current.getSource()).add(current);
    } else {
                List<Route> x = new ArrayList<>();
                x.add(current);
                map.put(current.getSource(),x);
    }
return map;
});

isso é o que eu pensei que conseguiria fazer, mas não consegui...
Minha pergunta é:  Estou errando em utilizar o Reduce? ou é  por Reduce mesmo só estou me perdendo na lógica?
Comment: Eu acho que já tem um `Collector` que faça isso...
Comment: tem chute de algum? to com dificuldade de qual utilizar
Answer: Acredito que o que você precisa é o groupingBy. Aproveitando sua lista routes e passando como critério de agrupamento uma propriedade da classe Route, no caso, getOrigem():
Map<String, List<Route>> rotasAgrupadas = routes.stream().collect(Collectors.groupingBy(Route::getOrigem);

Comment: `Collectors.groupingBy(Route::getOrigem)` é um pouco mais simples.
Comment: Se te ajudou, marque a resposta como correta, para ajudar outros colegas no futuro.
Comment: Deu certo, Obrigado !!!! tava me tirando o sono já rs
Comment: @VictorStafusa valeu pela dica. Editado na resposta.
Answer: A resposta aceita já responde o que é importante saber sobre a questão. Porém, ainda senti uma brecha solta: e como seria usando reduce?
Preliminares
Para começar, precisamos entender quais são os tipos possíveis de reduce; os tipos são os seguintes (na frente eu pus um alias para eu poder me referir ao longo do texto):

op-reduce: Optional<T> reduce(BinaryOperator<T> accumulator)
id-merge: T reduce(T identity, BinaryOperator<T> accumulator)
map-merge:  U reduce(U identity, BiFunction accumulator, BinaryOperator combiner)

op-reduce
Essa redução é útil para quando não se há um valor neutro/identitade previamente conhecido. De modo geral, ele é idêntico ao comportamento de id-merge, exceto em um caso especial: no caso do conjunto vazio. Para o caso geral, eu prefiro explicar dentro do corpo da outra redução.
Quando o conjunto de entrada é vazio, o op-reduce retorna Optional.empty(), caso contrário retornará um Optional com o valor adequado. Você pode tratar o resultado do modo tradicional do Optional:
Stream<X> fluxo = ...;
Optional<X> reducao = fluxo.reduce((x1, x2) -> operacaoCombinaX(x1, x2));
reducao.ifPresentOrElse(x -> System.out.println("A redução é " + x), () -> System.out.println("Fluxo vazio =P");

id-merge
Aqui, a redução garante que pelo menos haja o elemento neutro. Um elemento id é considerado neutro se, para a operação op, op(id, x) ==> x, qualquer que seja x.
Essa redução sempre retornará um valor, nem que seja a identidade. Ele pode ser entendido de diversas maneiras:
T respostaReducao = identity;
for (T valorNovo: valoresDaStream) {
  respostaReducao = accumulator(respostaReducao, valorNovo);
}

Mas essa operação não precisa ser linear. Se você tiver 6 elementos e deseja reduzi-los todos, também poderia fazer em paralelo:
x1---x2  x3---x4  id---x5  id---x6
   |        |        |        |
   x7-------x8       x5-------x6
        |                 |
        x9----------------xa
                 |
                 xb

Nessa árvore de operações, cada barra vertical | é a aplicação da função accumulate para os argumentos passados.
As operações com a identidade id são tautológicas, mas as coloquei por ilustração, para todas as operações ficarem com o mesmo nível de profundidade.
map-merge
Esse mapeamento não retornará o mesmo tipo do tipo passado. Ele pode ser pensado como uma espécie de mapeamento seguido de redução. Os seguintes códigos são mais ou menos equivalentes:
Stream<X> fluxo = ...;
U id = ...;
BiFunction map2u = ...;
BinaryOperator merge = ...;

// usando diretamente a redução map-merge
U reducaoMapMerge = fluxo.reduce(id, map2u, merge);

// fazendo o mapeamento para U e usando id-merge
U reducaoIdMerge = fluxo.map(map2u).reduce(id, merge);

// fazendo o mapeamento para U e usando op-reduce, pegando identidade caso vazio
U reducaoOpReduce = fluxo.map(map2u).reduce(merge).orElse(id);

Qual o tipo de redução adequada para a questão?
A primeira coisa a se observar é o que se tem e o que se pretende retornar.

o que se tem? um fluxo de Route
o que se pretende retornar? um multimapa da chave para todas as Routes dessa chave

Como o tipo de retorno obtido é diferente do tipo de entrada, então vou para a estratégia do map-reduce. Agora, preciso estabelecer quem é o elemento neutro e quais são as funções:

quem é id? new HashMap<String, List<Route>>()
no caso, poderíamos usar o operador diamante para tratar isso mais elegantemente new HashMap<>(), mas quis deixar explícito ali quais os tipos usados
quem é accumulate? o método Map.merge parece adequado, só preciso antes transformar a nova Route passada em um List<Route> antes; ou então fazer a verificação se a chave existe e inserir no final da lista:
// usando o Map.merge
(hm, route) -> {
  List<Route> lista = new ArrayList<>();
  lista.add(route);
  hm.merge(route.getSource(), lista, (l1, l2) -> { l1.addAll(l2), return l1; });
  return hm;
};

// inspecionando se já existe a lista e, caso contrário, criando-a

(hm, route) -> {
  List<Route> lista = hm.getOrDefault(route.getSource(), new ArrayList<>());
  lista.add(route);
  hm.putIfAbsent(route.getSource(), lista);
  return hm;
};

quem é combine? esse método deve pegar dois Maps e combiná-los; posso iterar nas chaves do segundo Map e chamar algo para misturar as duas listas:
(hm1, hm2) -> {
  hm2.forEach( (k, listaRoutes) -> {
    List<Route> listaOriginal = hm1.get(k);
    if (listaOriginal == null) {
      hm1.put(k, listsRoutes);
    } else {
      listaOriginal.addAll(listaRoutes);
    }
  });
  return hm1;
};

Como fica o código?
Fica mais ou menos assim, nesse caso:
Stream<Route> fluxo = ...;
Map<String, List<Route>> mapeamento =
    fluxo.reduce(new HashMap<>(),
        /* accumulate */
        (hm, route) -> {
          List<Route> lista = hm.getOrDefault(route.getSource(), new ArrayList<>());
          lista.add(route);
          hm.putIfAbsent(route.getSource(), lista);
          return hm;
        },
        /* combine */
        (hm1, hm2) -> {
          hm2.forEach( (k, listaRoutes) -> {
            List<Route> listaOriginal = hm1.get(k);
            if (listaOriginal == null) {
              hm1.put(k, listsRoutes);
            } else {
              listaOriginal.addAll(listaRoutes);
            }
          });
          return hm1;
        }
);

Jabá: totalcross-functional-toolbox
O TotalCross por si só não dá o suporte necessário para streams do Java 8. Como o TotalCross praticamente não fornece suporte ao Java 8 (com exceções através do retrolambda e de algumas interfaces funcionais (mas não todas corretamente)), e tive a necessidade de usar stream no meu projeto, então implementei algo semelhante ao uso de streams.
Com isso, surgiu o projeto totalcross-functional-toolbox, criado aqui na empresa e disponibilizado sob a licença MIT, que entre outras coisas com a pegada mais funcional também se preocupou em implementar o que precisamos usar de Stream e de Optional.
Assim, precisei implementar o Collectors.groupingBy(Function<T, K> keyExtractor). Basicamente, uma implementação que funciona é fazer o Collectors.groupingBy chamar o Collectors.toMap transformando cada elemento individual numa lista mutável de um elemento (CollectionUtils::getSingletonList) e um método para concatenar duas listas (CollectionUtils::addAll).
Mais precisamente? Quando implementei o Collectors.groupingBy, fiz uma versão muito parecida do reduce que aqui foi feito.
Comment: @LuisFelipe minha ideia foi para ficar de referência de leitura. Eu realmente acredito que a mais correta é a do StatelessDev, eu teria respondido assim. Mas fui lento, então peguei me perguntando "e se alguém parar nessa pergunta com essa necessidade do título?", daí resolvi escrever isto daqui.
Comment: Obrigado mesmo Jefferson, a outra resposta me atendeu, mas gostei muito da sua, e o legal é que fica de conhecimento pro próximo. Parabéns.


PouchDB: Como excluir todas as bases de dados?

Question: Pela que vi na documentação do PouchDB é possível aplicar db.destroy(), porém, só na base de dados criada/escolhida.
É possível excluir todas as bases de dados (diretamente pelo PouchDB)?
Answer: PouchDB fornece um plugin para isso:
https://github.com/nolanlawson/pouchdb-all-dbs
PouchDB.resetAllDbs();

Comment: Ou mesmo sem o plug-in é possível fazer uma chamada rest para [`/_all_dbs`](https://wiki.apache.org/couchdb/HTTP_database_API#List_Databases), iterar sobre  resultado e chamar `db.destroy()` em cada um deles (provavelmente é isso que esse plug-in está fazendo).
Comment: O  [recurso rest](http://docs.couchdb.org/en/1.6.1/api/server/common.html#get--_all_dbs) continua lá. O que foi removido é a função da API, eis o motivo de existência desse plugin. Veja a nota [no manual](https://github.com/nolanlawson/pouchdb-all-dbs/blob/master/README.md) do plug-in.
Comment: Interessante, Anthony. Vou testar sua sugestão. Obrigado.
Comment: Me parece que essa funçao _all_dbs foi depreciada no PouchDB 2.0. Ou estou enganado?
Comment: Entendi. Obrigado!


Using Views as a report in a custom module

Question: I'm new-ish to module development. I just need to be pointed in the right direction.
I have a custom module that I think would benefit from a report. The report should show up in the admin reports menu. (I already know how to use hook_menu to display "Hello world!" as a report in the reports menu.)
It seems to me that the easiest way to compile the data for the report would be to use Views. But where do I go from here? How do I programatically use a View as one of the reports my module provides? (Or am I wrong in assuming that this can be done or is a good way of doing things?)
To be clear: I am not talking about my module providing a default view that shows up in the views menu, but using the data from a View as a report.
What I want is the same result as this idea, but programatically in my module.
Answer: views_get_view_result is the API you should use to query an existing View and process the results in your module.


Expected score on an increasingly multiple choice test

Question: If a multiple-choice test (where all questions are worth the same) has $n$ choices on each question, random guessing gets you a score of $\frac1n$ on average. But what if the number of choices increased as you went through the test? Let's say that the number of choices matches the question number, so question $\#3$ has $3$ choices, and question $\#5$ has $5$ choices, and so on. If this test has $n$ questions, what is the expected score for random guessing?
The way I think of it is letting each question be worth 1 point and $X_i$ represent the amount of points gained on question $\#i$. Then the expected value for $X_i$ is $$E(X_i)=0\cdot\frac{i-1}{i}+1\cdot\frac1i=\frac1i$$
So the expected value for the amount of points gained on the entire test is $$E(X)=E(X_1+X_2+\dots+X_n)$$ $$E(X)=E(X_1)+E(X_2)+\dots+E(X_n)$$ $$E(X)=1+\frac12+\dots+\frac1n=H_n$$
Since there are n points in total, the expected score is $H_n/n$.
Is this the correct way to find the expected score on the test? If it is, is there an approximation or limit for $H_n/n$?
Comment: Looks correct to me. Also, $H_n/n \to 0$ for $n \to \infty$.
Comment: What do you mean by the "expected score"? What you calculated is the expected average score per question. The expected score on the test is $H_n$.
Comment: @joriki its quite common for the "score" on a test to be a percentage, for ease of comparison with other tests.
Answer: Yes, this is correct. $H_n\sim \ln n$ as $n\to\infty$, that is, the ratio $H_n/\ln n\to 1$. One way to see this is that $\ln n=\int_1^n\frac1xdx$, and by approximating the area by $n$ rectangles you can show that $1+\frac12+\cdots+\frac1n>\ln n>\frac12+\frac13+\cdots \frac1{n+1}$, so $\ln n<H_n<\ln n+\frac{n}{n+1}$.
So $H_n/n\approx\frac{\ln n}{n}\to0$.


Erro date_diff PHP

Question: Estou fazendo um teste, com uma consulta em banco Oracle (gravando o sysdate, resultado: 13/09/2016 13:24:44) e me retornando no PHP. Preciso calcular a diferença, em horas e estava tentando a função abaixo:
$date_a = new DateTime($p_fim[$passo]);
$date_b = new DateTime($p_inicio[$passo]);

$interval = date_diff($date_a,$date_b);
echo $interval->format('%h:%i:%s');

Mas está retornando o erro abaixo:

Fatal error: Uncaught exception 'Exception' with message
  'DateTime::__construct(): Failed to parse time string (13/09/2016
  13:24:44) at position 0 (1): Unexpected character'

Pesquisando no SO mesmo todos usam o formato 2016-09-13. É isso mesmo? Preciso converter antes de passar o valor?
Comment: Sim, o `date_diff` só aceita a string de data separadas com hífen. `-`, por exemplo; `13-09-16`, realize os teste e me avise se conseguir! depois coloco como resposta!
Comment: Tente isso: ALTER SESSION SET NLS_DATE_FORMAT = '[date_format]'
Answer: Esses são os tipos suportados, segundo a documentação:
const string ATOM = "Y-m-d\TH:i:sP" ;
const string COOKIE = "l, d-M-Y H:i:s T" ;
const string ISO8601 = "Y-m-d\TH:i:sO" ;
const string RFC822 = "D, d M y H:i:s O" ;
const string RFC850 = "l, d-M-y H:i:s T" ;
const string RFC1036 = "D, d M y H:i:s O" ;
const string RFC1123 = "D, d M Y H:i:s O" ;
const string RFC2822 = "D, d M Y H:i:s O" ;
const string RFC3339 = "Y-m-d\TH:i:sP" ;
const string RSS = "D, d M Y H:i:s O" ;
const string W3C = "Y-m-d\TH:i:sP" ;

http://php.net/manual/en/class.datetime.php
O seu caso não possui um formato padronizado oficialmente, portanto, terá que fornecer um formato aceitável.
Veja um exemplo de como usar o método DateTime::createFromFormat()
$date_a = DateTime::createFromFormat('d/m/Y H:i:s', '13/09/2016 13:24:44');
$date_b = DateTime::createFromFormat('d/m/Y H:i:s', '13/09/2016 20:24:44');
$interval = date_diff($date_a,$date_b);
echo $interval->format('%H:%i:%s');

Sendo mais específico para o seu caso,
$date_a = new DateTime('d/m/Y H:i:s', $p_fim[$passo]);

Comment: Desculpe, confundi as letras. Fiz a correção na resposta.  `H:i:s`. Estava errado como `H:m:i`
Comment: Boa Daniel. Só fiz um ajuste aqui: echo $interval->format('%h:%m:%i'); Ai exibiu bem certo. Muito obrigado!
Comment: Daniel, na virada de hora ocorre a situação abaixo, sabe como posso resolver?  D1 = 13/09/2016 14:46:12  d2 = 13/09/2016 15:00:41  DIFERENCA = 22:9:31

Erro date_diff PHP


How to show the cardinality $0$ is less than the cardinality $1$

Question: I know that to show this I have to show there's an injection from the $\varnothing$ to $\{\varnothing\}$.
But how can one even define a function on the $\varnothing$?
Comment: No, the formal definition.
Comment: What's the definition of a function?
Comment: Recall the definition of "function from $X$ to $Y$": A set $f\subset X\times Y$ such that for every $x\in C$ there exists exactly one  $y\in Y$ with $(x,y)\in f$. It follows that if $A$ is any set then $\emptyset$ is an injective function from $\emptyset$ to  $A$.
Comment: No, you're right. A function on A has to contain an ordered pair with first element a for each a in A, so there's no "empty function" on a non empty set. But there is an empty function on the empty set.
Comment: A mapping from one set to another
Comment: Of course, it is the empty function; $\;\varnothing\times\{\varnothing\}$ is the empty set.
Comment: Formally, a function f from a set X to a set Y is defined by a set G of ordered pairs (x, y) such that x ∈ X, y ∈ Y, and every element of X is the first component of exactly one ordered pair in G.
Comment: But if $X$ = emptyset then there is no $x \in X$
Comment: In the past I thought there exists a unique  $f:A \rightarrow {1}$ defined by $a \rightarrow 1$ for all $a \in A$ where $A$ is non-empty set. Does the emptyset function mean I am wrong and that $f$ is not unique.
Comment: "But if X = emptyset then there is no x∈X" EXACTLY!   So for any $b \in Y$ there is no $(x,b) \in \emptyset \times Y$.  And if there are $0$ such $(x,b)$ then there can not be more than one! So $\emptyset: \emptyset \to Y$ is injective because for every $y \in Y$ there is at most one (in fact there are zero) $(x,y) \in \emptyset \subset \emptyset \times Y$.
Comment: "In the past I thought there exists a unique f:A→1 defined by a→1 **for all** a∈A where A is non-empty set. "  And that is true **FOR ALL** $a\in \emptyset$.  That is trivially and vacuously true for all $a \in \emptyset$ because there aren't *ANY* $a\in \emptyset$.
Answer: A function, $f:X\to Y$ is a subset of a cartesian product, $X\times Y$ where each element $a \in X$ is "represented" precisely once.
$h:\emptyset \to \{\emptyset\} \subseteq \emptyset \times \{\emptyset\} = \{(x,y)|x \in \emptyset, y \in \{\emptyset\}\}$.  But as $\emptyset$ is empty $x \in \emptyset$ is impossible so so $\emptyset \times \{\emptyset\} = \{(x,y)|x \in \emptyset, y \in \{\emptyset\}\} = \emptyset$.
So $h= \emptyset$.  Is $\emptyset$ injective?  What does that mean?
$f\subseteq X\times Y$ is injective if for any $b\in Y$ there is at most one $(x,b)\in f$.
So for any $b \in \{0\}$ how many $(x, b) \in h = \emptyset$.  Well, zero as $h$ is empty.  So is there at most one?  Well, there sure as heck aren't more than one!
....
The emptyset is always an empty function from $\emptyset \to $ any set $X$ and it is vacuously injective.
Vacuous statements are, admittedly, irritating and confusing and you have my empathy.  If it helps, you can put a mental close in most definitions as "An $x$ is GLOOP if when it exists GOBBLETY occurs.  And when it doesn't exist it is GLOOP by default.  That's kind of cheating but it helps.
The old stumbling block is "Every element in the emptyset is red".  That is true.  Every element of the emptyset, all zero of them, are red because there aren't any elements.  But if we say "Every element in the emptyset, if it exists, is red" that's very clear.  Unfortunately it's inaccurate because the element doesn't exist.... well, it's still technically accurate to say it is red.... sigh... it gets easier.
Althernatively,  Every element is GLOOP $\iff $ there is no element that is not GLOOP.  It's very clear that the RHS is always true for an emptyset as there no elements at all.
Comment: What's confusing me is my definitions of injectivity have always involved elements in the domain... of which there aren't any now!
Comment: Why have you written h to be a proper subset in line 3?
Comment: Right.... but that makes *all* (postive) statements vacuously true.  "If $a \in \emptyset$ then $a$ is GLOOP."  That *must* be true because 1) a false hypothesis ($a\in \emptyset $ is always false) leads to *any* conclusion, and 2) there is not counterexample:  There are no $a\in \emptyset$ where $a$ *isn't GLOOP. ... admittedly empty functions are hard to imaging but... well think of it like this... there aren't any elements of $\emptyset$ that *aren't* being mapped to $Y$ so all elements of $\emptyset$ *are* being mapped to $Y$...
Comment: "Why have you written h to be a proper subset in line 3?"  Notation varies by from person to person and text to text but, I, me, fleablood, do not consider $\subset$ to mean proper subset.  If I wish to indicate proper subset, I would write $\subsetneq$.  However, if I were writing in pen, if a wanted subset possibly not proper, I'd write $\subseteq$.  But when I write in mathjax, I think "subset" so I write \$\subset\$ which comes out $\subset$.  Sorry if that is confusing.
Comment: That's ok. One more question. Is the function from the empty set to the emptyset then injective also by your reasoning
Comment: Yes..... $h: \emptyset \to Y = \emptyset$ is an injective (empty) function for all $Y$.  Even if $Y = \emptyset$.  Worth noting that $h: \emptyset \to Y$ is *never* surjective (obviously) *unless* $Y$ is empty.  Then $h: \emptyset \to \emptyset $ is bijective (vacuously).
Comment: This is hard to understand but thanks.
Comment: @Anteater23. I've tried an explanation below, with an emphasis on the logical aspect of the problem.
Answer: General idea: in order 2 conditions to be both satisfied, it is already necessary the first one to be satisfied.
So if non-injectivity requires 2 conditions and if the first one cannot be satisfied, non-injectivity does not hold , and therefore, automatically , injectivity holds.

Let f be a function from  {  }  to  { {  } }.
Let me " define" f arbitrarily like this : for all x, f(x) = 2x.
Now, whatever its " definition" may be, f is a relation, and therefore, in this case, a subset of the cartesian product :
<code>                 "{  }  cross { {  } }"
</code>
that is , the set of all pairs (x,y) such that (1) x belongs to Empty Set and (2)  y belongs to { {  }  }.
But, since condition (1) cannot be satisfied, a fortiori, there is no pair that satisfies both conditions, so my cartesian product is the Empty set.
I know that function f, that is a relation,  is a subset of a cartesian product that is empty. But the only subset of the empty set is the empty set itself. So : function f such that f(x)=2x is identical to the Empty set.
( That would have been true whatever formula I would have used to  "define" f).
Now, is f injective?
I know that f is injective just in case :
IF a pair (a, c) belongs to f ( whatever this pair may be)  , THEN there is no pair ( b, c) belonging to f with element a different from  element b.
( indeed, if we had at the same time (a, c) and ( b,c) with a different from b, then 2 diffetent elements of the domain would have the same image, and f would not be injective).
You know that a statement of the form (P --> Q) is false just in case P is true and Q is false. Let's apply this logical fact to our definition of injectivity which is an IF...THEN statement.
Let's see whether it is possible for f not to be injective.
For f NOT to be injective , it would be required that :
(1) there is actually a pair (a, b) belonging to f [ this is the " P is true" part]
AND
(2) there is ( at least) a pair (b, c) belonging to f with a different from b  [ this is the "Q is false" part, for, remember, Q was " there is no pair..." ]
But it is impossible that both consitions hold, since it is already impossible the first one to hold: f being empty, there is no pair (a,c)  that belongs to f, since there is nothing that belongs to f.
So the proposition " f is NOT injective" is FALSE ( and even necessarily false).
Consequently, the proposition " f is injective" must be true.


Can I do a T Test using percentages derived from 2 groups who took a survey?

Question: let's suppose I'm using a 4 point likert scale that I personally don't want to use but have to because I do not have the time to create a new one. And let's say it has 10 items. After participants have already responded, I manipulate the first two points "strongly disagree and disagree" into one point "disagree" and then agree and strongly agree into another point "agree". After this, I find an overall percentage for each item and for each group. So let's say 72% of group 1 agreed with items and 50% of group 2 agreed with items.
Would it be OK to do a T-Test to see if there is significant difference between the two percentages? If not, what would be the appropriate test to do in this scenario?
For some reason, I'm thinking something along the lines of chi square because of percentages but not totally sure why that would be, if that's correct, or how to conduct it.
Any help would be much appreciated.
Also, what would be the easiest way to statistically analyze this data to test if one group is significantly different than the other after manipulating the data the way I did?...as compared to the most acceptable way.
Comment: Please don't add to your question in comments. If you want to add followup questions, edit the original or post a new question
Comment: He probably won't see your comment. Post it under his answer and he'll be notified of your response.
Answer: If your scale has 10 items, you can count percentage of "agree" answers for each person. You'll get set of values for group 1 (say, first person agrees with 10% of items, second with 40% and so on) and another set for group 2. You can compare these two sets with t-test. But, be sure to check assumption of this test: data should follow normal distribution in both groups (separately in group 1and in group 2!) and variances in both gropus should be equal.
You can check normality assumption with Shapiro-Wilk, Kolmogorov-Smirnov, Lilliefors or any other normality test (remember to apply it twice: to data from group 1, and then to data from group two). Homogeneity of variances can be checked with F, Bartlett test (these two require normality) or Levene test (this one does not).
If all the assumptions are met, you can do t-test. If normality holds but variances are significantly different you can apply Welch correction to t-test. Otherwise you can move to nonparametric procedures like Wilcoxon two sample test (also known as Mann-Whitney-Wilcoxon test).
Another option, which IMO is not perfect, is to go with chi-squared test. For this you have to count overall number (not percent!) of "agrees" and "disagrees" in both groups, create contingency table and run chi-squared test on it.
Why I think it is not perferct? Because it treats every single answer as it was independent from any other, which is not true. 10 answers from the same person don't have to be independent. And even shouldn't be, if you scale is reliable.
Comment: Why is using a formal hypothesis test to check normality a good idea?
Comment: Beacuse it's formal :) QQ-plots and histograms are sometimes hard to interpret (at least for me)
Comment: It's a formal answer to a question we already know the answer to (count percentages are bounded and discrete, so they cannot possibly be normal  -- why get the wrong answer to that question at small sample sizes when you already know the answer?) ... and it's also not even the question we *want* to answer. We're concerned about the *impact* of the non-normality we know we have (which is worse at small samples, not large samples --- but we will tend to mostly reject normality in larger samples, when it doesn't impact the test we wanted to do very much at all). ... ctd
Comment: OK, I forgot about "10 items". You're right, we don't need normality check here. Data are not normal. But if there were plenty of items, percentages could behave like normal variable, even if they are indeed bounded.
Comment: ctd ... That is, we will tend to formally reject in just those situations where the amount of non-normality we have matters the least.
Comment: Sorry, was still clarifying my comment when you replied. Yes, you're right that with a lot of items the behavior of the test may be perfectly okay ... hypothesis tests can't help us with that sort of judgement; in fact they tend to tell us the opposite (again, we'll more often reject at large sample sizes, which is often the opposite of what we need to be doing with these sums of (presumably correlated within one person's answers) Bernoulli's with varying $p$'s - it's small sample sizes we need to be cautious of).
Comment: So, can you suggest any framework for general situation of $N$ items?
Comment: Sorry, I'm unsure what you mean by "framework" there.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/62497/discussion-between-lukasz-derylo-and-glen-b).
Comment: Thanks for your thought-out answer, Łukasz Deryło. Now, I'm just having a problem with that first part. My understanding is still a bit off, and I'm just trying to piece it together. So you said "say, first person agrees with 10% of items, second with 40% and so on". Do I get the average percentage of both groups and compare the difference between those percent averages? I'm just thrown off by you saying you need the set values for each person for group one instead of saying an average percent value for group one, an average percent value for group 2 and then comparing them.
Comment: To calculate t test statistic you need standard deviations in both groups, not only means. That is why you need percent of "agrees" for each person.


Can't get a basic method to work

Question: Can anyone please tell why the getSpeed method does not work ?
Whenever I hover over the method I get the :
to insert ;
illegal modifier
syntax error please insert []
syntax error on token
public class Tanks {

private String TankName;
private int TankModel;
private int CrewNumber;
private double Speed;
private int TurretSpeed;

Tanks (String name, int model, int crew, double speed, int turretspeed){

    this.TankName = name;
    this.TankModel = model;
    this.CrewNumber = crew;
    this.Speed = speed;
    this.TurretSpeed = turretspeed;

}

public static void main(String[] args) {

    Tanks merkava = new Tanks ("MERKAVA", 1, 5, 56.64, 67);
    Tanks judge = new Tanks ("JUDGE", 2, 6, 66.66, 68);

    public double getSpeed() {
        return Speed;
    }

    System.out.println(merkava.TankName+ " "+merkava.TankModel+" "+merkava.CrewNumber+" "+merkava.Speed+" "+merkava.TurretSpeed);
    System.out.println(judge.TankName+ " "+judge.TankModel+" "+judge.CrewNumber+" "+judge.Speed+" "+judge.TurretSpeed);

}
}

Comment: You don't declare methods inside other methods' bodies.
Comment: also, you try to access private attributes directly in those println. You need to use accessors.
Comment: Apart from the fact that you can't declare one method inside another, you're never actually calling the `getSpeed` method.
Answer: Your main method contains the following method.
 public double getSpeed() {
        return Speed;
    }

Please move this to Tanks class.
Following should work:
public class Tanks {

private String TankName;
private int TankModel;
private int CrewNumber;
private double Speed;
private int TurretSpeed;

Tanks(String name, int model, int crew, double speed, int turretspeed) {

    this.TankName = name;
    this.TankModel = model;
    this.CrewNumber = crew;
    this.Speed = speed;
    this.TurretSpeed = turretspeed;

}

public double getSpeed() {
    return Speed;
}

public static void main(String[] args) {

    Tanks merkava = new Tanks("MERKAVA", 1, 5, 56.64, 67);
    Tanks judge = new Tanks("JUDGE", 2, 6, 66.66, 68);

    System.out.println(merkava.TankName + " " + merkava.TankModel + " " + merkava.CrewNumber + " " + merkava.Speed
            + " " + merkava.TurretSpeed);
    System.out.println(judge.TankName + " " + judge.TankModel + " " + judge.CrewNumber + " " + judge.Speed + " "
            + judge.TurretSpeed);

}
}

Comment: I moved it no more errors, but no answer just the ones from the 2 System.out.println
Comment: Attributes are private. They should be called through accessors in those println
Comment: @lupul666 what did you expect apart from the two `print` statements.
Comment: I'm getting following `o/p`
`MERKAVA 1 5 56.64 67`
`JUDGE 2 6 66.66 68`
Comment: I think its printing speed, no?
Comment: i thought that   the method would also do that :S
 public double getSpeed() {
        return Speed;
    }
Answer: If you have gone through some basic Java course you will know that by defining a method (in this case getSpeed()) inside another function (main) is wrong.

Can't get a basic method to work