Find $f$ for $x\frac{\partial f}{\partial x}+y\frac{\partial f}{\partial y}=x^2+y^2$

Question:
$$x\frac{\partial f}{\partial x}+y\frac{\partial f}{\partial y}=x^2+y^2$$

Moving to polar we have $$r\cos \theta\frac{\partial f}{\partial x}+r\sin\theta \frac{\partial f}{\partial y}=r^2$$
We know that:
$$\frac{\partial f}{\partial x}=\frac{\partial f}{\partial r}\frac{\partial r}{\partial x}+\frac{\partial f}{\partial \theta}\frac{\partial \theta}{\partial x}$$
$$\frac{\partial f}{\partial y}=\frac{\partial f}{\partial r}\frac{\partial r}{\partial y}+\frac{\partial f}{\partial \theta}\frac{\partial \theta}{\partial y}$$
In our case we have $$\frac{\partial f}{\partial x}=\frac{\partial f}{\partial r}\frac{2x}{2\sqrt{x^2+y^2}}+\frac{\partial f}{\partial \theta}\frac{\frac{-y}{x^2}}{1+(\frac{x}{y})^2}=\frac{\partial f}{\partial r}\cos \theta-\frac{\partial f}{\partial \theta}\frac{\sin \theta}{r}$$
and for $$\frac{\partial f}{\partial y}=\frac{\partial f}{\partial r}\frac{\partial r}{\partial y}+\frac{\partial f}{\partial \theta}\frac{\partial \theta}{\partial y}=\frac{\partial f}{\partial r}\sin \theta\frac{\partial f}{\partial \theta}\frac{\cos \theta}{r}$$
Do I need to assign to $$x\frac{\partial f}{\partial x}+y\frac{\partial f}{\partial y}=x^2+y^2$$ both $\frac{\partial f}{\partial y}$ and $\frac{\partial f}{\partial x}$ for both $r$ and $\theta$?
Answer: A solution is $f(x,y)= (x^2+y^2)/2$. If you want obtain one solution, you can separated the variables and solve the system $x\frac{\partial f}{\partial x}=x^2$ and $y\frac{\partial f}{\partial y}=y^2$.
Comment: But then I can say $\frac{\partial f}{\partial x}=x$ and $\frac{\partial f}{\partial y}=y$ ?
Comment: Yes, and integrate in both sides
Comment: I don't mean "separation of variables" method for solve differential equations
Comment: $x\frac{\partial f}{\partial x}=x^2+C$ and $y\frac{\partial f}{\partial y}=y^2-C$ ($C$ is a constant) would be better.
Answer: $$x\frac{\partial f}{\partial x}+y\frac{\partial f}{\partial y}=x^2+y^2$$
With change of variables $\begin{cases} X=x^2 \\ Y=y^2 \end{cases}$ $\quad\to\quad 2X\frac{\partial f}{\partial X}+2Y\frac{\partial f}{\partial Y}=X+Y$
If the goal is to find not only particular solutions, but a general solution, the method of characteristics is recommended.
The related characteristic equations are :
$$\frac{dX}{2X}=\frac{dY}{2Y}=\frac{df}{X+Y}$$
A first characteristic is derived from $\frac{dX}{2X}=\frac{dY}{2Y}\quad\to\quad \frac{Y}{X}=c_1$
A second characteristic is derived from $\frac{dX}{2X}=\frac{dY}{2Y}=\frac{dX+dY}{2(X+Y)}=\frac{df}{X+Y}\quad\to\quad f-\frac{X+Y}{2}=c_2$
The solution expressed on implicit form is :
$$\Phi\left(\left(f-\frac{X+Y}{2}\right)\:,\:\left(\frac{Y}{X}\right)\right)=0$$
where $\Phi$ is any differentiable function of two variables.
This can be expressed on explicit form :
$f-\frac{X+Y}{2}=$ any derivable function of $\left(\frac{Y}{X}\right)=\left(\frac{y}{x}\right)^2$ or equivalent to any derivable function of $\frac{y}{x}$
The general solution is :
$$f(x,y)=\frac{x^2+y^2}{2}+F\left(\frac{y}{x}\right) $$
where $F$ is any derivable function.
Note that $F\left(\frac{y}{x}\right)$ can be replaced by $G\left(\frac{x}{y}\right)$ or many equivalent forms.
In polar coordinates $\begin{cases} x=\rho\cos(\theta) \\ y=\rho\sin(\theta)\end{cases} \quad\to\quad \frac{y}{x}=\tan(\theta)\quad$
and $F\left(\tan(\theta)\right)$ can be replaced by $G(\theta)$
$$f(\rho,\theta)=\frac{\rho^2}{2}+G(\theta)$$
where $G$ is any derivable function.
Alternatively, one can transform the Cartesian PDE to a Polar PDE :
$$x\frac{\partial f}{\partial x}+y\frac{\partial f}{\partial y}=x^2+y^2=\rho \frac{\partial f}{\partial \rho}=\rho^2$$
$$\frac{\partial f}{\partial (\frac{1}{2}\rho^2)}=1\quad\to\quad f=\frac{1}{2}\rho^2+G(\theta)$$
Answer: in $\mathbb R^2$ in the vector form you can write:
$$\vec r \cdot \vec {\nabla f}=\vec r \cdot \vec r$$
where $ \vec r = (x,y)$
then you can get $$\vec {\nabla f}=\vec r+k\vec r_p$$
where $\vec r_p$ is vector perpendicular to $\vec r$ which is just one possible vector cause we are in $\mathbb R^2$ of dimension 2 and k is an arbitrary coefficient; $\vec r_p=(y,-x)$
or in other words: $$\frac{\partial f}{\partial x}= x+ky$$
$$\frac{\partial f}{\partial y}= y-kx$$
for finding simplest solution we set $k=0$. so by a simple integration you find $f(x,y)=\frac{(x^2+y^2)}{2}+C$
Comment: It's a nice observation. However $a\cdot b = a\cdot a$ does not imply $b = a$ but rather that $b = a + c$ where $c$ is any vector that is orthogonal to $a$, i.e. $a\cdot c = 0$. Thus this is not the most general solution.
Comment: that's true and thanks for feedback.
Answer: $$
(x,y)\cdot\nabla f=(x,y)\cdot(x,y)
$$
gives one solution to be $f(x,y)=\frac12r^2$. The other solutions would differ by a solution to
$$
(x,y)\cdot\nabla g=0
$$
that is, $g$ does not change in the radial direction. Thus, $g$ is simply a function of $\theta$, the angle of $(x,y)$.
Thus, the general solution is
$$
f=\tfrac12r^2+u(\theta)
$$
Answer: Solve PDE
$$x\frac{\partial u}{\partial x}+y\frac{\partial u}{\partial y}=x^2+y^2\qquad\quad (1)$$

After change $\;x=e^\xi,\; y=e^\eta\;$ we get
$$\frac{\partial u}{\partial \xi}+\frac{\partial u}{\partial \eta}=e^{2\xi}+e^{2\eta}.\qquad (2)$$
Particular solution of $(2)$ is $$u_p=\frac{e^{2\xi}}{2}+\frac{e^{2\eta}}{2}.$$
Solution of $\;\frac{\partial u}{\partial \xi}+\frac{\partial u}{\partial \eta}=0\;$ is $u_c=f(\xi-\eta)$.
Then general solution of $(1)$ is
$$u=u_c+u_p=f(\xi-\eta)+\frac{e^{2\xi}}{2}+\frac{e^{2\eta}}{2}\\=
f(\log x-\log y)+\frac{x^2}{2}+\frac{y^2}{2}\\=f\left(\log\frac xy\right)
+\frac{x^2}{2}+\frac{y^2}{2}\\=
F\left(\frac xy\right) +\frac{x^2}{2}+\frac{y^2}{2}
$$


How can I tell if Netbeans 7.3 and Symfony2 is working properly?

Question: I have recently followed the common advice found on the internet on how to install Symfony2  in Netbeans 7.3 by pointing the configuration to the Symfony2 standard edition zip file.
Now I'm following the book on the Symfony website to create the HelloBundle demo, and I'm noticing some inconsistencies.
First, when running a Symfony command in Netbeans, the generate bundle does not work as the book says it should. It forces me to use the --dir option. Here are the parameters I had to add:
<code>--namespace=Acme/HelloBundle --format=yml  --dir=src
</code>
Secondly, I see the routing file that was created, but the route parameters are different than what the book says. First the term "Pattern" is used instead of "Path." Further searching indicates that "Pattern" is an obsolete term and that "Path" is preferred now. If this is the case, then why is "Pattern" showing up in my files if I'm using the most current version of the framework (2.3.1)?  Also, my routing file has the word "Default" in it while the book has "Hello." Here is a copy of the output.
<code>acme_hello_homepage:
    pattern:  /hello/{name}
    defaults: { _controller: AcmeHelloBundle:Default:index }
</code>
Finally, the book is unclear as to whether or not creating the bundle also automatically creates the controller files. Is this the case? I do not have "HelloController.php" file the books says I should be editing.
I'm new to Symfony, but this feels a little off. If that's the case how do I configure it to work as it should?
Answer: I'm using Netbeans as IDE for my symfony 2.x projects, i can't tell what's the problem with your Netbeans configuration, but here's a guide that can help setting-up things :)
http://software-talk.org/blog/2012/06/symfony2-tutorial-netbeans-and-symfony2-setting-everything-up/
Hope it helps.
Comment: ... from that post, "I experienced some problems if I did not place the zip inside the project folder before creating the project, so I would suggest to do it that way."  ... I had left my file in the downloads folder. This was my problem. If yours is working correctly, did you download the zip file to your project folder as well?
Comment: Not inside my project directory, but I use this patterns in my computers to organize my projects folder.
I have a directory named D:\Projects each project is stored in his own directory inside the 'D:\Projects' and the symfony zip is inside D:\Projects.


rpcinfo: couldn't find a suitable transport

Question: After setting up NFS on a server, rpcinfo -p servername from a client is returning the error message
rpcinfo: couldn't find a suitable transport

Connectivity is fine, checked with tcpdump.
On the server hosts.allow contains the necessary entries. /etc/netconfig contains the following
# This config file is part of some non-installed packages (like nfs-utils)
#
# In case you install a tool that requires this file, please comment out the following lines:
#
# from https://highon.coffee/blog/security-harden-centos-7/
#
# udp6       tpi_clts      v     inet6    udp     -       -
# tcp6       tpi_cots_ord  v     inet6    tcp     -       -

udp        tpi_clts      v     inet     udp     -       -
tcp        tpi_cots_ord  v     inet     tcp     -       -
#udp6      tpi_clts      v     inet6    udp     -       -
#tcp6      tpi_cots_ord  v     inet6    tcp     -       -
rawip      tpi_raw       -     inet      -      -       -
local      tpi_cots_ord  -     loopback  -      -       -
unix       tpi_cots_ord  -     loopback  -      -       -

Any ideas?
Answer: The problem, believe it or not, was caused by the blank line after the main comment block in the file /etc/netconfig. After removing the blank line, the mount worked.


hyper-v availability group

Question: We are setting up SQL AG's (availability groups) on Hyper-V. We want to use SQL Server for HA and DR. IE:- We want SQL Server to perform failovers between SQL replicas, we don't want SQL and Hyper-V trying to failover at the same time.
I'm not familiar with Hyper-V so excude my ignorance, but how to I configure a SQL Server VM to NOT startup after the node it is running on Fails?
Eg:-
Primary   replica on Node-1,
Secondary replica on Node-2.
Node-3 is non-SQL
If Node-1 fails, I want SQL to failover to Node-3 (It can't failover to Node-2 due to anti-affinity rules)
Monitoring will raise an alert. We then migrate the previous primary replica running on Node-2 to Node-3.
When Node-1 is available, we migrate back.
Many Thanks,
Answer:
but how to I configure a SQL Server VM to NOT startup after the node it is running on
  Fails?

Why do you care? This isa situation a HA AG in SQL Server has to ahndle - what if you do not use vm's but 2 servers and one gets a second long power outage and then restarts?
As long as both VM's are on 2 physical machines (i.e. Hyper-V nodes) this is not a situation that should bother you at all.
If properly set up, you will get Hyper-V restarting the node and SQL Server failing over, but both will not fall back and the server should work without any issues anyway.
That means that in this case you issue is a non-issue and the only answer is not to care.
Alternatively you do not set up the Hyper-V part on an availability group. Not sure that 2 SQL AG instances on ONE PIECE OF CLUSTER make any sense - I would prefer anything larger in hardware with very well planned disc storage.
Comment: Thanks for the response. We have 4 cluster nodes. I don't want SQL Server potentially failing over at the same time as Hyper-V fails over. Due to node /network utilisation/storage utilisation etc, each could interfere with the other, this would make troubleshooting/diagnostics more difficult. I think its better to simply let SQL Server handle the failover to the secondary replica.. We can then migrate the failed original primary to another node (so we one agaian have a HA pair) - Note we have a ASYNC replica in another data centre.
Comment: Seriously, if you have problems with this your network is TREMENDOUSLY too small to handle the load of a proper SQL Serer to start with.

hyper-v availability group


Parallel ForEach Giving different results in different ocasions

Question: I have never used Parallel.ForEach but I played around with it and found this occurrence.
I run a parallel loop (code found on msdn https://msdn.microsoft.com/en-us/library/dd997393(v=vs.110).aspx did edit it with the subtotal *=2 to try understand what it is doing) with an enumerable range firstly (0,1) and then (0,1,2) then I run the second one again but after sleeping the thread for 200 milliseconds, and the result then differs
if the Thread.sleep(200)is not commented out this is the results
result 1 = 2
result 2 = 6
result 3 = 4

if the Thread.sleep(200)is commented out this is the results
result 1 = 2
result 2 = 6
result 3 = 6

Here is the code
Stopwatch timer = new Stopwatch();
int[] nums = Enumerable.Range(0, 1).ToArray();
long total = 0;
for (int i = 0; i < 2; i++)
{
     timer.Restart();
     total = 0;
     if (i == 0) nums = Enumerable.Range(0, 1).ToArray();
     if (i == 1) nums = Enumerable.Range(0, 2).ToArray();
     Parallel.ForEach<int, long>(nums,() => 0,(j, loop, subtotal) =>
     {
       subtotal += 1;
       subtotal *= 2;
       return subtotal;
     },(finalResult) => Interlocked.Add(ref total, finalResult));

     Console.WriteLine("The total from Parallel.ForEach is {0:N0} and took {1}", total, timer.Elapsed);
     timer.Stop();
     //Thread.Sleep(200);
}

timer.Restart();
nums = Enumerable.Range(0, 2).ToArray();
total = 0;
Parallel.ForEach<int, long>(nums, () => 0,  (j, loop, subtotal) =>
{
    subtotal += 1;
    subtotal *= 2;
    return subtotal;
},(finalResult) => Interlocked.Add(ref total, finalResult));

Console.WriteLine("The total from Parallel.ForEach is {0:N0} and took {1}", total, timer.Elapsed);
timer.Stop();

I figured it has got to do with threads working over one another but this seems like a bug
Note I did have a look at Simulation gives different result with normal for loop Vs Parallel For
Why is this happening?
Comment: @JánЯabčan Can you please elaborate. I dont understand what this code is doing when is it multiplying 2 and why?
Comment: I don't even understand how you get your results...
Comment: @sam change your thread.sleep to 1000 and see if you get it then
Comment: i don't understand what variable should i watch to see the results 2,6,4 or 2,6,6
Comment: @sam copy this code in a console application and run it... it is the total variable. if you are stepping through the code you are creating your own thread.sleep which means you will never see the 2,6,6 result
Answer: Because this code is ill-defined:
 Parallel.ForEach<int, long>(nums,() => 0,(j, loop, subtotal) =>
 {
   subtotal += 1;
   subtotal *= 2;
   return subtotal;
 },(finalResult) => Interlocked.Add(ref total, finalResult));

In that, if a single thread executes both iterations then you get the result 6. Effectively, you do:
subTotal = 0; //From init
subTotal += 1; //=1 First iteration
subTotal *= 2; //=2 First iteration
subTotal += 1; //=3 Second iteration
subTotal *= 2; //=6 Second iteration
total += subTotal; //=6 End gathering (actually interlocked)

But if two threads share the work, you get
subTotal1 = 0; //From init
subTotal2 = 0; //From init
subTotal2 += 1; //=1
subTotal1 += 1; //=1
subTotal1 *= 2; //=2
subTotal2 *= 2; //=2
total += subTotal1 //=2 End gathering 1 (interlocked)
total += subTotal2 //=4 End gathering 2 (interlocked)

Comment: @Neil - I'm not sure what your question is. But, if you're using a variant of `Parallel.ForEach` that uses local state, a function that mutates local state and a final action that gathers all results and merges them, it only makes sense to do so if you'll get consistent results irrespective of how many threads are operating (so how many copies of the local state will exist) and how the results are merged in the final action. You had a calculation that doesn't work like that - it's critical in how many threads are being used and hence how many copies of local state exist.
Comment: Thank you for the explanation. so just to make sure i understand this correctly parallel foreach should never be used for calculations it is then used where each iteration has its own execution not for values that get sent to the next iteration?
Comment: That is what i was asking :). thank you for your answer and clarification. up-voted and accepted
Comment: @neil you *could* write one that does that (I've seen people do it in production code), but there is no point since you'd essentially be forcing it to be de facto single threaded.
Comment: @Taekahn Yeah that makes sense. this is what i understood on Damien's explanation
Comment: @Damien_The_Unbeliever one last question. if i would to use this concept  to call a webservice for each client and the server could manage those in-sync requests and responses, the threads will be able to isolate and independently manage each cllients information?


Javascript / JQuery - How do I find the size of this array of objects?

Question: I have this code to iterate through an array of objects:
for (vehicleIndex in scenes[sceneID].vehicles) {
  vehicleID = scenes[sceneID].vehicles[vehicleIndex];
  ...
}

but I need to know how to determine the number of items being iterated through so that on the final item, I can execute a particular function. How do I do this?
Answer: Example in ES5:
Object.keys( scenes[sceneID].vehicles ).forEach(function( vehicle, index, arr ) {
    if( index === arr.length - 1 ) {
        // do something on last entry
    }
});

Even tho, "last" just means the last element which was looped over. Since there is specific order within a Javascript object (they are infact unordered). However, we could sort the object key names manually by just chaining a .sort() before the .forEach()
Comment: The "default sorting" is also implementation specific as objects are bags of un-ordered keys (hence not associative arrays)
Answer: var arraySize = scenes[sceneID].vehicles.length;
var i;
var currentItem;
for (i = 0; i < arraySize; i++) {
  currentItem = scenes[sceneID].vehicles[i];
  if (i == arraySize - 1) {
    // do something special
  } else {
     // do something not so special ;-)
  }
}

Answer: scenes[sceneID].vehicles should have a length property.
Answer: Use this to find the length:
scenes[sceneID].vehicles.length

length is a built-in property in arrays. However, if you want to check for the last item, you have to check
scenes[sceneID].vehicles.length - 1

as arrays are zero-indexed.
Also, you should not use for...in to loop on arrays - if someone extends Array.prototype (or worse, Object.prototype), then you will not be happy. Use a normal for loop (which also allows you to use the final item easily):
var len = scenes[sceneID].vehicles.length;
for (var vehicleIndex = 0; vehicleIndex < len; vehicleIndex++) {
  vehicleID = scenes[sceneID].vehicles[vehicleIndex];
  //...
}
//Do something with the final item here
//Similar to this: itemFunc(vehicleID);

See this SO question for more details.
Comment: for...in can be used safely if you have an if statement to check if the property belongs to the object in question or it was inherited (.hasOwnProperty())
Comment: @jbabey True. However, the order of iteration is undefined, and the final item cannot be reliably accessed after the loop if you do that: http://stackoverflow.com/questions/280713/elements-order-for-in-loop-in-javascript
Answer: for (vehicleIndex in scenes[sceneID].vehicles) {
  vehicleID = scenes[sceneID].vehicles[vehicleIndex];
  ...
}
doSomethingWithLastItem(vehicleId);

Because JS does not have block scope, by the time your loop finished vehicleId will be the last item's id.
In generic terms you can get the size of an array by accessing the .length property. You can also get the size of an object using Object.keys(obj).length.


Set site URI for drush uli without 'default'

Question: Versions discussed: Drupal 8.6.13, Drush 9.6.1.
This is somewhat similar to How to have an environment specific drush.yml? except that the other thread is now four or five months out-of-date and Drush 9.6.1 doesn't seem to respect the drush.yml anymore.
I'm just trying to set my Site URI.
As detailed in that thread, I've tried web/sites/default/drush.yml as well as many other locations for the drush.yml, done a drush cc drush, and yet drush status still reveals an incorrect Site URI of http://default, showing that it is not respecting the uri: line in any of my drush.yml files.
To complicate matters, I'm using DDEV, so following up on some suggestions that I've gotten from the Drupal Slack that we should really be using an environment variable (namely DRUSH_OPTIONS_URI) have proven tricky, as I'm not exactly sure where that goes inside of the DDEV environment.
Inside the DDEV container, if I do export DRUSH_OPTIONS_URI=http://my.ddev.local/ then everything works great, but once I quit the container or try to do things from outside it, such as ddev exec drush uli, things are back to the incorrect Site URI.
How can I persist this environment variable across restarts of DDEV/Docker?
Answer: I'm writing this up for posterity, since the Slack is relatively ephemeral. Here's the current method, following Providing custom environment variables to a container:
In e.g. .ddev/docker-compose.environment.yml put the following:
version: '3.6'

services:
  web:
    environment:
      - DRUSH_OPTIONS_URI=http://my.ddev.local

Then ddev rm and ddev start to prove to see it working. (This works for drush uli inside the container, after ddev ssh.)


Is $f(x) = e^{−∥x∥^2}$ with $x∈R^n$ concave?

Question: Is $f(x) = e^{−∥x∥^2}$ with $x∈R^n$ concave?
According to my calculations the $e^{-x}$ is convex, the norm is also convex. Then the whole function is convex.
However, when I plot a visual graph in 2D, this function is concave (looks like a multivariate Gaussian).
And here https://math.stackexchange.com/a/1972485/539984 they say that it is nor neither not convex, however, I do not understand the proof. The Hessian is $\geq0$ then why the conclusion is that it is not convex?
Thank you for clarifying!
Comment: convex non decreasing composed with convex is convex
Comment: @blamethelag then why they say it is indefinite?
Comment: Maybe because the example you are refering to is convex composed with concave. Here you cannot say $f$ is convex because $e^{-x}$ is not non decreasing.
Comment: Plot the graph in case $n=1$. Then use radial symmetry
Answer: Composition of convex functions is not necessarily convex and $e^{-x^2}$ is a counterexample to this, being the composition of $x^2$ and $e^{-x}$. However, if $f: \mathbb{R}\rightarrow \mathbb{R}$ is convex non-decreasing and $g: \mathbb{R}^n\rightarrow \mathbb{R}$ is convex, then $f\circ g$ is also convex.
The criterion for the convexity of $C^2$ functions $\mathbb{R}^n\rightarrow \mathbb{R}$ goes as follows:

If $f$ is convex, then it has everywhere positive semi-definite Hessian.
If $f$ has everywhere positive definite Hessian, then $f$ is strictly convex.

An analogous principle is true for concave functions.
One can easily check that $f=e^{-\|x\|^2}$ has positive semi-definite Hessian at some points (far from the origin) and negative semi-definite Hessian at some other points (close to the origin). Thus $f$ is neither convex everywhere nor concave everywhere.
Comment: Isn't the Hessian negative semi-definite  at points close to the origin (the other way round)?
Comment: Yes, you are correct. Let me edit it


View, Nodes categorized by field with counter just right to Category name

Question: I would like to split my 100 nodes by category field and display amount of nodes (from 1 category) near Category name.
Here is a screenshot of what I want to get at the end.

(X documents)

Could you please give me a hint/direction how can I do that?

"X" - number of documents in category
"documents" - word that could be translated in other languages.
Answer: Amend your view as follows:
Add the category term as a field to the view, either straight as a field from the node, or as a relationship. Make sure to exclude this category field from display.

Choose your format for the view, and for the format settings, select the hidden category field you just added as 'Grouping Field Nr. 1'.

Your view should now categorise the content with the category as the headings for each group.
Now to add the count.
In the Advanced part of the view, click on Theme: Information.

This open this window:

Now copy the name of a view override from the row 'Style Output' (underlined in red in screenshot'. The names to the left are to override the view in a very general way, and more the right it will target the view more specifically. Make it specific so that only this view is targeted.
Create a new file in your theme's templates folder with the name you just copied.
Paste this code in your file (it comes from clicking on the blue 'Style output' link in the view's theme information window, with a slight adaption).
<?php

/**
 * @file
 * Default simple view template to display a list of rows.
 *
 * @ingroup views_templates
 */
?>
<?php if (!empty($title)): ?>

<?php print $title . ' (' . count($rows) . ' ' . format_plural(count($rows), 'document', 'documents') . ')'; ?>

<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>

<?php endforeach; ?>

The last thing to do is to clear your cache.
Comment: that's perfect! exactly what i wanted.
Thanks for details!


Are there any clefs other than treble, bass, tenor, and alto?

Question: For most of my life, I've thought that treble and bass were the only musical clefs. Then I learned about the alto and tenor clefs. I've found articles online saying that these 4 clefs are the only ones regularly used, which makes it sound like there are more clefs out there that aren't commonly used.
Are the treble, bass, tenor, and alto clefs the only clefs, or are there more?
Comment: Percussion clef for drums, Tablature for guitar, if those count to you
Answer: There are three modern pitched clefs:

, the G-clef
, the C-clef (less common)
, the F-clef

Note that I didn't call them treble, alto, and bass. That's because the meaning of the clef depends on where it appears horizontally on the stave:

For the G-clef, the line passing through the middle of the swirly bit (technical term) is G4.
For the C-clef, the line passing through the centre is C4.
For the F-clef, the line passing through the two dots is F3.

We can then create a whole range of possibilities by shuffling these clefs around the stave:

Most of these are unused in modern music. You'll encounter treble and bass everywhere. Alto and Tenor are still used, but are less common, and tend to be associated with specific instruments (notably viola).

You'll also find octave-shifting clefs. They have a little "8" above or below the clef, to indicate up or down an octave:

, treble clef down one octave (8vb)
, treble clef up one octave (8va)

It's possible to create two-octave versions using "15" instead of "8", but that's getting pretty exotic

There's also a few other special-use clefs:

, used for unpitched percussion. Each space and line has a meaning, but it's not really standardised.
, used for tablature for guitars and other similar instruments

Note that there are many other clefs that have existed, and I'm not going to be exhaustive. Often they are just different ways of drawing the same clef.

All images shamelessly stolen from Wikipedia: https://en.wikipedia.org/wiki/Clef
Comment: This is a really thorough and in depth answer. Tenor clef is pretty common in cello literature.
Comment: That covers it.  I'd just add that I've encountered every one of these clefs, but that's because I do early music, and many older editions use the original clefs, which utilize all seven possible positions (not including octave transpositions) where a "C" can be.
Comment: @DrSvanHay and Alto clef is standard for violas, but we don't talk about them :-)
Answer: There's also something called a neutral clef. The treble, bass, tenor, and alto clefs are the most common. Many people don't really see the Neutral Clef very often, so it's less common than the treble, bass, tenor, and alto clefs. Use this website for more info on all 5 of these clefs: https://www.musicnotes.com/now/tips/a-complete-guide-to-musical-clefs-what-are-they-and-how-to-use-them/
Comment: I checked the website--your neutral clef is the same as the clefs for unpitched percussion in endorph's answer.
Comment: Hi,  we recommend putting information into your answers, because links are prone to vanish into the cyberfog of yesterday.


Convert datetime c++ struct (received as bytes) to c# datetime instance

Question: So i am working on replacing a legacy app that was written in c++ and i have hit a small issue in mapping a struct used in network communications to c#.  Basically the other end on the tcp connection uses the following struct to write dates and i have no idea how to convert the bytes generated by serialising that struct to a c# datetime. Most of it is easy till you get to the "millis" and "second" which are made up of 10 bits and 6 bits respectively so that the 2 bytes is shared between them.  I assume you solve this with bit-shifting to read and write the values to a byte array but i have no experience with this.
typedef struct DATE_TIME
{
    USHORT  year;
    UCHAR   month;
    UCHAR   day;
    UCHAR   hour;
    UCHAR   minute;
    USHORT  millis : 10;
    USHORT  second : 6;
}

Code for current attempt to read
ushort Year = br.ReadUInt16();
byte Month = br.ReadByte();
byte Day = br.ReadByte();
byte Hour = br.ReadByte();
byte Minute = br.ReadByte();

ushort secAndMillSec = br.ReadUInt16();
ushort Milliseconds = (ushort)(secAndMillSec >> 6);
ushort Seconds = (ushort)((ushort)(secAndMillSec << 12)>>12);

Code for my first try at a write
 bw.Write(Year);
 bw.Write(Month);
 bw.Write(Day);
 bw.Write(Hour);
 bw.Write(Minute);

 ushort secAndMillSec = (ushort)(Milliseconds << 6);
 secAndMillSec = (ushort)(secAndMillSec + Seconds);
 bw.Write(secAndMillSec);

Again does it look right?  So far all the test data i can run it against is empty dates so i am having issues testing myself
Comment: millis = combined & 0x3ff;  seconds = combined >> 10;
Comment: How do you receive the data? Is it a stream or byte array?
Comment: @MD.Unicorn as a stream but i have a BinaryReader/BinaryWriter on the stream so i can get them in parts for as a byte array.  At the min i am playing with extracting them all individually apart from second and milli which i get as a ushort then trying to bit shift them into separate fields
Comment: @MD.Unicorn put the first cut of the code at the bottom of my original question
Comment: You are doing well except for the bit manipulations. See my answer.
Answer: Bit fields are not portable across compilers but we can assume that these two fields are in two consequent bytes.
I assume you are receiving a stream from the network, and you are at the point of reading the datetime.
BinaryReader reader = new BinaryReader(networkStream);
int year = reader.ReadUInt16();
int month = reader.ReadByte();
int day = reader.ReadByte();
int hour = reader.ReadByte();
int minute = reader.ReadByte();
int ms = reader.ReadUInt16();
int second = ms >> 10;
int millist = ms & 1023;
DateTime dt = new DateTime(year, month, day, hour, minute, second, millis);

Comment: ok thanks i will try a few simple tests and if looks good go with this implementation till i get real data i can use it on
Comment: would it make a difference if i am using ushort and byte data types instead of int.  both milli and second are ushort in my code
Comment: just to be clear the order of the fields in the struct will be the order of bits and bytes in incoming stream so milli bits before second bits
Comment: @Seer No that doesn't make a difference. About the order of bits, see [here](http://msdn.microsoft.com/en-us/library/ewwyfdbe(v=vs.110).aspx)
Comment: If the reading works (which means the assumptions are correct, writing would be `writer.WriteUInt16((ushort)((second << 10) & millis))`
Comment: sorry just to be clear.  The struct i included at the start is the struct the legacy code is using and sending from memory so its order should be bit order right? This looks like it would create the correct ushort `ushort joint = (ushort)((milli << 6) + seconds);`. Checked the bits generated in a viewer and it looks right but your reader reads them out wrong
Comment: @Seer So are you getting the desired result from what you tried? My code is based on what [Visual C++ do about bit fields](http://msdn.microsoft.com/en-us/library/ewwyfdbe(v=vs.110).aspx). Other compiler my be different.
Comment: Updated post / question again with something that looks like it works byte wise but still a little worried as the byte/bit order looks right to me but you seem to think it should be opposite i think? I hate not having data for the field to check it with.
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/14379/discussion-between-seer-and-md-unicorn)
Answer: Seer. I was working on a similar project to. What i did was convert the date time to a Json objet then send it to c# as bytes and then from C# i read the bytes as Json. I prefer you use Json to communicate between c++ and C#.
Comment: can't as the other end is an external legacy system as well :(
Comment: There should other ways like @MD.Unicorn stated, but in case if nothing goes write in your scenario ty this solution ->. Since u have full control in ur c# app make only the communication TCP receiving part in C++ and bind it to the listening socket of ur C# app. In this case u can handle all data not only date time. because you can retrieve the value as it is in C++ and then send it to the C# in anyformat


Behavior for displaying map doesn't run

Question: I'm trying to create a pretty straightforward page with a Google map that I need to customize, but the code in the behavior isn't being run for some reason. Here's the code:
/**
 * Implementation of hook_theme
 */
function mymodule_theme() {
  return array(
    'affiliates_map' => array(
      'template' => 'affiliates-map',
      'path' => drupal_get_path('module', 'mymodule') . '/templates',
      'render element' => 'content',
     )
  );
}

/*
 * Page callback for map page.
 */
function mymodule_search_map() {
  drupal_add_css('
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      #map {
        height: 100%;
      }', array('group' => CSS_DEFAULT, 'type' => 'inline'));

  $path = drupal_get_path('module', 'mymodule');
  $gmap_api_key = variable_get('affiliates_gmap_api_key', '');
  drupal_add_js('//maps.google.com/maps/api/js?v=3&key=' . $gmap_api_key . '&callback=initMap',  array('type' => 'external'));
  drupal_add_js($path . '/js/mymodule.js', array('type' => 'file', 'weight' => 6, 'scope' => 'footer'));

  $output = theme('affiliates_map');

  return $output;
}

Here's my theme template.
<?php
/**
 * @file
 *   This template handles the display of the affiliates map.
 */
?>

Map content goes here

and the js file
(function($) {
  Drupal.behaviors.affiliatesMap = {
    attach: function (context, settings) {
      var map;

      function initMap() {
        map = new google.maps.Map(document.getElementById('naa-map'), {
          center: {lat: -34.397, lng: 150.644},
          zoom: 14
        });
      }
    }
  };
}(jQuery));

My console is giving me an error about initMap() not being found, and when I put a breakpoint in the behavior in initMap, it doesn't get hit. What am I doing wrong that it's not finding the behavior code? I've mimicked the Location Map module, and it works fine, so I'm not sure where I went wrong.
Thanks.
Answer: The issue ended up being my CSS. I was using styles from the sample page that had a height of 100%. Once I added some height and width to my naa-map div, my map showed up fine.
Answer: I think you should not declare initMap inside of the anonymous attachment - cause it's not visible outsinde. Try it like
(function($) {
  Drupal.behaviors.affiliatesMap = {
    attach: function (context, settings) {
      function initMap();

    }
  };
}(jQuery));

var map;

function initMap() {
    map = new google.maps.Map(document.getElementById('naa-map'), {
      center: {lat: -34.397, lng: 150.644},
      zoom: 14
    });
}

But I think it's anyway not so nice with that global space "var map".

Behavior for displaying map doesn't run


What is the difference between machine learning approaches and Fourier series to fit a curve to data graph?

Question: As I know machine learning(at least in some problems) tries to fit a curve to data graph. And I think Fourier transform tried to do it. But machine learning use a hypothesis curve with the formula like h = w1x1 + w2x2 + ... + wnxn but Fourier uses a combination of Sin()/Cos() functions.
What is the difference? Why machine learning doesn't use a Sin()/Cos() combination like Fourier series/transforms?
Answer: Using Fourier series is machine learning.
Machine/Statistical learning is just a general term for all kinds of tasks where learning from data is required.


Let $AB$ be a diagonal matrix. Is A invertible?

Question: Let $AB \in K^{n\times n}$, $AB$ is a diagonal matrix and the elements on the diagonal are non-zero.
Is $A$ invertible?
Since $AB$ is a diagonal matrix and the elements on the diagonal are non-zero, $AB$ is invertible. Also neither $A$ nor $B$ can possibly contain zero-vectors or $AB$ would too which it doesn't. However not containing zero-vectors is not sufficient for a matrix to be invertible, right?
Please be aware that I don't know much about linear algebra yet, so a thorough explanation would be much appreciated.
Comment: $A(B(AB)^{-1})=I$, done.
Answer: $$AB = \Lambda$$
Since $\Lambda$ is a diagonal matrix with non-zero elements it's invertible
$$\left (
AB
\right)^{-1} = \Lambda^{-1}$$
If a product is invertible, then multiplicands are also invertible
$$\left(
AB
\right)^{-1} = B^{-1}A^{-1} = \Lambda^{-1}
$$
therefore $A^{-1} = B\Lambda^{-1}$
Comment: My prof's script contains this rule with the constraint that $A, B \in GL(n, K)$. Is this really true for all matrices in $K^{n\times n}$?
Comment: @Kaster , your proof assumes what must be proved, i.e. that $\,A\,$ is invertible. To write $\,(AB)^{-1}=B^{-1}A^{-1}\,$ is meaningless *unless* we know a priori that both $\,A,B\,$ are invertible.
Answer: Use the determinant:
$$AB=\begin{pmatrix} a_1&0&...&0\\...&...&...&...\\0&0&...&a_n\end{pmatrix}\,\,,\,a_i\neq 0\Longrightarrow \det A\cdot\det B=\det AB=\prod_{i=1}^na_i\neq 0\Longrightarrow$$
$$\Longrightarrow \det A\neq 0\Longrightarrow \,\,A\;\;\text{ is regular and thus invertible}$$
Comment: Thanks for your answer though I'll have to do a bit of reading to understand it because we haven't covered the determinant yet.
Comment: Well, then re-take your argument: a matrix is non-invertible( i.e. singular) iff upon reducing it (by rows or columns, it doesn't matter) we get one at some point one row (column) of zeros, If this was the case for $\,A\,$ then in $\,AB\,$ (after reducing $A$) we'd get one row (column) or zeros, which is impossible since, at you pointed out, $\,AB\,$ is invertible.
Comment: Makes sense. I wasn't exactly sure if I could assume A to be reduced already. So this also means if $A$ had linearly dependant columns (and could thus be reduced to have zero columns) the columns  in $AB$ would also be linearly dependent, right?
Comment: Indeed so, @Christian
Answer: Yes, both $A$ and $B$ are invertible provided they are square in the first place. We could however say that $A$ and $B$ both have full-rank since
$$\text{rank(AB)} \leq \min  \{\text{rank(A), rank(B)}\}$$ Since $AB$ is diagonal with non-zero entries, $\text{rank(AB)} = n$. If $A \in \mathbb{R}^{n \times m}, B \in \mathbb{R}^{m \times n}$, then the previous result means that $m \geq n$. If $m=n$, we could also conclude that $A$ and $B$ are invertible.


Comparação de Lists de objetos - C#

Question: Preciso comparar 2 listas de objetos que foram preenchidas via banco de dados, conforme classes abaixo:
public class Ausente
{
    public ObjectId Id { get; set; }
    public Int32 RA { get; set; }
}

public class AlunoEstagio
{
    public ObjectId Id { get; set; }
    public Int32 RA { get; set; }
    public String ALUNO { get; set; }
    public Int32 PERIODO { get; set; }
    public String DISCIPLINA { get; set; }
    public char CONCEITO { get; set; }
}

A List 1 receberá o objeto Ausente, a list 2 receberá o objeto AlunoEstagio.
Eu gostaria de comparar as 2 listas de forma que quando houver um atributo RA da List 1 presente na List 2, que o objeto correspondente da List 2 seja adicionado em uma terceira lista (List 3).
Não tenho ideia de como realizar essa comparação, poderiam me ajudar?
Comment: O que você já fez? Que problemas encontrou? Mostre algum código, pelo menos tente fazer algo para gente poder ajudar com sua dificuldade.
Answer: Se os 2 tipos fossem iguais, você poderia usar o Intersect, mas como não são, acho que o código abaixo faz o que você precisa:
var list3 = from l1 in list1
            join l2 in list2 on l1.RA equals l2.RA
            select new
            {
                l1,
                l2
            };

Onde list1 e list2 são do tipo List<Ausente> e List<AlunoEstagio> respectivamente.
Comment: Obrigado Bruno, mas essa variável list3, devo converter para um atributo do tipo List certo? A ideia é exibir o conteúdo em um DataGridView
Comment: É só você mudar o select, selecionando o que você precisa mostrar no grid. Se me disser quais campos precisa, eu altero a resposta pra você.
Comment: E dependendo do controle que for usar, não precisa converter pra list e nem mudar o select, nos campos você pode mudar o bindind pra algo como l1.RA, l2.ALUNO etc...
Comment: Obrigado Bruno, já consegui, só adicionei um .ToList() entre a última chave e o ponto vírgula e funfou ! Me ajudou bastante cara, valeu

Comparação de Lists de objetos - C#


Proper course of study for someone who wants a career as a conductor

Question: I have a friend who recently graduated at the top of his class at a prestigious east coast music conservatory. (He graduated with a bachelors of  music.) He wants to be a conductor and applied to a number of graduate programs, but his application (with pre-screening videos) did not result in any invitations for a live audition. He says that the feedback he received was that he didn't have enough conducting experience. To remedy that lack he has enrolled in a Masters of Music Ed program at a local university. I've looked at the program, and to my (inexpert) eyes, it seems to be preparation  for teaching high school orchestras, bands, choirs, etc.
Is this a useful pursuit for someone who doesn't really want to teach high school? Will any fine arts graduate programs in conducting find secondary school experience compelling? If not, does anyone have any suggestions for improving one's conducting skills to better the chances of graduate admission?
Comment: If you don't get a good answer here, you could try https://academia.stackexchange.com/
Answer: The only way to get conducting experience is to actually conduct. For the beginning conductor that means jumping at absolutely every opportunity to conduct, whether that's student ensembles, community bands, church choirs or whatever.
A masters course in education will contain some conducting, but that won't be the main emphasis, and that's probably not the best route to take.
Answer:
it seems to be preparation for teaching high school orchestras, bands, choirs, etc.

It is possible that you're right. I can't confirm, though.
I think the best approach in this kind of things is to take classes with some already established director, a maestro who knows what and how makes the difference. Don't look so much into the degree as a whole, but rather to what exactly would improve his conducting. Once he's under the guidance of a maestro who'll work with him to get the best of him, he should naturally start to introduce him to new opportunities and of course how to prepare to get right those auditions.
It is possible that he can get that maestro at the university to which he's applying, I don't know. But above all, that's the thing to which your friend should pay attention to, in my opinion.
Hope this helps!


Is there a way to write the variation of a functional in terms of the shift operator

Question: First of all, I'm not a mathematician, I study physics (so please be gentle). In learning physics (much to my chagrin) the finer mathematical details are often swept under the proverbial "carpet". It is pretty common to come across some functional:
$$J=\intop F\left[\overrightarrow{X}(\tau)\right]d\tau$$
Where F is an arbitrary (in this case) function and X represents a position vector being parameterized by $\tau$. If we're seeking the minimization, it is common to consider a variation in J with respect to some variation in our parameter tau.
$$\delta J=\intop F\left[\overrightarrow{X}(\tau+\delta\tau)\right]d\tau-\intop F\left[\overrightarrow{X}(\tau)\right]d\tau$$
I'm wondering is it then legitimate to utilize the shift operator which is defined by:
$$F\left[\overrightarrow{X}(\tau+\delta\tau)\right]=e^{\delta\tau\frac{\partial\overrightarrow{X}}{\partial\tau}\cdot\overrightarrow{\nabla_{x}}}F\left[\overrightarrow{X}(\tau)\right]$$
Which is essentially just a concise way of expressing the Taylor/Maclaurin expansion. If one considers utilizing this then we have an expression of the form:
$$\delta J=\intop\left(e^{\delta\tau\frac{\partial\overrightarrow{X}}{\partial\tau}\cdot\overrightarrow{\nabla}}-1\right)F\left[\overrightarrow{X}(\tau)\right]d\tau$$
Or examining just the integrand:
$$\left(e^{\delta\tau\frac{\partial\overrightarrow{X}}{\partial\tau}\cdot\overrightarrow{\nabla}}-1\right)F\left[\overrightarrow{X}(\tau)\right]$$
and expanding out a few terms:
$$=\left(\delta\tau\overrightarrow{U}\cdot\overrightarrow{\nabla}+\left[\delta\tau\overrightarrow{U}\cdot\overrightarrow{\nabla}\right]\left[\delta\tau\overrightarrow{U}\cdot\overrightarrow{\nabla}\right]+\cdots\right)F\left[\overrightarrow{X}(\tau)\right]$$
$$=\left(\delta\tau\overrightarrow{U}\cdot\overrightarrow{\nabla}+\frac{1}{2}\delta\tau\delta\tau\overrightarrow{U}\cdot\left(\overrightarrow{\nabla}\overrightarrow{U}\right)+\delta\tau\delta\tau\overrightarrow{U}\cdot\overrightarrow{U}\overrightarrow{\nabla}\cdot\overrightarrow{\nabla}\cdots\right)F\left[\overrightarrow{X}(\tau)\right]$$
The first term seems to correspond to the first variation (which is then manipulated to obtain the Lagrange equation, are the other terms higher variations?
Now I know this isn't right (as we've taken no limits and specified no boundary conditions); however I was wondering if you can express higher order variations (since they generally only teach us physicists the first variation) in terms of the shift operator (which happens to be linear). I can think of several applications of such a mathematical tool within the realm of physics. Any literature you might be able to steer me towards?
I should probably note that the problems I have in mind will take place on general (pseudo/semi) Riemannian manifolds where derivatives will be covariant ones.
Comment: The strange thing is that the parameter $\tau$ appears to be the same as the integration variable $d\tau$ in the integral, which means that $J$ does not seem to depend on this parameter. Can you be more specific on this point? Do you really mean this?
Comment: @Gribouillis generally the "action" as we call J (often denoted S) is a number, all variables having been integrated out. F would then be called the lagrangian (often denoted by L). The extrema of J is used  ultimately to find a differential equation for X($\tau$)
Comment: @Gribouillis  In some books they call $\delta\tau$ instead $\epsilon u$ and take the derivative wrt $\epsilon$
Comment: I see, the true 'variable' is $X$ itself, the shift is only a special type of perturbation. There are boundary problems but it is not your question.
Answer: This is only a first reaction, because I don't have a book or a paper in mind to recommend. It seems to me that there are at least 3 levels to consider your calculation
1) The formal level, where nothing is mathematically justified, but it still does have a meaning because formal solutions usually lead to correct solutions far before one is able to prove rigourous theorems. This is a very good reason to perform formal calculations.
2) The regular case where functions such as $F$ and $X$ are supposed to be infinitely smooth and have all the good properties so that the formal calculations become mathematically true. This is ideal for physicists equations. Remark that you are using the exponential of the derivation operator, this is called functional calculus with unbounded operators. Books on functional analysis could tell you about this. Basically however the first tool is that the calculus can be fully justified when functions are infinitely smooth.
3) The 'real' situation where functions are not infinitely smooth. Mathematical legitimacy is usually obtained by establishing limits when smooth functions converge to the real functions (density of smooth functions spaces in other function spaces). The important part is to discover inequalities that apply to the problem, such as some energy is bounded, etc. This is where the real mathematical work takes place.
Edit: it seems to me that some factorials are missing near the end of your question.
Edit2: I forgot to mention that your use of $e^{\delta_\tau \frac{\partial X}{\partial \tau} \nabla}$ can also be viewd as being part of the theory of semi-groups of bounded operators, a field of functional analysis generaly related to evolution equations.
Comment: I'll look into the functional analysis, and yes I was definitely considering them being infinitely smooth. +1. Indeed! I forgot the factorials!


No "webform" link in operations column

Question: i'm new to Drupal and PHP in general, so this may be obvious - But I'm working with Drupal 7 with module webform installed. Recently, i don't know why the link stopped appearing in the Operations column on the Content list page in the admin.
 Any help would be appreciated!
Comment: try to change your theme and then try
Comment: i try it :/ but it does'nt work
Answer: Hi make sure you are enable the webform functionality  like this
check
http://prntscr.com/bur06a
 if not working then  follow  tutorial
Comment: i didn' find it, [link](http://prntscr.com/bur3mf)
Comment: try  with new webform   go to admin/content  add new / webform
Comment: i found the same thing :/
Comment: give me  your  site link
Comment: it's just local
Comment: ok  have you follow this https://www.ostraining.com/blog/drupal/webform-module/
Comment: i have alredy creating my webform with differents fields and some conditions and it works fine but today i was surprising when i didn't find the link operation webform :/
Comment: check this  https://www.drupal.org/node/1161924  your problem is same
Comment: finaly it's work, i follow the first tutoriel, you was right, enable webform was uncecked :$ thank you so much for your help
Comment: my pleasure buddy keep codeing

No "webform" link in operations column


What is the correct syntax to supply a class to Mockito.any() so that the verify() call is unambiguous?

Question: I'm using Mockito.spy(...) on a non-Mock object to verify that one of its methods is never called. However, there's an ambiguity because I'm just using any(), any(), and there are two overloads with two parameters:

I'm a bit new to Java and can't figure out the right way to express what Mockito wants from me. I think I don't have a good handle on reflective concepts in Java, e.g. difference between Class, Function, lambdas, etc.
Here's an example of an actual (non-Mockito) use of that method:
        return jdbiExecutor.execute(Foo.class,
            foo -> {
              // Some code.
              return Bar.newBuilder().build();
            });

So, what I'm trying to verify is the first overload that takes a Function<D, T> for its second parameter. Some things I've tried but don't work:
// Is specifying just one of the parameters enough?
verifyZeroInteractions(executor.execute(any(Foo, any()));

// Maybe I need to supply the `.class()`?
verifyZeroInteractions(executor.execute(any(Foo.class, any()));

// Or literally, `Class<Foo>`?
verifyZeroInteractions(executor.execute(any(Class<Foo>), any()));

// Or what, do I _have_ to specify both parameters to some degree?

How can I get this to work?
Answer: You should give the explicit type to compiler
executor.execute(any(), Matchers.<Function<?, ?>> any()); // here ? can be your explicit type


How to fix 'Is poppler installed and in PATH?' in R

Question: I'm running a python script in R using reticulate. I use py_discover_config() for finding Python config. I am using anaconda. I don't really understand environments and why I would need one.
I tried use_python() and use_condaenv() even installing packages with conda_install.
library(tidyverse)
library(jsonlite)
library(reticulate)

py_discover_config()
# Set the path to the Python executable file
source_python("~/projects/stiekemthuis/API.py")

json_list <- api_fun() %>% toJSON()

It had no problem importing the python libraries:
from pdf2image import convert_from_path
import numpy as np
from pathlib import Path
import io, json
import os
from PIL import Image
import requests
import sys

I got an error at line 25:
pages = convert_from_path(files[0], 300)

Error in py_call_impl(callable, dots$args, dots$keywords) :
  PDFInfoNotInstalledError: Unable to get page count. Is poppler installed and in PATH?
I tried to setwd() to a the path of the binaries of poppler.
What can be done?
Comment: Does this answer the question? https://stackoverflow.com/questions/17332238/add-poppler-to-path-in-debian/17340158#17340158 . I would not expect changing the working directory to help.
Answer: I stopped using the library(reticulate) and started using system2 for direct execution through python command followed by the path to script:
command = "python"
allArgs = c(path2script)

output = system2(command, args=allArgs, stdout=TRUE)

json_list <-output %>% fromJSON()

I used code from another thread in my python script:
print(json.dumps(res, sort_keys=False, indent=2, separators=(',', ': ')))

Because my formatting of the Json string was bad.


Caching ordered Spark DataFrame creates unwanted job

Question: I want to convert a RDD to a DataFrame and want to cache the results of the RDD:
from pyspark.sql import *
from pyspark.sql.types import *
import pyspark.sql.functions as fn

schema = StructType([StructField('t', DoubleType()), StructField('value', DoubleType())])

df = spark.createDataFrame(
    sc.parallelize([Row(t=float(i/10), value=float(i*i)) for i in range(1000)], 4), #.cache(),
    schema=schema,
    verifySchema=False
).orderBy("t") #.cache()

If you don't use a cache function no job is generated.
If you use cache only after the orderBy 1 jobs is generated for cache:
If you use cache only after the parallelize no job is generated.

Why does cache generate a job in this one case?
How can I avoid the job generation of cache (caching the DataFrame and no RDD)?
Edit: I investigated more into the problem and found that without the orderBy("t") no job is generated. Why?
Comment: With your updates clarifying the question, I deleted my original answer. This is an interesting question as orderBy("t") is lazily evaluated as it should be and cache() without orderBy is also lazily evaluated, but together, I too am not sure why anything is executed for purely transformer operations.
Answer: I submitted a bug ticket and it was closed with following reason:

Caching requires the backing RDD. That requires we also know the
  backing partitions, and this is somewhat special for a global order:
  it triggers a job (scan) because we need to determine the partition
  bounds.


Dynamic Backends with HAProxy

Question: I'm trying to figure out the best way to handle dynamic proxying of HTTP requests.
Basically I want to take a dynamic hostname in the form of myname.cust.mydomain.example and then forward requests to an HTTP backend server with the name "myname" taken from the hostname.
I've been racking my brain trying to figure out the best way to handle this and if HAProxy is even up to the task.
Another option I was thinking was something like Lighttpd with LUA or even Nginx.
Comment: How would you go about mapping `myname` to a particular backend server?
Comment: That's what i'm trying to do. Myname will be an internal server that I want to proxy requests to, so that if a user visit Myname.cust.mydomain.com it will automatically proxy the request through to Myname on the internal network. There may be a few hundred servers, and ideally it should be dynamic.
Answer: The easiest solution would be just use DNS to map foo.cust.mydomain.example to a specific server IP, as womble suggested. This would skip the entire proxy server. Perhaps this is not possible for you, for example if you do not have public IP addresses for the backend servers.
Directing all requests to one server (with a wildcard DNS) and then forwarding the requests dynamically according to the Host header is a bit more complicated, and it seems HAProxy cannot do this, because every backend server must be explicitly defined in HAProxy configuration.
Nginx, though, is different, with right configuration Nginx can use Host header to choose the backend. Nginx needs a DNS server that maps names to backend addresses, of course.
Here is a small example of the configuration:
server {
    listen 80 default;

    location / {
        # You might need to send some headers to the backend server
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;

        resolver 192.0.2.1; # DNS server IP
        # Forward all requests to the backend server using $http_host
        # (this is the 'Host:' header value)
        proxy_pass http://$http_host$request_uri;
    }
}

This redirects http://myserver.cust.mydomain.example/foo/ to http://myserver.cust.mydomain.example/foo/. Does not seem very helpful at first sight. But if you set up a private DNS server that maps those names to a backend server addresses, the request actually gets forwarded to a correct backend server on a private address.
But, this kind of DNS server setting might not be desired, and could cause problems in some cases. So, with some additions to the Nginx config, we can take another approach:
location / {
    # headers...

    resolver 192.0.2.1;

    # A regex to get the first part (hostname) from the Host header
    if ($http_host ~* "([a-z0-9-]+)(\.[a-z0-9-]+)*") {
        # Save a captured part from the regex to a variable
        set $redirect_hostname $1;
        # Pass the request to a desired backend
        proxy_pass   http://$redirect_hostname.private.mydomain.example$request_uri;
    }
}

Now redirect goes from http://myserver.cust.mydomain.example/foo/ to http://myserver.private.mydomain.example/foo/. The DNS server can hold private addresses under different domain, and proxy_pass directive can be modified to match the desired name server configuration.
I still think this kind of proxying might not be the easiest way to solve the whole picture, but it's one possibility after all. I'm happy if this was of any help.
References: Nginx Wiki, especially HttpProxyModule and HttpRewriteModule
Comment: Mikko, thank you so much for the help. This gives me a great start!
Comment: Please vote up and/or select the answer if the post was helpful! Thanks!

Dynamic Backends with HAProxy


Positioning flex box divs within a container

Question: I have this https://jsfiddle.net/zd2Lpkor/ flex box based code that i am trying to understand how i can position elements using flexbox.

In my fiddle, i set up a width of 1px but the code produces a div that isn't 1px in width. Why is that happening?
Secondly if i lay out my divs like this

1

2

3

can i use flexbox to position my div in any marked spot in the diagram below?. Iam looking for flex box features that can allow me place my div or content in exact cells that i pick within my diagram below.
Comment: *"i set up a width of 1px but the code produces a div that isn't 1px in width. Why is that happening?"* Because you have `flex-grow` applied to each item via inline styles.
Comment: @MichaelBenjamin So `flex-grow` has a default minimum width?
Comment: No. `flex-grow` tells the item to consume free space on the line, based on the available space and the value you set.
Answer: If you would like to position specific div in specific cell in your layout you should consider CSS Grid instead of flexbox:
https://developer.mozilla.org/pl/docs/Web/CSS/grid
This allows you to create a definition of layout of your cells, and assign divs to chosen areas. You do it with grid-template-areas in container element. You have to also use display: grid. It could be similar to (x* are areas that you want to be empty, but still they have to be defined in layout):
grid-template-areas: "1  x  x  x  x  2"
                     "B1 x  x  x  x  B2"
                     "C1 x1 M1 x2 x2 C2";
                     "x3 x3 M2 x2 x2 x4";
                     "L1 x5 x5 x5 x5 L2";
                     "3  x5 x5 x5 x5 4";

Then you can assign div to one of the areas:
grid-area: B1;

Answer: Tomasz's answer is correct, but if you want to work with flex box you can do it like this.

.container {
  width: 400px;
}

.row {
  border: 2px solid white;
  color: white;
  display: flex;
  padding: 10px 20px;
  background-color: black;
}

.one,
.two,
.three,
.four,
.five,
.six
{
  justify-content: space-between;
}

.four {
  justify-content: center;
}

1

2

b1

b2

c1

m1

c2

m2

l1

l2

3

4

Also if you want to learn CSS flexbox I recommend this site


Server 2012r2 DNS failover/load balance SOA entry

Question: I have 2 Server 2012r2 servers running DNS in failover/loadbalance. They both sync fine but I have noticed that they each claim themselves as SOA. It sounds wrong to me, but is this due to the failover?
Thanks,
Travis
Comment: `I have 2 Server 2012r2 servers running DNS in failover/loadbalance` - What does that mean exactly? How are they configured for failover/loadbalance?
Comment: Are these Domain Controllers hosting an AD integrated DNS zone? If so, then each server is SOA for it's copy of the zone and this is perfectly normal.
Comment: My apologies, I was thinking of the DHCP setup. Realizing this, should the SOA on the 2nd DNS server point to the 1st DNS server?
Answer: For AD integrated DNS zones, each server hosting a copy of the zone is the SOA for it's copy of the zone.
This is perfectly normal.
Answer: It is typical for systems that do not use DNS to replicate to claim themselves as master.  This is true for not only Windows (AD Integrated zones) but also bind (ldap-bind) and powerdns (ldap, database, etc).
More on Windows Bind, and PowerDNS
I've asked this question as well, I expect as more people use APIs with multiple providers, the SOA and Serial # will continue to diverge.


Methods of using filters in Laravel - what is the difference

Question: I try to learn Laravel, and I'd like to verify the user is logged in before calling a controller to do stuff.
There seems to be at least 3 different ways to accomplish this, and I'd like to know what is the difference between these.
Route::get('/main', 'StuffController@doStuff')->before('auth');

Route::get('/main', array('before' => 'auth', 'uses' => 'StuffController@doStuff'));

Or in the controllers constructor:
public function __construct() {
    $this->beforeFilter('auth');
}

Answer: There are no differences. Laravel is the Framework that allow you to accomplish many tasks in many ways.
I prefer to add filters in routes grouping them, for example:
// logged users paths
Route::group(
    ['before' => 'auth'],
    function () {
        Route::get('/dashboard', [
                'as'   => 'dashboard',
                'uses' => 'DashboardController@mainPage'
            ]);
    }
);

// paths only for admin
Route::group(
    ['before' => 'admin'],
    function () {
        Route::get('/admin',
            ['as'   => 'admin_dashboard',
             'uses' => 'AdminDashBoardController@mainPage'
            ]);
        Route::get('/categories/{page?}',
            ['as'   => 'categories',
             'uses' => 'CategoryController@displayList'
            ])->where('page', '[1-9]+[0-9]*');
    }
);

There is one benefit of such use - its' much easier to look if all routes have correct filters.
Assume you want to display some content only for logged users and you need to use auth filter. You have many controllers to display content for logged users.
If you use beforeFilter directly in those controllers or in parent controllers constructor the following things can happen:

you may forget to put beforeFilter in all your controller constructors
you may forget in your controller constructor to run parent constructor (where you have beforeFilter)
you may extend not the class you wanted (for example you extend BaseController and you have beforeFilter defined in AuthController and in one or some classes you extend BaseController)

Those situations can cause that you display content for unlogged users because you need to remember about auth filter it in each controller and if you want to make sure you did everything right, you need to look at code of all your controllers.
Using route grouping (as I showed above) you can easily look at one file (of course assuming you use one file for routing) and you will see which routes use auth filter and which don't.
Of course I assume many people will have their own opinion on that thing but that's me personal preference to use filters in routes.
Answer: Your two ways have no difference, just different syntax style.
I prefer to put the auth filter in a BaseController, then extends all controllers I want to be authed from BaseController. Just write once, used everywhere. Btw, you can also put your csrf filter here.
class BaseController extends Controller {
  public function __construct() {
    $this->beforeFilter('auth');
    $this->beforeFilter('csrf', array('on' => 'post'));
  }
}


Node.js module: export async function

Question: In the given example it is demonstrated, how to export a variable, or a function from a custom module. How could one export an asynchronous function in a similar manner and then call it from app.js something like:
// app.js

var things = require("./someThings");

await things.getSomeThingsAsync();

EDIT:
The example (answer on Stackoverflow) pointed to by the above link contains the following code:
// someThings.js

(function() {
    var someThings = ...;

    ...

    module.exports.getSomeThings = function() {
        return someThings();
    }

}());

// main.js

var things = require("someThings");
...
doSomething(things.getSomeThings());

Say inside of the module's incapsulated function a asynchronous function exists, which you would like to expose to whoever imports the module. For example:
(function() {
    ...
    const doSomethingAsync = (time) => {
        return new Promise(resolve => {
            setTimeout(() => resolve(42), time)
        })
    }

    //const doSomething = async () => {
    async function doSomething () {
        let answer1 = await doSomethingAsync(3000)
        let answer2 = await doSomethingAsync(1000)
        return answer1 + answer2
    }
    ...
    /*module.exports.doSomething = function() {
        return doSomething();
    }*/
    module.exports.doSomething = async function() {
        return doSomething();
    }
}());

How would you expose the doSomething function in similar fashion as the in the original answer it is done for someThings - how can the referred to answer be changed in such a way, that when exporting functions, it lets you use the await keyword? It will then be used as:
// app.js

var things = require("./someThings");

console.log(await things.doSomething());

I have tried multiple approaches, but I always get:
SyntaxError: await is only valid in async function

Answer: You can try this :
//yourModule.js

let yourModule={};
yourModule.you=async()=>{
    //something await...
}
modules.export = yourModule;

//app.js

let yourModule = require('<pathToModule>');

async function test()
{
    await yourModule.you();  //your `await` here
}

Answer: You are misunderstanding the error. It says

SyntaxError: await is only valid in async function

not "for async function"
There is no problem with your export. It is simply not possible to use await outside of a function marked async. Therefore the bug is in app.js. It should be:
var things = require("./someThings");

async function app () {
    console.log(await things.doSomething());
}

app().then(() => console.log('done calling app()'));

Answer: This is probably a duplicate of this question.
You can simply assign the function (or a function expression) to a property (or just the entirety) of `module.exports'.
For example:
async function AsyncStuff () { ... }

module.exports.myAsyncThing = myAsyncStuff;

Answer: Try this
var things = require("./someThings");
let result = getResult();
async function getResult() {
    return await things.getSomeThingsAsync();
}

Node.js module: export async function


Why is a page generated by views listening to block.tpl?

Question: I'm working on some custom templates for a page created by Views and I'm struggling to understand why it's using block.tpl (which I thought was used for blocks). Basically I'm trying to get rid of all the extra divs created for just this one particular page, and until I remove the div class content I can't get the desired style I'm looking for.
I did something similar for a block generated by views and used the template name block--view-name.tpl and got the desired effect. I ended up copying that same template file and just called it block.tpl and got the deserved effect on this Views page.
Now I'm left scratching my head as to why this Views page is listening to block.tpl when it's not a block. Also, seeing as it apparently wants a block template to do what I want, I'm trying to figure out the template naming but none of the usual tools are helping (theme developer module, the theme information under the advanced tab when editing the view).
Does anyone know why a page generated by views would be listening to block.tpl? If it helps the view content on the page is being wrapped by the following div:

Answer: That block is the main content block.

It is provided by the system module and is the default content area block in the page template.
More information:

system_block_info ( delta is "main" )
system_block_view
Comment: Ah I see, well that at least clears up the first part. Do you know how I would go about figuring out naming a custom block template for that page? The theming information provided by the View settings doesn't offer any suggestion for a block template and I've tried every possible name I can think of.
Answer: In Drupal 7 the main page content was turned into a block that could be positioned with the block module. Problem is I don't think people have many use cases for that functionality.
You can get rid of that ugly #block-system-main div by doing the following:

Add a template to your theme called block--system--main.tpl.php
Print ONLY the content within that block template: <?php print $content; ?>


Trying to add a code to my CSS but it doesn't work

Question: So I made a small change on the page (gesher-jds.org/giving):

Donate Now, Pay Later

to

Donate Now, Pay Later

and now the design of the right calculator has changed (more like the button as I see). How do I fix it? Both of them looked the same (besides the text). I tried to add the code below to the CSS but it still didn't work. What I'm doing wrong?
CSS
a#payLater {
    background: #60426c;
    width: 100%;
    display: inline-block;
    margin-top: 20px;
    padding: 10px;
    text-align: center;
    color: #fff !important;
    font-size: 20px;
    text-transform: uppercase;
    letter-spacing: 1px;
    font-weight: bold;
    text-decoration: none !important;
    }

Comment: It's hard to help. Please provide some codepen example because as far as I can see, you've only changes the id atrribute value. Maybe change all occurences of #anchor1 to #payLater in css styles ? (It's not a good practice but it might work)
Comment: The problem is that the left calculator is using the #anchor1, that's why I'm trying to change it. Can't I just add the code below to the CSS file with the same id? When I tried it, it didn't work.
Comment: Maybe use class instead ?
Comment: How do I do that?
Comment: Donate Now, Pay Later
and you style it like .payLater {styles here}
Comment: I still need the id, because it's connected to other things. Can I put the id and class together?
Comment: Technically, you can
Comment: I used this one: Donate Now, Pay Later but it still didn't work.
Comment: And this one: .payLater {
    background: #60426c;
    width: 100%;
    display: inline-block;
    margin-top: 20px;
    padding: 10px;
    text-align: center;
    color: #fff !important;
    font-size: 20px;
    text-transform: uppercase;
    letter-spacing: 1px;
    font-weight: bold;
    text-decoration: none !important;
Comment: Go to the page, open dev tools, click the html element and you'll see his styles on the righ. Copy and paste the styles to the box on the right "element.style".It works correctly and the styling gets applied. The reason it's not working for you is that your styles are probably getting overwritten by other styles. You'll see there which styles are applied
Comment: So what can I do in order to fix it?
Answer:
If you apply the styling in the dev tools it works like expected. The reason it does not work in your working environment is probably because your styles are overwritten by different styles. Check the dev tools to see which styles are applied
Potential fixes:
1) Tidy up the "!important" rules.
2) Build stronger selectors -> keyword to look for knowledge [CSS Specificity]
If you set !important in one CSS rule, it'll become hard to overwrite that because !important = 1000 Specificity points so the rule is really strong
Comment: It's weird, but when I add this code to the css, it looks like it cant even find it: a#payLater {
    background: #60426c;
    width: 100%;
    display: inline-block;
    margin-top: 20px;
    padding: 10px;
    text-align: center;
    color: #fff !important;
    font-size: 20px;
    text-transform: uppercase;
    letter-spacing: 1px;
    font-weight: bold;
    text-decoration: none !important;
    }
Comment: Sorry i couldn't anwer. Did you manage to fix the issue ? I went to the website and it looks good now, is it right ?
Comment: two looking good buttons next to each other. It's the desired look I guess
Comment: I didn't fix it. I just checked. I tried everything and it doesn't work. It looks like #payLater can't find the #payLater in the css file. How do I fix it?
Comment: I just checked and it doesn't look good. I still don't see the button.
Comment: It's really weird because it works for me. I see two buttons with correct styles applied. Try clearing the cache
Comment: I did. I also checked from a different computer.
Comment: It's weird. It looks fine on my phone and edge. When I check on other computers, I don't see the change. Why not?


Como criar uma instanciar uma classe usando variáveis provenientes de um retorno de função em Python 3?

Question: Olá, gostaria de poder instanciar a classe Sala abaixo usando como argumentos o retorno da função choose_sala():
O ideal seria já chamar no retorno da função a inicialização da classe Sala, mas não obtive sucesso até agora.
Segue o exemplo simplificado:
Python 3
class Sala:
    def __init__(self, ano, turma):
        self.ano = ano
        self.turma = turma

        print(" Sala Escolhida foi... ")

    def say_hello:
        print("Hello!")

r1 = [] # desnecessário!

def choose_sala():
    r1 = ['8A']
    r1 = "".join(r1)
    print(r1)

    print(r1[0], " ", r1[1]) #para poder usar casa letra separadamente, não deu certo usando a lista normal.
    return r1

Gostaria de poder usar:
a = Sala(choose_sala())
a.say_hello() # teste da classe

Answer: O que você quer fazer é:
a = Sala(*choose_sala())

O * faz com que cada elemento retornado seja passado separadamente como um parâmetro separado para a classe Sala.
Veja mais sobre isso no tutorial básico oficial aqui.
Comment: Ok, obrigado, funcionou muito bem, sabia que era algo simples, mas não tão simples quanto um *. Tutorial básico, aqui vamos nós!
Comment: @GeorgeBueno agora que deu certo, poderia marcar minha resposta como aceita, para fechar a pergunta? Só clicar no checkmark verde ao lado da resposta.


Why chords make melody sound different?

Question: I am learning to harmonize melodies. I put basic triads under the melody notes. Sometimes, they work well. Sometimes, the chords just make the melody sound different. I can't find solution to it.
For example. Melody as the following.
Key: A minor. 3/4
Measure 1: A B C
Measure 2 and 3: D C B - - -
B lasts 4 beats.
I put F and C under A note. Vertically, AFC. Now A does not sound like A any more. I put D under B, now B does not sound like B anymore. I don't see I do anything wrong here chord-wise. But the whole thing sounds different from how melody sounds alone which is really a disaster. The chords changed the melody.
Comment: Which "B" are you adding the "D" to?
Comment: If you don't like the way your chords work with your melody then choose different chords.
Comment: The last B note
Answer: Played by itself, your melody will sound like A minor, and A will sound like the tonic — the first note of an A minor scale. This is influenced by the fact that it's the first note in your melody as well as by the fact that your melody is made of the first three notes of the A minor scale.
However, when you harmonize the A with F and C, you've created an F major chord. That's going to give a strong impression of F major, not of A minor.
Context has an immense impact on the perception of pitch, so one cannot effectively harmonize with arbitrarily chosen notes. This is one of the primary objectives of music theory: to explain how melody and harmony affect each other.
Answer: I'll add to Aaron's answer:

Sometimes, the chords just make the melody sound different.

You've stumbled onto the magic of "harmonization." And that's kind of the point of it. Start with a melody (monophony); then add chords to harmonize it. Right off the bat you've "enhanced" it (at least from a Western tonal perspective), brought it from 2D into 3D if you will. But there's usually a "simplest, obvious" choice. This stays close to the tonic, and uses "basic building block" chords like I, IV, and V. For example, I might harmonize your "A B C | D C B" melody simply with an A minor chord in the first measure and an E major (V) in the second measure.
But composers and arrangers have always enjoyed the challenge of making more inventive harmonic choices. Bach wrote hundreds of harmonizations of simple short melodies (chorales), and often wrote several different harmonizations of one given chorale melody, showing how there could be more than one approach. And yes, you could even harmonize a tune with a different key than the "obvious" one. (This is often done in with techno "remixes," harmonizing an originally major melody with minor.) I could probably recast your melody to be in C major, so that the first measure "A B C" could become IV, V, I.

But the whole thing sounds different from how melody sounds alone which is really a disaster.

Is it, though? As PiedPiper suggested, if you don't like it, do something different. (And keep in mind, there's no rule that you have to harmonize at all! There's a lot of room for monophony even today.) But consider trying different harmonizations, until it changes your perception of the melody in a way that you do like.
Answer: Let's assume we really are in A minor. That somehow the key is established.
Minor is type of interval quality between two pitches. For example, a minor third, which is two tones three semi-tones apart. In the key of A minor the third tone of the scale, which is C, is a minor third above the A. That particular minor third is what give the key its minor quality.
With the key A minor already established, if you play the single tone A, that single tone A should provide a sense of the minor quality, even though there are no other tones to make that explicit. This comes from the actual A and its implied relationship to the C.
Additionally, that single tone A has an implied relationship with the tonic chord of A minor. That chord is spelled A C E, and importantly the A is the chord root of that chord.
That makes the single A carry the characteristics of both the tonic of the key and the chord root of the key's tonic chord.
If you harmonize A with tones A F C, that is an F major chord. That chord's root is F while the A is the third of the chord. The interval between F and A is a major third.
So, the things that "sounds different" are:

A changes its role from (at least implied) chord root to the chord's third.
Relative to the root of the F major chord the A is part of a major third.
Relative to the root of the (implied) A minor chord the A is part of a minor third.

Why chords make melody sound different?

That phenomena is essential what the art of harmony is all about!
Relative relationships are very, very important in harmony.
When a pitch is harmonized the principle harmonic relationships to pay attention to are:

the relationship of a pitch to the tonic of a key
the relationship of a pitch in a chord to its chord root
intervals, the relationship between two pitches

To illustrate how those three relationships differ let's consider pitch F in the key C major and harmonized in a V4/2 chord (or chord symbol G7/F), which spelled vertically would be F G B D:

F is the subdominant, the fourth scale degree, of C major
F is a minor seventh above the chord root G in chord G7
F is a major second below G in G7/F

Instead of just saying a pitch "sounds different", based on those different relative relationships, we can say things like: F is a tendency tone in C major that wants to resolve to E, F is an unstable chord tone in G7, and F forms a dissonant major second when it is the bass in G7/F.

I couldn't find answer to it on the internet. No one is talking about this.

A good, college level harmony textbook will cover all of these ideas.

Why chords make melody sound different?


Data management of a representative sample

Question: In our original database there are some variables which are quantitative, but actually they are categorical variables. Our question is, should categorization be done in the original database or directly in the representative sample, or is it the same to do both ways?
Comment: Thanks for the extra detail, but clarify by editing the question, not by adding comments.
Comment: Your question doesn't seem specific to R at all, so don't mention that in the title. More crucially it is quite unclear. Do you mean that some variables have been imported in a way that surprises you? That could be specific to R, and if so arguably off-topic here. but without code or examples it is difficult to comment.
Comment: We wonder if data management (here creating categorical variables out of numeric variables, dealing with missing data etc.) should be done in the original database and then create the representative sample for further analyses, or directly do the data management part in the sample. Thanks.
Comment: I don't find that any clearer. What is a representative sample (it's very far from an agreed standard term)? Why should it make any difference? No examples here to clarify.
Comment: May be i should have thought to explain the context bit more. Here we had a database with around 60,000 observations and we had to do survival analysis. The Schoenfeld plots which we created were very unclear due to the large number of data. So we decided to create a sample, out of the initial population. After checking that the distributions of the variables were similar in both initial database and the sample, we concluded it was representative sample. Then we realized there were some variables in numeric form, but which had to be categorized.
Answer: My recommendation is to focus on the goal.
If the goal is to improve the data structure and geometry, then I would recommend doing any change on the database itself.
If the goal is mainly to prepare the data for the analysis, then this is generally package specific (e.g. R or Stata) and is best done with the package code itself.
In any case, keep track of any changes and ensure everything can be reversed.


how to config nginx when the server make redirect

Question: I configured my Nginx to locate /doc to one of my local servers, just like this:
  location /doc {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;
        proxy_pass http://127.0.0.1:8000;
        proxy_redirect off;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header   X-Forwarded-Proto $scheme;
  }

Then my server on 8000 port will make a redirect to /message/html
This is the problem...
The correct URL should be /doc/message/html
How can I config my Nginx to redirect the URL of /redirected_by_port_8000_server  to /doc/redirected_by_port_8000_server in the location /doc block
Comment: Take a look at the [`proxy_redirect`](http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_redirect) directive. Use `curl -I` to identify the exact value of the `Location` response header that needs to be matched.
Answer: Many thanks to @Richard Smith.
I used curl -I checked the redirect location and changed my Nginx config file below:
  location /doc {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;
        proxy_pass http://127.0.0.1:8000;
        proxy_redirect https://$http_host https://$http_host/doc; #this will rewrite the redirect Location header
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header   X-Forwarded-Proto $scheme;
  }

Answer: You have to rewrite the URI. In nginx you will be able to pass /doc at the beginning of the URI by adding / at the end of the proxy_pass statement. It looks like below. Such that http://whatever/doc -> http://127.0.0.1:8000/doc
proxy_pass http://127.0.0.1:8000/;

However, the next proxy should rewrite by itself the /doc path and add it at its beginning. In nginx it would look like.
location /doc {
    rewrite ^/(.*) /$1/message/html/ break;
    proxy_pass http://127.0.0.1:8000/;
}


How to calculate $s.e. Md_{est}$ from $Md$ using Delta method?

Question: I've calculated the $\theta_{est}$ using MLE for the exponential distribution (with parameter $\theta$).
Then I've calculated the median $Md$ using $\theta_{est}$.
How can I use the Delta method to calculate $s.e. Md_{est}$?
The Delta method (for estimating $Var(\theta)$) requires function $g(\gamma)$ and a "parametrization" $\gamma$ of $\theta$. Then
$$Var(\theta)=g'(\gamma)^2Var(\gamma)$$
But what to use as $\gamma$ to get $Var(Md_{est})$?
Could I use $\gamma=\theta_{est}$ since that's the only thing I have here? But isn't its derivative 0? What about using $\gamma= \frac{1}{\theta} = \text{mean of X~exp}$?
Comment: Are you sure you need the delta method?
Answer: You don't need the delta method here!  The density function of the exponential distribution https://en.wikipedia.org/wiki/Exponential_distribution is
$$
f(x;\theta) = \frac1\theta e^{-x/\theta}, \qquad x> 0
$$
Then you can find the likelihood function, maximize it to find the maximum likelihood estimator $\hat{\theta} = \bar{x}$ which has variance $\theta^2/n$.  But we can calculate that the median is $M=\ln 2 \theta$ so the variance of the maximum likelihood estimator of the median is simply $(\ln 2)^2 \theta^2 / n$.  No need for delta method here.


How to automatically assign child taxonomy terms?

Question: I'm building a virtual network like Instagram but its contents (images) are about a certain event.  The strategy of selecting taxonomy terms is to display all of the tags (about 20 ones) and a checkbox and users can check any one of them. I use ttr_configurable_widget to do so.
The problem is there are many synonyms for a word and I don't want to display the synonyms, as an example in tagging the words female, women, girl, sister, daughter, lady are almost the same so when some one search for female the lady tag should be searched as well, furthermore this tag should be displayed as a hidden element in the web page(for search engines)
So there is a main tag like women and a set of synonyms. What I need to do is to format the tags as follow

Then only display the woman, when a user selects woman its synonyms also be attached to the content.
It is also preferred to load the synonyms but hide them in the node display page.
How can I do this?
The Taxonomy Term Reference Tree Widget and Taxonomy Group Fields are almost doing this but in these widgets users can check or uncheck the children even if the parent is selected.
Comment: Let them be loaded and hide with JQuery
Answer: The best way to achieve this job is using JQUERY,load all terms in the page  ,hide all of  children  terms and when the parent term checked show the children terms of it( also when unchecked hide all children of it).


How to get email id and address from contacts

Question: Hi i am trying to get email address from android contacts.i am trying like below but from this code i am getting ph number pls help me.
Cursor pCur = cr.query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
            null, null);
    String email = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));

Answer: You need to change the DataKind to Email.  Try this:
Cursor pCur = cr.query( ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, null, null, null);
String email = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));


Jquery script like google image preview

Question: I am looking a script (example in web) like google images preview. I have attached an image what I am looking for

I have spend a time of looking such script / example but nothing. If someone know a name or a link please give it to me.
Comment: http://www.tripwiremagazine.com/2013/03/jquery-slider.html
Answer: I have found a script but it's not exactly like Google Image's but has the same functionality. The script is free and is coded in HTML with CSS and JavaScript.

Click here to view the script

Jquery script like google image preview