C free(): invalid pointer allocated in other function

Question: I'm new in StackOverflow. I'm learning C pointer now.
This is my code:
#include <stdio.h>
#include <stdlib.h>

int alloc(int* p){
    p = (int*) malloc (sizeof(int));
    if(!p){
        puts("fail\n");
        return 0;
    }
    *p = 4;
    printf("%d\n",*p);
    return 1;
}

int main(){

    int* pointer;

    if(!alloc(pointer)){
        return -1;
    }else{

        printf("%d\n",*pointer);
    }

    free(pointer);

    return 0;
}

I compile with: gcc -o main main.c
error: free(): invalid pointer: 0xb77ac000 ***
what's wrong with my code?
Comment: Also, you [shouldn't cast the value returned by `malloc`](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc).
Comment: you never change `pointer`
Answer: Arguments in C are always passed by value. So, when you call alloc(pointer), you just pass in whatever garbage value pointer contains. Inside the function, the assignment p = (int*)... only modifies the local variable/argument p. Instead, you need to pass the address of pointer into alloc, like so:
int alloc(int **p) {
    *p = malloc(sizeof(int)); // side note - notice the lack of a cast
    ...
    **p = 4; // <---- notice the double indirection here
    printf("%d\n", **p); // <---- same here
    return 1;
}

In main, you would call alloc like this:
if (!(alloc(&pointer))) {
    ....

Then, your code will work.
Comment: malloc(sizeof(int)) work. Why malloc(sizeof(int*)) ?
Comment: @Drew: `sizeof **p` would be even better.
Answer: Everything in C is pass-by-value. This means that functions always operate on their own local copy of what you pass in to the function. Usually pointers are a good way to mimic a pass-by-reference scheme because a pointer and a copy of that pointer both contain the same memory address. In other words, a pointer and its copy both point to the same space.
In your code the issue is that the function alloc gets its own local copy of the pointer you're passing in. So when you do p = (int*) malloc (sizeof(int)); you're changing the value of p to be a new memory address, but the value of pointer in main remains unchanged.
You can get around this by passing a pointer-to-a-pointer, or by returning the new value of p.
Answer: You have two major problems in your code.
First, the alloc function creates a pointer via malloc, but never frees it, nor does it return the pointer to the calling function. This guarantees the memory the pointer addresses can never be freed up via the free command, and you now have memory leaks.
Second, the variable, int* pointer in main, is not being modified as you would think. In C, function arguments are "passed by value". You have two ways to address this problem:

Pass a pointer to the variable you want to modify (in your case, a pointer to a pointer to an int)
Have the function return the pointer to the function that called it.

Here are two implementations of my recommendations:
Approach 1

#include <stdio.h>
#include <stdlib.h>

int alloc(int** p);

int alloc(int** p) {
   if (!p) {
      printf("Invalid argument\n");
      return (-1);
   }
   if ((*p = (int*)malloc(sizeof(int))) == NULL) {
      printf("Memory allocation error\n");
      return (-1);
   }
   **p = 123;
   printf("p:%p - *p:%p - **p:%d\n", p, *p, **p);
   return 0;
}

int main(){
   int* pointer;

   if(alloc(&pointer) != 0){
      printf("Error calling function\n");
   }else{
      printf("&pointer:%p- pointer:%p- *pointer:%d\n", &pointer, pointer, *pointer);
   }

   free(pointer);

   return 0;
}

Sample Run for Approach 1

p:0xbfbea07c - *p:0x8656008 - **p:123
&pointer:0xbfbea07cointer - pointer:0x8656008ointer - *pointer:123

Approach 2

#include <stdio.h>
#include <stdlib.h>

int* alloc(void) {
   int* p;
   if ((p = (int*)malloc(sizeof(int))) == NULL) {
      printf("Memory allocation error\n");
      return (NULL);
   }
   *p = 123;
   printf("p:%p - *p:%d\n", p, *p);
   return p;
}

int main(){
   int* pointer = alloc();

   if(pointer == NULL) {
      printf("Error calling function\n");
   }else{
      printf("&pointer:%p- pointer:%p- *pointer:%d\n", &pointer, pointer, *pointer);
   }

   free(pointer);
   pointer = NULL;

   return 0;
}

Sample Run for Approach 2

p:0x858e008 - *p:123
&pointer:0xbf9bb1ac- pointer:0x858e008- *pointer:123

Answer: You are passing the pointer by value into your alloc function. Although that function takes a pointer to an int, that pointer itself cannot be modified by the function. If you make alloc accept  **p, set *p = ..., and pass in &pointer from main, it should work.
#include <stdio.h>
#include <stdlib.h>
int alloc(int** p){
  *p = (int*) malloc (sizeof(int));
  if(!*p){
    puts("fail\n");
    return 0;
  }
  **p = 4;
  printf("%d\n",**p);
  return 1;
}
int main() {
  int* pointer;
  if(!alloc(&pointer)){
    return -1;
  } else {
    printf("%d\n",*pointer);
  }
  free(pointer);
  return 0;
}

Answer: If you want a function to write to a non-array parameter of type T, you must pass a pointer to that parameter.
void func( T *ptr )
{
  *ptr = new_value;
}

void foo ( void )
{
  T var;
  func( &var ); // writes new value to var
}

If T is a pointer type Q *, it would look like
void func( Q **ptr )
{
  *ptr = new_pointer_value;
}

void foo ( void )
{
  Q *var;
  func( &var ); // writes new pointer value to var
}

If Q is a pointer type R *, you would get
void func( R ***ptr )
{
  *ptr = new_pointer_to_pointer_value;
}

void foo ( void )
{
  R **var;
  func( &var ); // writes new pointer to pointer value to var
}

The pattern is the same in all three cases; you're passing the address of the variable var, so the formal parameter ptr has to have one more level of indirection than the actual parameter var.
One sylistic nit: instead of writing
p = (int *) malloc( sizeof (int) );

use
p = malloc( sizeof *p );

instead.
In C (as of the 1989 standard), you don't need to cast the result of malloc; void pointers can be assigned to other pointer types and vice versa without needing a cast (this is not true in C++, but if you're writing C++, you should be using the new operator instead of malloc anyway).  Also, under the 1989 version of the language, using the cast would mask a bug if you forgot to include stdlib.h or otherwise didn't have a declaration for malloc in scope.  That hasn't been a problem since the 1999 version, though, so now it's more a matter of readability than anything else.
The type of the expression *p is int, so the result of sizeof *p is the same as the result of sizeof (int).  This way, if you ever change the type of p, you don't have to modify the malloc call.
To allocate an array of values, you'd use something like
T *p = malloc( sizeof *p * NUM_ELEMENTS );

or, if you want everything to be zeroed out initially, use
T *p = calloc( sizeof *p, NUM_ELEMENTS );


javascript non multi-touch events

Question: I am developing a small embedded application which uses a resistive touch screen (ADS 7846) that does not support multi-touch gestures.
The problem is that when using a finger (or other object) to touch the screen, the mousedown event only gets fired when the finger is released, if fact both the mousedown and mouseup events get fired only when the finger is removed.
function $(id) {return document.getElementById(id)};

$("butsetup").addEventListener("mousedown", function(e) {
  alert('down');
});

$("butsetup").addEventListener("mouseup", function(e) {
  alert('up');
});

Is there a solution to make this work as expected ?
As suggested by @antyrat this reports true:
alert( 'ontouchstart' in document.documentElement )

But I read somewhere that some browsers 'expose' this capability to the dom but do not enable it ?
Answer: Yes, you can use touchstart and touchend events:
$("butsetup").addEventListener( ('ontouchstart' in document.documentElement) ? "touchstart" : "mousedown", function(e) {
  alert('down');
});

$("butsetup").addEventListener( ('ontouchstart' in document.documentElement) ? "touchend" : "mouseout", function(e) {
  alert('up');
});

Comment: Thanks, I already tried that touchstart and touchend do not fire at all !
Comment: can you try run in console "'ontouchstart' in document.documentElement"? And look what it return?
Comment: Thanks, unfortunately there is no javascript console, I am using midori on a 320 x 240 screen!
Comment: so try then use this: `alert( 'ontouchstart' in document.documentElement )`
Comment: Yes, that reported true !
Comment: So problems seems to be in other place. Touch events should work. Try to use debugger. And what framework are you using? As I see you have `$` sign. If you use jQuery `$("butsetup").on` should be instaed of `addEventListener`. Also `butsetup` not seem like correct selector, if it's class name should be `.butsetup`
Answer: Use touchstart and touchend events .
$("butsetup").addEventListener("touchstart", function(event){
    alert('touchstart');
}, true);

$("butsetup").addEventListener("touchend", function(event){
    alert('touchend');
}, true);

Comment: Thanks, but the touchstart and touchend events do not fire.
Comment: I think is something wrong with the element or the jquery. does touchstart return any objects or is null? These events tested and works fine!
Comment: oops sorrie, I am not using jquery, $() is an alias to document.getElementById()
Comment: oouf :) this happens!

javascript non multi-touch events


Odd ratio for binomial variable values

Question: I am calculating the odd ratio of logistic regression (using statsmodel of Python). I have one independent variable (i.e. process type: faulty (1) or non-faulty (2) and one dependent variable (i.e. process-time: late (0) or on-time (1)). I calculated the odd ratio at C.I 95% using logistic regression (I used statsmodel of Python). I got the following value:
<code>                    5%        95%      Odds Ratio
Process type    1.431001    1.541844    1.485389
</code>
I interpreted the above odds ratio as "Increasing from 1 to 2 for Process type (i.e. going from a faulty to non-faulty) is associated with an increased in the odds by 48% of completing the process on time."
My first question: is my interpretation correct?
As the independent variable is nominal in nature, do I need to calculate the separate odd ratio for each value type of independent variable (i.e. one odd ratio for faulty values and one add ratio of non-faulty values)? My understanding is that as I am using logistic regression to calculate odds ratio so I should be using an independent variable that has at least two types of nominal variable values. I can not calculate for a single type of nominal value.
Could anyone shed some light on it?
Comment: just confirming, non-faulty is your control group?
Comment: Non-faulty is one of the value type of independent variable.  What do you mean by control group???
Comment: For the interpretation, are you comparing faulty to non-faulty or non-faulty to faulty?
Comment: @jros non-faulty to faulty
Answer: The interpretation should be adjusted slightly to something more similar to:
The odds of a non-faulty process experiencing an on-time process-time are 48% greater than the odds of a faulty process experiencing an on-time process-time.
In order to calculate the odds ratio for faulty process, just flip the odds ratio (1/1.485).
The coefficients of a logistic regression rely on comparison, so even continuous, numerical independent variables have an comparative interpretation
Comment: Thanks for the reply. I read from the link (https://www.statology.org/interpret-odds-ratio-less-than-1/) where single odd ratio was used to compare odd of both value types

Odd ratio for binomial variable values


Build the graph of a function with absolute value.

Question: The function is:
And my idea of graphic (i did it using two graphs and deleting some parts)

Is it correct?
Answer: Your choice of scale makes the graph a bit difficult to interpret, but it appears you correctly graphed $y = x^2 + 3$ when $|x| > 1$.  However, you incorrectly graphed $y = |x + 2| + |x - 1|$ in the interval $[-1, 1]$.
Since $x - 1 \geq 0$ if $x \geq 1$ and $x - 1 < 0$ if $x < 1$,
\begin{align*}
|x - 1| & =
\begin{cases}
x - 1 & \text{if $x \geq 1$}\\
-(x - 1) & \text{if $x < 1$}
\end{cases}\\
& =
\begin{cases}
x - 1 & \text{if $x \geq 1$}\\
-x + 1 & \text{if $x < 1$}
\end{cases}
\end{align*}
Since $x + 2 \geq 0$ if $x \geq -2$ and $x + 2 < 0$ if $x < -2$,
\begin{align*}
|x + 2| & =
\begin{cases}
x + 2 & \text{if $x \geq -2$}\\
-(x + 2) & \text{if $x < -2$}
\end{cases}\\
& =
\begin{cases}
x - 1 & \text{if $x \geq -2$}\\
-x - 2 & \text{if $x < -2$}
\end{cases}
\end{align*}
Putting these rules together yields
\begin{align*}
|x + 2| + |x - 1| & =
\begin{cases}
x + 2  + x - 1 & \text{if $x \geq 1$}\\
x + 2 - (x - 1) & \text{if $-2 \leq x < 1$}\\
-(x + 2) - (x - 1) & \text{if $x < -2$}
\end{cases}\\
& =
\begin{cases}
2x + 1 & \text{if $x \geq 1$}\\
3 & \text{if $-2 \leq x < 1$}\\
-2x - 1 & \text{if $x < 1$}
\end{cases}
\end{align*}
If $|x| \leq 1$, then $-1 \leq x \leq 1$.  If $-1 \leq x < 1$, then the rule for $-2 \leq x < 1$ applies, so $$y = |x + 2| + |x - 1| = 3$$  If $x = 1$, then the rule for $x \geq 1$ applies, so $$y = |x + 2| + |x - 1| = 2x + 1 = 2 \cdot 1 + 1 = 2 + 1 = 3$$  Thus, in the interval $[-1, 1]$, the graph of $y = |x + 2| + |x - 1|$ lies on the horizontal line $y = 3$.
The graph of the function
$$
y =
\begin{cases}
x^2 + 3 & \text{if $|x| > 1$}\\
|x + 2| + |x - 1| & \text{if $|x| \leq 1$}
\end{cases}
$$
is sketched below.  While the grid lines make it somewhat difficult to tell, the circles at the points $(1, 3)$ and $(-1, 3)$ are filled since these points are on the graph while the circles at the points $(1, 4)$ and $(1, -4)$ are empty since these points are not on the graph.
Answer: The green parts are correct, but try to look at the blue part again. For example, we have
$$
f(1) = |1-1| + |1+2| = 3.
$$


Create a percentage discount coupon with a maximum value

Question: Need to have a coupon that follows this basic logic:
<code>IF (Commerce % Coupon Granted amount > Max Value) THEN
    Commerce % Coupon amount = Max Value
ELSE
    Commerce % Coupon amount = % of ORDER
</code>
For example:
10% with a max of $100.

Order value = 500, Discount = 50 (10% of 500)
  Order value = 1000, Discount = 100 (10% of 1000)
  Order value = 1500, Discount = 100 (flat 100)
Answer: If you're using the latest version of Commerce Discount and Commerce Coupon, you can accomplish this with just two rules connected to a single coupon code.

Create a Coupon Code by going to Admin→Store→Coupons->Create Coupon Code. Save it.
Create a new Discount (Admin→Store->Discounts->Create). Set it to Order Discount and add a Total amount condition. Set the condition to less than and the amount to 2000. Set the percentage discount as you desire. Finally, add the coupon code from step 1 to this discount and save it.
Create a another Discount. Set it to Order Discount and add a Total amount condition. Set the condition to greater than or equal to and the amount to 2000. Set the flat discount as you desire. Finally, add the coupon code from step 1 to this discount and save it.

Now, when a customer checks out, the coupon will attempt to apply both discounts, but because of the condition, only one will apply: $200 if the order is $2000 or over, and 10% if the order is $1999.99 and under.


What is the number of unique permutations in a list with repeated elements, if they are also considered equal under a phase shift?

Question: This is similar to many questions asked before, but none seem to need to be unique under a phase shift as well.
Basically, my problem is, how many unique combinations in a group of 11 are there, if there need to be 5 A's and 6 B's.
For example [A,A,B,A,B,B,B,A,B,B,A]. However, they must also have to be unique when shifted. So for example, that set would be equivalent to [A,B,A,B,B,B,A,B,B,A,A].
I hope the explanation makes sense. Thank you.
Comment: What does "shifted" mean here? Please be a bit more specific.
Comment: Wouldn't this be the same as a seated around a circular table arrangement? You can look up problems of that ilk.
Comment: So a shift would be to move the group one element to the left, and then to place the element from the start at the end, similar to the two groups in the question.
Comment: Quite possibly this question refers to Polya counting using the cycle indices of the cyclic / dihedral group (necklaces and bracelets). The simplest case is when the number of slots is prime.
Answer: Imagine you place these $A$'s and $B$'s in a line of length $11$. From $11$ choose $5$ places for the $A$'s, and from the remaining $11-5=6$ choose $6$ places for the $B$'s. Because a given arrangement can be shifted over $11$ times and still be counted as just one arrangement, we divide the total number by $11$. Therefore we get $$\frac {\binom {11}{5} \binom {6}{6}}{11}=42$$
In the general case, with $n$ $A$'s and $m$ $B$'s, we have, by the same logic $$\frac {\binom {n+m}{n} \binom {n+m-n}{m}}{n+m}$$
Comment: I think that might be just what I need, thank you. One quick question, would this be a more difficult calculation to make if the length was not a prime number, and instead was 10 or 8, as there are more symmetries within the combinations?
Comment: @Luke I added some details.
Comment: Ah thank you that is great. Sorry to keep asking questions, but, so if i were to have 4 A's and 4 B's, unless I've calculated it wrong, it seems to come out as 8.75 combinations, am I doing something wrong?
Comment: This formula is correct only when $n+m$ is a prime number and $n, m \ne 0$, because in that case an arrangement and its shifted iterates form a set of $n+m$ different arrangements. When $n+m$ is not prime, it is not always the case. By the way $\binom{n+m-n}{m} = 1$
Comment: @Luke for those more complicated cases, you need to consider when are arrangements overcounted $10$ times and when they are overcounted less than $10$ times. This can be done using Burnside's lemma, which says that given a number of patterns, you can find those distinguishable up to motions (in this case rotations) by finding the average that are fixed by one of these motions.


How to compute cache bit widths for tags, indices and offsets in a set-associative cache and TLB

Question: Following is the question:

We have memory system with both virtual of 64-bits and physical
  address of 48-bits. The L1 TLB is fully associative with 64 entries.
  The page size in virtual memory is 16KB. L1 cache is of 32KB and 2-way
  set associative, L2 cache is of 2MB and 4-way set associative. Block
  size of both L1 and L2 cache is 64B. L1 cache is using virtually
  indexed physically tagged (VIPT) scheme.

We are required to compute tags, indices and offsets. This is the solution that I have formulated so far:

page offset = log base 2(page size)=14bits
Block offset=log base 2 (block size)= 6 bit
virtual page number =virtual address-pageoffset= 64-14= 50 bits
L1 cache index =page offset - block offset= 8 bits
L1 tag=Physical address-L1 index-block offset= 50 bits
TLB index= log base 2 (64/64)=0 bits {since it is fully associative and whole cache can be thought of as one set.}
TLBtag= virtual page number - index=50 bits
L2 cache index= log base 2 ( cache size/ (block size * ways)) 13bits
L2 tag= 21 bits

For reference:

This is the solution that I have calculated.Please tell if wrong.
Thanks in advance :)
Comment: The page offset is the low 14 bits of the address: 16kiB = 2^14 bytes.
Comment: You should probably leave in *how* you worked out the values for each cache parameter; that makes it easier for people to see if you're right without having to actually do all the work in their head.
Comment: @PeterCordes just added full calculations. Hope this helps understand it better :)
Answer: Looks right.
You should really calculate L1D index bits the same way you do for L2: log2(32KiB / (64B * 2)) = log2(256) = 8 bits.
Calculating the L1 index bits as page offset - block offset is only possible because your diagram shows you that your cache has the desirable property that all the index bits are page-offset bits.  (So for aliasing behaviour, it's like a PIPT cache: homonyms and synonyms are impossible.
 So you can get VIPT speed without any of the aliasing downsides of virtual caches.)
So I guess really calculating both ways and checking is a good sanity check.  i.e. check that it matches the diagram, or that the diagram matches the other parameters.
It's also not required that L1D index+offset bits "use up" all the page offset bits: e.g. increasing L1D associativity would leave 1 or more page-offset bits as part of the tag.  (This is fine, and wouldn't introduce aliasing problems, it just means your L1D isn't as big as it could be for a given associativity and page size.)
It is common to build caches this way, though, especially with smaller page sizes.  For example, x86 has 4k pages, and Intel CPUs have used 32kiB / 8-way L1D for over a decade.  (32k / 8 = 4k).  Making it larger (64kiB) would also require making it 16-way associative, because changing the page size is not an option.  This would start to get too expensive for a low-latency high throughput cache with parallel tag + data fetch.  Earlier CPUs like Pentium III had 16kiB / 4-way, and they were able to scale that up to 32kiB / 8-way, but I don't think we should expect larger L1D unless something fundamental changes.  But with your hypothetical CPU architecture with 16kiB pages, a small+fast L1D with more associativity is certainly plausible.  (Your diagram is pretty clear that the index goes all the way up to the page split, but other designs are possible without giving up the VIPT benefits.)
See also Why is the size of L1 cache smaller than that of the L2 cache in most of the processors? for more about the "VIPT hack" and why multi-level caches are necessary to get a combination of low-latency and large capacity in practical designs.  (And note that current Intel L1D caches are pipelined and multi-ported (with 2 reads and 1 write per clock) for access widths up to 32 bytes, or even all 64 bytes of a line with AVX512.  How can cache be that fast?.  So making L1D larger and more highly associative would cost a lot of power.)
Comment: Update: Ice Lake did increase L1d to 48kiB by making it 12-way set associative. ([How does the indexing of the Ice Lake's 48KiB L1 data cache work?](https://stackoverflow.com/q/59809991))  The associativity doesn't have to be a power of 2, unlike the number of sets or the line size (otherwise you'd have to actually divide the address, instead of just take bit-ranges).  Also, apparently there are CPU-architecture design tricks that could have been used to do that other ways, without making it more associative.


Prove that $\text{rank}(T) = \text{rank}([T]_{\beta}^{\gamma})$.

Question: Let $T:V\to W$ be a linear transformation between finite-dimensional vector spaces, and let $\beta$ and $\gamma$ be ordered basis for $V$ and $W$, respectively. Then $\text{rank}(T) = \text{rank}([T]_{\beta}^{\gamma})$.
MY ATTEMPT
Before presenting this theorem, the author defines $\text{rank}(A) = \text{rank}(L_{A})$, where $L_{A}:\textbf{F}^{n}\to\textbf{F}^{m}$ is the linear transformation defined by $L_{A}x = Ax$.
But we know that
$$\text{rank}(L_{A}) = \dim\text{span}\{L_{A}(e_{1}),L_{A}(e_{2}),\ldots,L_{A}(e_{n})\}$$
Moreover, $L_{A}(e_{j}) = a_{j}$, where $a_{j}$ is the $j$-th column of $A$. Consequently, $\text{rank}(A)$ equals the dimension of its column space.
Based on it, I do not know how to proceed. Am I on the right track?
This question has already been solved here, but the textbook has not presented the fact that invertible linear mappings preserve rank so far. Is there another way to solve it? Or should I insist a little bit more on it?
Answer: Exercise. Let $V_1$ and $V_2$ two finite dimensional vector spaces over the same field. Then, if $f : V_1 \to V_2$ is a linear isomorphism, for any subspace $S$ of $V_1$, $f(S)$ is a subspace of $V_2$ such that $\dim f(S) = \dim S$.
Once you are proved this simple exercise, suppose $\beta = \{v_1,\dots,v_n\}$ and $\gamma = \{w_1,\dots,w_m\}$. Define $\phi_\beta : V \to \mathbf F^n$ by
$$\phi_\beta \Big( \sum_{i=1}^n a_iv_i \Big) = \sum_{i=1}^n a_ie_i = \begin{pmatrix}
a_1 \\ \vdots \\ a_n
\end{pmatrix},$$
and similarly for $\phi_\gamma : W \to \mathbf F^m$. It is easy to see that $\phi_\beta$ and $\phi_\gamma$ are linear isomorphisms and that the following diagram
$$
\require{AMScd}
\begin{CD}
V @>{T}>> W\\
@V{\phi_\beta}VV @VV{\phi_\gamma}V \\
\mathbf{F}^n @>>{L_A}> \mathbf{F}^m
\end{CD} \qquad \textrm{where } A := [T]_\beta^\gamma
$$
commutes, that is, $\phi_\gamma \circ T = L_A \circ \phi_\beta$. Then, if we take $V_1 = \mathbf F^m$, $V_2 = W$, $f = \phi_\gamma^{-1}$ and $S = L_A(\mathbf F^n)$ in the preceding exercise, $\phi_\gamma^{-1}(L_A(\mathbf F^n))$ is a subspace of $W$ with the same dimension of $L_A(\mathbf F^n)$, i.e., with dimension $\operatorname{rank}(A)$. But also, since $\phi_\beta$ is surjective, $\mathbf F^n = \phi_\beta(V)$, and then
$$\phi_\gamma^{-1}(L_A(\mathbf F^n)) = \phi_\gamma^{-1}(L_A(\phi_\beta(V))) = T(V).$$
Comment: Thanks for the explanation! It has helped me to grasp the details.


which query is better to get DATE + 23:59:59

Question: SELECT DATEADD(hh, 23, DATEADD(mi,59 ,  DATEADD(ss,59 , '2019-09-22 00:00:00.000')))
SELECT DATEADD(dd,1, DATEADD(ss, -1 , '2019-09-22 00:00:00.000'))

result

2019-09-22 23:59:59.000
2019-09-22 23:59:59.000

both have same result but witch is better as performance
Comment: When I was much, much younger I used to spend days working on what was the most efficient way to do something. But the fact is, unless you are doing this a billion times, it is very, very unlikely to make one iota of a difference.
Comment: On the other hand it is much more important to make your expression as "readable" as possible (for us humans).
Answer: Neither is "better".  There can be multiple ways to express something in SQL.  For instance, here are some other ways:
select convert(datetime, '2020-09-22') + convert(datetime, '23:59:59')
select datetimefromparts(2020, 09, 22, 23, 59, 59, 0)
select convert(datetime, '2020-09-22' + ' 23:59:59')

For your particular examples, the first has three function calls and the second has two.  That would normally mean that the second is a wee, wee bit faster.  However, the compiler probably pre-calculates these anyway, so that doesn't make a difference.
More important is why you would want to do this.  I have see this type of calculation used to support between with datetime values:
where getdate() between startdt and enddt

If that is your intention, fix your logic.  It is much better to have the upper bound be non-inclusive, so you write:
where getdate() >= startdt and getdate < enddt

Then the you can use '2019-06-23' for the end date, not worry about "getting the last second", and not having a bug where you miss the last second of every day.
Aaron Bertrand has an extensive discussion on the use of between with date/time values:  What do BETWEEN and the devil have in common?
Comment: @AkbarAsghari, I suggest the inclusive start and exclusive technique Gordon mentioned so that you don't miss rows with fractional seconds in the last second of a day (e.g. between '2019-09-22 23:59:59.003' and '2019-09-22 23:59:59.997').
Comment: My orginal date type is DATETIME


Find whether an Alternating Sequence is Convergent

Question: $$\sum _{n=2}^{\infty} \frac{\left(-1\right)^{n-1}}{\left(\ln \left(n\right)\right)^k} \quad \text{ for } k>0$$
By Leibniz's test if $a_n \to 0$ for an alternating sequence it is convergent, over here if I take the value of $k\rightarrow 0$ and $\lim _{n\to \infty }\left(a_n\right)$ then I would be able to say it is convergent. However, the limit appears to tend to $0$ when $k \to 0$ implying that the sequence is divergent. Am I right in this approach or am I doing something wrong while finding the limit. Is this series truly divergent?
Comment: $k$ is a fixed positive number. The question of letting $k \to 0$ does not arise.
Comment: On an **intuitive level** the *significance* of $~k~$ approaching $~0,~$ *from above* is that as $~k~$ decreases, one can **informally** say that the alternating series *takes longer* to converge.
Answer: The sequence has a term $a_n = \frac{\left(-1\right)^{n-1}}{\left(\ln \left(n\right)\right)^k } \to 0$ when $n \to \infty$, decreases in absolute value, and the sequence is alternating, so its sum converges.
(The proof of this classical result is: as $a_n$ decreases in absolute value and has alternating sign, $\forall N, \forall k > N$, the sum from $2$ to $k$ is bounded by the sums from $2$ to $N$ and from $2$ to $N+1$, an interval whose length is $|a_{N+1}|$ which $\to 0$ when $N \to \infty$. So the sequence of sums to $N$ is a Cauchy sequence, in a compact set (bounded and complete), so it converges).
You are confused by the fact that there is a parameter $k$. But $k$ is fixed for a given sequence, so you do not have to think about what happens when $k \to 0$.
By the way, when talking about a sequence whose successive terms are summed, the convention is to call it a series rather than sequence.
Comment: For the alternating series criterion, it's important that $|a_n|$ *decreases* as well as converges to $0$ (consider a series whose terms alternate between $1/n$ and $-1/n^2$).
Comment: @ronno Yes, thanks for noting that I forgot this condition.


Find joint density function, marginal and expected value

Question: Let $X_1$ and $X_2$ have joint density function:
$$f_{X_{1},X_{2}}\left(x_{1},x_{2}\right)=4x_{1}x_{2}, 0\leq x_{1}\leq1,
0\leq x_{2}\leq1$$
If $Y_{1}=X_{1}$ and $Y_{2}=X_{2}/X_{1}$
(a) Find the joint density function of $Y_{1}$ and $Y_{2}$.
(b) Find $P\left(Y_{2}\geq2\right)$
Solutions:
(a) I did this by using Jacobian method.
The inverse of the transformation is,
$$T^{-1}: X_{1}=Y_{1}$$
$$\qquad\qquad\quad\qquad\;X_{2}=Y_{2}X_{1}=Y_{2}Y_{1}$$
The jacobian of the transformation is:
$$J_{T^{-1}}:\:det\begin{bmatrix}1 & 0\\
y_{2} & y_{1}
\end{bmatrix}=y_{1}$$
Then, the joint density function of $Y_{1}$ and $Y_{2}$ is:
$$f_{Y_{1},Y_{2}}\left(y_{1},y_{2}\right)=4y_{2}y_{1}^{3}, 0\leq y_{1}\leq1
 , 0\leq y_{2}\leq\frac{1}{y_{1}}$$
(b) To do this, first i have to find the marginal density of $Y_2$.
I got the next result,
$$f_{Y_{2}}\left(y_{2}\right)=\int_{0}^{1}4y_{2}y_{1}^{3}dy_{1}+\int_{0}^{1/y_{2}}4y_{2}y_{1}^{3}dy_{1}=y_{2}I_{\left(0,1\right)\left(y_{2}\right)}+\frac{1}{y_{2}^{3}}I_{\left(1,\infty\right)\left(y_{2}\right)}$$
Next, I calculated $P\left(Y_{2}\geq2\right)$ in two ways. These are,

$P\left(Y_{2}\geq2\right)=\int_{2}^{\infty}\frac{1}{y_{2}^{3}}dy_{2}=-\frac{1}{2}\frac{1}{y_{2}^{2}}\biggr|_{y_{1}=2}^{y_{2}=\infty}=\frac{1}{8}$
$P\left(Y_{2}\geq2\right)=1-P\left(Y_{2}\leq1\right)=1-\int_{0}^{1}y_{2}dy_{2}=\frac{1}{2}y_{2}^{2}\biggr|_{0}^{1}=\frac{1}{2}$

My teacher said that all the procedures i did to calculate the joint density and the marginal are wrong. As the marginal is wrong, then the calculation of $P\left(Y_{2}\geq2\right)$ is wrong.
Then, I think something is wrong in my calculations because of the diferent results that i get in numbers 1 and 2.
Please help me to clarify the ideas.
Comment: Did your teacher give any advise as to how to proceed?  Because although this might not be what was expected, it certainly is *not wrong*!  (Well, *except* for that flub at the end.)
Comment: @Graham Kemp. Thanks for your response. I will ask him to show me how to proceed.
Answer:
My teacher said that all the procedures I did to calculate the joint density and the marginal are wrong.

Nope.   It looks okay.   Running through it my way seems to match with what you have.
The joint is correct.
$$\begin{align}f_{Y_1, Y_2}(y_1,y_2) & = f_{X_1, X_2}(y_1, y_1y_2)\cdot \lVert\frac{\partial(y_1,y_1y_2)}{\partial(y_1, y_2)}\rVert\\[1ex] & = 4(y_1)(y_1y_2)~\mathbf 1_{0\leq y_1\leq 1~,~ 0\leq y_1y_2\leq 1}\cdot\begin{Vmatrix}1 & 0\\y_2 & y_1\end{Vmatrix} \\ &= 4 ~ y_1^3 ~ y_2~\mathbf 1_{0\leq y_1\leq 1~,~ 0\leq y_2\leq y_1^{-1}} \end{align}$$
The marginal is then indeed a piecewise function, like so:
$$\begin{align}f_{Y_2}(y_2) &= \int_0^{\min(1,1/y_2)} f_{Y_1,Y_2}(t, y_2)\operatorname d t\cdot \mathbf 1_{0\leq y_2 <\infty}
\\ & = 4y_2\int_0^1 t^3 \operatorname d t\cdot \mathbf 1_{0\leq y_2<1}+4y_2\int_0^{1/y_2}4t^3\operatorname d t\cdot\mathbf 1_{1\leq y_2<\infty}
\\ & = y_2\mathbf 1_{0\leq y_2<1}+y_2^{-3}\mathbf 1_{1\leq y_2<\infty}
\end{align}$$
And so we have: $$\begin{align}\mathsf P(Y_2\geq 2) &= \int_2^\infty s^{-3}\operatorname d s \\[1ex]&= \frac 18\end{align}$$
Alternatively, ah, there is your mistake.   The complement of $Y_2\geq 2$ is not $Y_2\leq 1$.   This is the way to go:
 $$\begin{align}\mathsf P(Y_2\geq 2) &= 1-\mathsf P(Y_2<2)\\[1ex] &= 1-\int_0^1 s\operatorname d s-\int_1^2 s^{-3}\operatorname d s\\[1ex] & =1-\tfrac 12-\tfrac 38 \\[1ex] & = \tfrac 18\end{align}$$

Just to verify, let us do it the easy way.
$$\begin{align}\mathbf P(Y_2\geq 2) & = \mathbf P(X_1\leq X_2/2) \\[1ex] & =\int_0^1\int_0^{t/2} 4st\operatorname d s\operatorname d t \\[1ex] & = 4\int_0^1 t \int_0^{t/2} s\operatorname d s\operatorname d t \\[1ex] &= \tfrac 12 \int_0^1 t^3\operatorname d t \\[1ex] & = \tfrac 18\end{align}$$

tl;dr Everything checks out until the very end.   Get up and try again!


Direction of gradient vector

Question: How do we know that gradient always points in direction of greatest increase of function and not the greatest decrease?
Comment: Can you please give an example to validate this
Answer: Directional derivative along a normal vector $\vec{n}$ is
$$n_x\frac{\partial f}{\partial x}+n_y\frac{\partial f}{\partial y}+n_z\frac{\partial f}{\partial z}=(\vec{n}\cdot \nabla)f=\vec{n}\cdot(\nabla f)$$
Directional derivative along itself ($\vec{n}=\frac{\nabla f}{|\nabla f|}$):
$$\frac{1}{|\nabla f|}(\nabla f)\cdot(\nabla f)=|\nabla f|>0$$
while in the opposite direction, you get $-|\nabla f|$.
Comment: Can you please give an example to validate this
Comment: $f=x^2+y^2+z^2$. This is obviously increasing in the direction away from the center. Gradient: $\nabla f=(2x,2y,2z)$. Which of course is a vector that points away from the center. I used the directional derivative to demonstrate, because once you pick a direction, the derivative always just tells you the rate of change. I just upgraded this statement to the full gradient vector.
Comment: (Doubt)But also how is gradient at point is normal normal to it?
Answer: If $h = \nabla f(x) \neq 0$, then $df(x,h) \lim_{t \downarrow 0} {f(x+th)-f(x) \over h }= \langle h,h \rangle = \|h\|^2 > 0$. Hence for some $\delta>0$, if $t \in (0,\delta)$ then $f(x+th) > f(x)$.
Answer: When you take the partial derivatives, if a function in the direction of an axis is increasing, the corresponding value in the gradient is positive, while when it's decreasing, it's negative.
So, if it is increasing in that direction, the arrow points towards it. If it is decreasing in that direction, the arrow points away from it. This makes sure that the gradient always points in the direction of increase.
Answer: Each component of the gradient tells you how fast your function is changing with respect to the standard basis. It's not too far-fetched then to wonder, how fast the function might be changing with respect to some arbitrary direction? Letting v⃗  denote a unit vector, we can project along this direction in the natural way, namely via the dot product grad(f(a))⋅v⃗ . This is a fairly common definition of the directional derivative.
We can then ask in what direction is this quantity maximal? You'll recall that
grad(f(a))⋅v⃗ =|grad(f(a))||v⃗ |cos(θ)
Since v⃗  is unit, we have |grad(f)|cos(θ), which is maximal when cos(θ)=1, in particular when v⃗  points in the same direction as grad(f(a)).

Direction of gradient vector


How to make method entity_uri work when $entity_type is taxonomy_vocabulary?

Question: I have a table with entities of type content, taxonomy_vocabulary and terms. For content and terms, I can show a link to each detail page by using the method entity_uri.
But for entities with type taxonomy_vocabulary this does not work, entity_uri returns null.
What is the best way to get the url for a taxonomy_vocabulary entity?
Comment: Taxonomy doesn't come with a default page to view a vocabulary. So I guess that is why entity_uri has nothing to return in this case. I am happy to get the admin page for the vocabulary, but that is not what is pretended in most cases.
I think there should be a default detail page for each vocabulary, listing its terms. And then entity_uri should return that uri natively.
Answer: I hope it is not the best answer, because it requires customized code. But anyway, it is a possible solution and I'll share it.
<code>/**
 * Implements hook_entity_info().
 */
function mymodule_entity_info_alter(&$info) {
  if (isset($info['taxonomy_vocabulary'])) {
    $info['taxonomy_vocabulary']['uri callback'] = 'my_module_entity_info_uri_callback';
  }
}

/**
 * Return path for taxonomy_vocabulary entities
 */
function my_module_entity_info_uri_callback($taxonomy) {
  return array(
    'path' => 'admin/structure/taxonomy/' . $taxonomy->machine_name,
  );
}
</code>


How to use Bash to parallelise my PHP script

Question: I have a PHP script that loops through some urls. The urls are stored in urls.txt, and it needs to call the php script like php urlcheck.php LINE_FROM_urls.txt
When it reaches a set number of processes, I want it to sleep for 5 seconds, like this
COMCHECK=`ps aux | grep -c php`

while [ $COMCHECK -ge 150 ];do
COMCHECK=`ps aux | grep -c php`
echo "Sleeping"
sleep 5

and then I want it to check again. If its -le 150, run the next url etc.
I have no idea how to do this. My Bash is quite limited, and frankly, the language weirds me out.
Answer: while read URL; do
    while (( $(ps aux | grep -c php) >= 150 )); do
        sleep 5
    done

    php urlcheck.php "$URL" &
done < urls.txt

# Optional: wait for all PHP processes to finish.
wait

Answer: You can try something like:
limit=150

# read lines from the file urls.txt one by one.
while read line; do

        # check number of running php processes.
        while [ $(ps aux | grep -c php) -ge $limit ];do
                # if it's >= limit..sleep.
                echo "Sleeping"
                sleep 5
        done

        # limit not reached..run another process..in background.
        php urlcheck.php  $line &

done < urls.txt

Comment: This did the trick, and quite well I might add. Also, your code is very nice looking <3 Is there a way to stop it from outputting errors etc from the php file, other than removing error reporting on the php file?
Comment: To remove the errors spit by PHP you can replace `php urlcheck.php  $line &` by `php urlcheck.php  $line 2> /dev/null &`
Comment: Hey, sorry. One more thing. Is there a way I can make it remove each url from the file as it cycles through?


Nested Loop Optimisation in C and OpenMP

Question: Actually I have two questions, the first one is, considering cache, which one of the following code is faster?
int a[10000][10000];
for(int i = 0; i < 10000; i++){
    for(int j = 0; j < 10000; j++){
       a[i][j]++;
    }
}

or
int a[10000][10000];
for(int i = 0; i < 10000; i++){
    for(int j = 0; j < 10000; j++){
       a[j][i]++;
    }
}

I am guessing the first one will be much faster since there are a lot less cache miss. And my question is if you are using OpenMP, what kind of technique will you use to optimise such a nested loop? My strategy is to divide the outer loop into 4 chunks and assign them among 4 cores, is there any better way (more cache friendly) to do it?
Thanks!
Bob
Comment: You can test both on you platform. But I assume, 1st fastest. Also, question: Is array element must be int? Perhaps, enough short or char? By decrease element size, you will decrease memory traffic.
Answer: As maxihatop pointed out, the first one performs better because it has better cache locality.
Dividing the outer loop into chunks is a good strategy in the case like this, where the complexity of the task inside the loop is constant.
You might want to take a look at #pragma omp for schedule(static). This will evenly divide the iterations contiguously among threads. So your code should look like:
#pragma omp for schedule(static)
for (i = 0; i < 10000; i++) {
    for(j = 0; j < 10000; j++){
        a[i][j]++;
    }

Lawrence Livermore National Laboratory provides a fantastic tutorial of OpenMP. You can find more information there.
https://computing.llnl.gov/tutorials/openMP/


How to iterate products on for to get specific DOM elements with foreach on PHP 7

Question: I really don't know what's happening that I'm cannot iterate this object of data. The problem is that I always print the same object, but if I print a separate values, it's be there.
Each product has a hidden inputs and I'm reading it with DomDocument PHP library.
<input class="productName" id="03MJRUXE" type="hidden" value="Camisa Polo Masculina Flamê">
<input class="productId" id="03MJRUXE" type="hidden" value="03MJRUXE">
<input class="productPrice" id="03MJRUXE" type="hidden" value="69.99">
<input class="productCategory" id="03MJRUXE" type="hidden" value="Polos">
<input class="productBrand" id="03MJRUXE" type="hidden" value="Business">

Each product has a product-info div and each one product print the own DOMElement below:
DOMElement Object
(
    [tagName] => input
    [schemaTypeInfo] =>
    [nodeName] => input
    [nodeValue] =>
    [nodeType] => 1
    [parentNode] => (object value omitted)
    [childNodes] => (object value omitted)
    [firstChild] =>
    [lastChild] =>
    [previousSibling] => (object value omitted)
    [nextSibling] => (object value omitted)
    [attributes] => (object value omitted)
    [ownerDocument] => (object value omitted)
    [namespaceURI] =>
    [prefix] =>
    [localName] => input
    [baseURI] =>
    [textContent] =>
)
DOMElement Object
(
    [tagName] => input
    [schemaTypeInfo] =>
    [nodeName] => input
    [nodeValue] =>
    [nodeType] => 1
    [parentNode] => (object value omitted)
    [childNodes] => (object value omitted)
    [firstChild] =>
    [lastChild] =>
    [previousSibling] => (object value omitted)
    [nextSibling] => (object value omitted)
    [attributes] => (object value omitted)
    [ownerDocument] => (object value omitted)
    [namespaceURI] =>
    [prefix] =>
    [localName] => input
    [baseURI] =>
    [textContent] =>
)

...

I'll let a screenshot below:

And my function that iterate this elements is below:
/**
 * Extract info of the inputs.
 *
 * @param DOMNodeList $elements
 * @param DOMNodeList $qtdeProducts
 * @return array
 */
private function extractInfoByInputs($elements, $qtdeProducts)
{
    $productInputs = [];
    $arrKeysList = [
        'productName',
        'productId',
        'productPrice',
        'productCategory',
        'productBrand'
    ];

    for ($i = 0; $i < $qtdeProducts->length; $i++) {
        /**
         * @var int $k
         * @var DOMElement $element
         */
        $arrProducts = [];
        $loop = 0;
        foreach ($elements as $k => $element) {
            $class = $element->getAttribute('class');
            if (!in_array($class, $arrKeysList)) {
                unset($elements[$k]);
            } else {

                print_r($element);

                if ($loop >= sizeof($arrKeysList))
                    continue;

                $class = $element->getAttribute('class');
                $value = $element->getAttribute('value');

                $arrProducts[$loop] = [$class => $value];
                $loop++;

                /*foreach ($arrKeysList as $y => $kItem) {
                    if ($class === $kItem) {

                        $arrData[$y] = [$class => $value];
                        $arrProducts[$loop] = $arrData[$y];
                    }
                }*/

                //$productInputs[$i] = $arrProducts;
                //$loop++;
            }
        }

        $productInputs[$i] = $arrProducts;
    }

    print_r($productInputs);

    return $productInputs;
}

The wrong output is below:
Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [productName] => Camisa Polo Masculina Flamê
                )

            [1] => Array
                (
                    [productId] => 03MJRUXE
                )

            [2] => Array
                (
                    [productPrice] => 69.99
                )

            [3] => Array
                (
                    [productCategory] => Polos
                )

            [4] => Array
                (
                    [productBrand] => Business
                )

        )

    [1] => Array
        (
            [0] => Array
                (
                    [productName] => Camisa Polo Masculina Flamê
                )

            [1] => Array
                (
                    [productId] => 03MJRUXE
                )

            [2] => Array
                (
                    [productPrice] => 69.99
                )

            [3] => Array
                (
                    [productCategory] => Polos
                )

            [4] => Array
                (
                    [productBrand] => Business
                )

        )

    [2] => Array
        (
            [0] => Array
                (
                    [productName] => Camisa Polo Masculina Flamê
                )

            [1] => Array
                (
                    [productId] => 03MJRUXE
                )

            [2] => Array
                (
                    [productPrice] => 69.99
                )

            [3] => Array
                (
                    [productCategory] => Polos
                )

            [4] => Array
                (
                    [productBrand] => Business
                )

        )

    [3] => Array
        (
            [0] => Array
                (
                    [productName] => Camisa Polo Masculina Flamê
                )

            [1] => Array
                (
                    [productId] => 03MJRUXE
                )

            [2] => Array
                (
                    [productPrice] => 69.99
                )

            [3] => Array
                (
                    [productCategory] => Polos
                )

            [4] => Array
                (
                    [productBrand] => Business
                )

        )

Update
I updated the PHP code and I set a screenshot also.
Please, someone can help me with that?
Comment: Show more of your html file (in particular show several products with the parent nodes);
Comment: ALSO What would be the right output
Comment: I update the code now. Thank's for your interest to help me.
Answer: I solved this question!
Sometimes it's good to erase everything and start over.

First, I convert DOMNodeList to array of DOMElement with for loop.
Second, I make a foreach loop of list of attribute's names and other foreach loop of elements converted.

The code of solution is below:
/**
 * Extract info of the inputs.
 *
 * @param DOMNodeList $elements
 * @return array
 */
private function extractInfoByInputs($elements)
{
    $arrKeysList = [
        'productName',
        'productId',
        'productPrice',
        'productCategory',
        'productBrand'
    ];

    $arrayElements = [];
    for ($i = 0; $i < $elements->length; $i++) {
        $item = $elements->item($i);
        $class = $item->getAttribute('class');

        if (in_array($class, $arrKeysList))
            $arrayElements[] = $item;
    }

    $arrayAttrs = [];
    foreach ($arrKeysList as $y => $kItem) {
        $loop = 0;
        /**
         * @var int $k
         * @var DOMElement $element
         */
        foreach ($arrayElements as $k => $element) {
            $class = $element->getAttribute('class');
            $value = $element->getAttribute('value');

            if ($class === $kItem) {
                $arrayAttrs[$loop][$y] = [$class => $value];

                $loop++;
            }
        }
    }

    print_r($arrayAttrs);

    return $arrayAttrs;
}

And the output is below:
Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [productName] => Camisa Polo Masculina Flamê
                )

            [1] => Array
                (
                    [productId] => 03MJRUXE
                )

            [2] => Array
                (
                    [productPrice] => 69.99
                )

            [3] => Array
                (
                    [productCategory] => Polos
                )

            [4] => Array
                (
                    [productBrand] => Business
                )

        )

    [1] => Array
        (
            [0] => Array
                (
                    [productName] => Camisa Polo Masculina Listrada
                )

            [1] => Array
                (
                    [productId] => 03XZAMSE
                )

            [2] => Array
                (
                    [productPrice] => 59.99
                )

            [3] => Array
                (
                    [productCategory] => Polos
                )

            [4] => Array
                (
                    [productBrand] => Business
                )

        )

    [2] => Array
        (
            [0] => Array
                (
                    [productName] => Camisa Polo Masculina Tie Dye
                )

            [1] => Array
                (
                    [productId] => 03TBNCME
                )

            [2] => Array
                (
                    [productPrice] => 99.99
                )

            [3] => Array
                (
                    [productCategory] => Polos
                )

            [4] => Array
                (
                    [productBrand] => Business
                )

        )

        etc...

One observation about those keys
There is many keys in out loop.
Actually it's grouped by key, but it's better to group by input name/class and your value.
So, one little modification...

Before:
$arrayAttrs[$loop][$y] = [$class => $value];
And now:
$arrayAttrs[$loop][$class] = $value;

... and that's it! Better output is below:
Array
(
    [0] => Array
        (
            [productName] => Camisa Polo Masculina Flamê
            [productId] => 03MJRUXE
            [productPrice] => 69.99
            [productCategory] => Polos
            [productBrand] => Business
        )

    [1] => Array
        (
            [productName] => Camisa Polo Masculina Listrada
            [productId] => 03XZAMSE
            [productPrice] => 59.99
            [productCategory] => Polos
            [productBrand] => Business
        )

    [2] => Array
        (
            [productName] => Camisa Polo Masculina Tie Dye
            [productId] => 03TBNCME
            [productPrice] => 99.99
            [productCategory] => Polos
            [productBrand] => Business
        )

    [3] => Array
        (
            [productName] => Camisa Masculina Slim
            [productId] => H2EUSE01E
            [productPrice] => 119.99
            [productCategory] => Camisas
            [productBrand] => Business
        )

    [4] => Array
        (
            [productName] => Camiseta Masculina Alongada
            [productId] => 4E6QWBDE
            [productPrice] => 49.99
            [productCategory] => Camisetas
            [productBrand] => Business
        )

    [5] => ...

I hope to help someone else by solving this question.


How to restart App Service Plan

Question: The iPhone app has an option to "restart" a service plan. Can anybody tell me where this is located in the portal? I can't seem to find it.
Answer: You can do this only via API
POST https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/serverfarms/{name}/workers/{workerName}/reboot?api-version=2022-03-01

This will restart the single machine. So if you have two instances you need to run it for each instance separately.
I recommend trying the option Try it from the documentation.
Answer: I think we now have a way to do that (without requiring a direct API call as suggested by @krzysztof-madej in his answer). The current location seems a bit strange to me, but you can choose any app currently running within the plan, then navigate to Monitoring > Health Check > Instances. Then you can click Restart to restart the specific instance of your plan.
Answer: In the Azure portal go to your App Service Plan. In the left menu click Apps under settings. Then click on your app to open the app's settings. There you will have an option to restart the App
Comment: I am not looking for a way to restart an app. I am looking for a way to restart the whole "service plan". (The mobile app has this function, one can archive the same thing [or something similar] if you change the pricing tier.)
Comment: Thank you for the pointer to the feedback site. i posted a comment there. Do you happen to know what the "restart service plan" button in the mobild app does?
Comment: I see, unfortunatly this feature is not available in the portal. Such a feature was [requested in 2017](https://feedback.azure.com/forums/169385-web-apps/suggestions/17826847-restart-app-service-plan-all-web-apps-in-a-plan#:~:text=If%20you%20need%20to%20restart,each%20iteration%20of%20the%20loop.) and declined by the Azure App Service team.
Comment: Not 100% sure what the mobile app does exactly, but I suspect it call the `Restart Web App` function [documented in the REST API](https://docs.microsoft.com/nl-nl/rest/api/appservice/appserviceplans/restartwebapps)

How to restart App Service Plan


linux hardware raid 10 / lvm / virtual machine partition alignment and filesystem optimization

Question: I've been reading everything I can find about partition alignment and filesystem optimization (ext4 and xfs) but still don't know enough to be confident in setting up my current configuration.  My remaining confusion comes from the LVM layer and if I should use raid parameters on the filesystem in guest os'es.
My main questions are:

When I use 'pvcreate --dataalignment' do I use the stripe-width as calculated for a filesystem on RAID (128kB for ext4 in my situation), the Stripe size of the RAID set (256kB), something else altogether, or do I not need this?
When I create ext2/3/4 or xfs filesystems in guests on the Logical Volumes, should I add the settings for the underlying RAID (e.g. mkfs.ext4 -b 4096 -E stride=64,stripe-width=128)?
Does anyone see any glaring errors in my set up below?  I'm running some benchmarks now but haven't done enough to start comparing results.

I have four drives in RAID 10 on a 3ware 9750-4i controller (more details on the settings below) giving me a 6.0TB device at /dev/sda.  Here is my partition table:
Model: LSI 9750-4i DISK (scsi)
Disk /dev/sda: 5722024MiB
Sector size (logical/physical): 512B/512B
Partition Table: gpt

Number  Start      End         Size        File system     Name      Flags
 1      1.00MiB    257MiB      256MiB      ext4            BOOTPART  boot
 2      257MiB     4353MiB     4096MiB     linux-swap(v1)
 3      4353MiB    266497MiB   262144MiB   ext4
 4      266497MiB  4460801MiB  4194304MiB

Partition 1 is to be the /boot partition for my xen host.
Partition 2 is swap.
Partition 3 is to be the root (/) for my xen host.
Partition 4 is to be (the only) physical volume to be used by LVM
(for those who are counting, I left about 1.2TB unallocated for now)

For my Xen guests, I usually create a Logical Volume of the needed size and present it to the guests for them to partition as needed.  I know there are other ways of handling that but this method works best for my situation.
Here's the hardware of interest on my CentOS 6.3 Xen Host:

4x Seagate Barracuda 3TB ST3000DM001 Drives (sector size: 512 logical/4096 physical)

3ware 9750-4i w/BBU  (sector size reported: 512 logical/512 physical)
    All four drives make up a RAID 10 array.
    Stripe: 256kB
    Write Cache enabled
    Read Cache: intelligent
    StoreSave: Balance

Thanks!
Comment: [This answer](http://serverfault.com/a/558930/77281) might help you.
Answer: Specifically in answer to your questions:

Stripe width (256KB)

Yes

There are two things I can think of that aren't mentioned:

3.1) You aren't starting with the top level I/O size, which is where you need to start. If your application is mostly going to write in x KB blocks, then you need top optimise and align the entire storage stack for x KB blocks.
3.2) You haven't touched upon the block group alignment (-g option for ext* file systems). You need to adjust your block group size in a way that avoids all of the block groups starting on the same disk, thus creating a massive hot-spot and making that disk the bottleneck.
I wrote an article on this subject that explains how to achieve optimal storage stack alignment, which you may find useful.


Host two ready websites with different URL using same code base

Question: I'm pretty newbie to drupal and deploying stuffs. I've two separate drupal websites ready.
www.example.com
www.example.org

My directory structures on local machine for both websites are
wamp/www/example.com/sites/'all & default ' folder
wamp/www/example.org/sites/'all & default ' folder

These websites have complete different theme and database from each other. Now I want to go live for these two websites. But the problem is on hosting server they will provide me only 1 drupal installation. I need both URL's working. (There is a setting for URL redirection on hosting).  But on hosting server, redirection via .htaccess is not running. (They said !!!). So my question is how to host two complete different websites on server with two complete different URLs using same drupal code base? I'm using drupal 7. Any help or suggestion will be appreciated.
Thanks in advance…
Comment: You used domain names that belongs to commercial companies. In examples use http://example.com and http://example.org (with subdomains as needed) instead. Please edit your question. I'd prefer not to do that myself to avoid making it less useful for you.
Comment: @Mołot Thanks for pointing that. I've no idea that these are commercial addresses. I've edited my question.
Comment: refere http://www.ostraining.com/blog/drupal/drupal-multi-sites/
Answer: It looks like you are looking for Multisite approach. It's pretty easy to set up and to keep sites separate, but if one day you'll need to share anything between sites, you'll regret not using Domain Access.
If you are sure there will be no need to share data, in <drupal root>/sites create 2 subdirectories, like example.org and example.com, and put site-specific files (modules, themes, libraries and settings.php) into them. Point both domains to your Drupal (your provider should be able to help with that) and Drupal will take care to recognize what site is accessed.
It might be worth to consider Domain Access module.

The Domain Access project is a suite of modules that provide tools for running a group of affiliated sites from one Drupal installation and a single shared database.


How To Capture Flash in Module Window?

Question: Is there a way to capture video playing in a flash player module? From what I see there is no cache or at least the player settings are set to no cache and no store.
Thanks
Answer: Replay Media Catcher is a good program, http://applian.com/download-videos/ to capture flash streams
This is a list of more programs which are similar
http://stream-recorder.com/forum/record-rtmp-flash-video-flv-stream-embedded-t2324.html

How To Capture Flash in Module Window?


How to find expectancy of the sum of several random variables

Question: Suppose that $X_{1}, X_{2}, X_{3}... X_{n}$ are random variables independent from each other, all with an unknown distribution, with a standard deviation of 1 and mean of 0.
Let $Y= [\frac{X_{1}+ X_{2}+ ... +X_{n}}{n}]$
Find $E(Y)$ and $\sigma(Y)$
I tried using linearity of expectation  but got nowhere, what can I do to solve this problem?
Comment: Write down in your own words the statement of linearity of expectation. Can you see how it applies to find $\mathbb E[Y]$?
Answer: Using the linearity of the expectation, we get that
$$\mathbb{E}[Y] = \mathbb{E}\left[\frac{X_1 + X_2 + \ldots + X_n}{n}\right] = \frac{1}{n}\mathbb{E}\left[X_1 + X_2 + \ldots + X_n\right] = \frac{1}{n}\sum_{i=1}^n \mathbb{E}\left[X_i\right]$$
Since all the expectations $\mathbb{E}\left[X_i\right]$ are equal by hypothesis (identically distributed), the previous sum is equal to $n\mathbb{E}\left[X_1\right]$ (I wrote the first random variable $X_1$ but it can be the one you choose, since they are identically distributed). Plugging this result in the previous expression, we get
$$\mathbb{E}[Y] = \frac{n}{n} \mathbb{E}\left[X_1\right] = \mathbb{E}\left[X_1\right]$$
Since the mean of all $X_i$ is $0$, then $\mathbb{E}[Y] = 0$.
Can you proceed with the standard deviation using that
$$\mathbb{V}\text{ar}[aX] = a^2\mathbb{V}\text{ar}[X]$$
$$\mathbb{V}\text{ar}\left[X_1 + X_2 + \ldots + X_n\right] = \sum_{i=1}^n\mathbb{V}\text{ar}[X_i] + \sum_{i\neq j}\mathbb{C}\text{ov}[X_i, X_j] $$
and remembering that the random variables $X_1, X_2, \ldots, X_n$ are independent?
Comment: I think I can, thank you so much! This was a very clear explanation.


How to create a Size field on Commerce product content fields?

Question: I am new to Drupal Commerce and I have set up a store. But the problem is that adding variations for each product is a pain, especially when the product has more than 5 colors and 4 sizes.
What I want to do is to have a size Field in Content type instead of product type's fields so that I add the sizes only once (like choosing the categories or collection).
And then customers can select a radio button or so to be able to add the item to the Shopping Cart.
How can I make it work or is there another solution for it?
Answer: I'd go for another solution/approach, as detailed below ...
Commerce Bulk Product Creation
You may want to use the Commerce Bulk Product Creation module. Excerpt from its project page:

... facilitates the creation of groups of related products in bulk. Product administrators can select a number of options for various fields, and a product will be created for all possible combinations of these values. Out of the box, only list fields are supported for this, but an API exists to enable other types of fields for 'combination creation'.

Attention: this module doesn't have an official release yet (only an RC6), though with over 1.200 reported installs, it seems it is pretty stable / trustworthy.
Commerce Backoffice
Another option is to use the Commerce Backoffice module, e.g. because of the auto creation of product display nodes. It provides the backoffice functionality present in Commerce Kickstart (V2), and contains these sub-modules:

Commerce Backoffice Product (commerce_backoffice_product).
Commerce Backoffice Order (commerce_backoffice_order).
Commerce Backoffice Content (commerce_backoffice_content).

This module (and a few dependencies) provides the rich store owner experience that has made Commerce Kickstart 2 so popular (and prevents that you have to install the entire Commerce Kickstart distribution). And there is a great video introduction about it also.
Note: if you use Commerce Backoffice, you most probably also want to use the Shiny administration theme, also used in Commerce Kickstart (V2).
Comment: Ah great, first one is kinda working but there's one thing more that would make it perfect. when I add a bulk product, is there a way to include all fields related to the product display node to the same creation fields? (because this way I have to create a bulk product and then tap 'edit' and then set other fields as well.
Comment: @AbedNaseri I'm not aware about how you can do that "also" (using the 1st solution). However I'm pretty sure that you should be able to get that part to work via some type of "Views Bulk Operations (VBO)" aferwards (possibly by combining that with a custom VBO action implemented via the [Rules](https://www.drupal.org/project/rules) module). If that makes sense to you, I'd suggest to post some type of followup question (with reference to this question if you want), to also try to answer your additional question in your prior comment (and maybe mark this answer as "accept"?).
Comment: I think I'll just go with the current way, so far is way faster than before. thank you:)


Does the difference in harmonic series between instruments have a significant effect on the consonance of the sound?

Question: We all know that an instrument's timbre is uniquely determined by its harmonic series. Harmonic series are also very effective in describing whether an interval is consonant or not. For example, the perfect fifth (say C to G) is consonant because the harmonic series of C and G have a very large overlap. (Actually, they almost coincides!)
Having those two ideas in mind, here is what I am thinking about: if the relative loudness of the harmonic series of two instruments are different (of course the notes in it are the same), then when they play the same interval, one of them might sound more consonant than the other. By "relative loudness of the harmonic series", I mean something like this (taken from this pdf):

For example, trumpets have a very loud third harmonic (this may be not right; just to illustrate what I mean), so when that third harmonic happens to be a very unpleasant note after combining with the rest of the orchestra, trumpets should not be used. Perhaps we should instead use an oboe or something.
Question: Are there any theories about what I mentioned above? Is it an important thing to consider in Orchestration?
Comment: If you want to research for theories about *orchestration* in respect to your question you might look for *timbre* and *formants* and *orchestration*. (s. my 2. answer!) you'll find e.g. this pdf: https://asa.scitation.org/doi/pdf/10.1121/1.4799391
Answer:
Is it an important thing to consider in Orchestration?

You have in fact stumbled onto the very foundation (and art) of orchestration. Orchestration is about not only knowing how each instrument sounds, but how to blend those sounds together to get the effects / textures you're looking for.
Composers generally don't think about blend in terms of harmonic series, but as Tim alluded to, we think about character. To illustrate my point, I'll give a couple brief examples.
To extend your (the OP's) point, not only does each instrument have a unique base timbre, but that timbre also changes not only throughout the instrument's pitch range but dynamic as well.
Let's, for a moment, think like an orchestrator:
EXAMPLE 1

The clarinet has 3 registers: chalumeau, clarion, and altissimo, each with its own characteristics: the first is dark and velvety, the 2nd is focused and clear, and the 3rd is piercing but smooth. Though I haven't tested it, I'm quite confident that the harmonic spread of these registers would differ.

All of this is wonderful to know, but it's also important to know that clarinets also get buried easily. If we wanted the sound to cut through the ensemble, you could pair the clarinet with oboe, trumpet, or piccolo, for example. If you wanted a softer, fuzzier sound, you would blend the clarinet with flute, especially in the flute's lowest register.
Every instrument has unique characteristics dynamically (in terms of the dynamic range they are able to produce, which in fact does change throughout the instrument's range; such as the oboe at the bottom of its range!), timbrally, and unique characteristics due to the nature of how the instrument makes sound (for example, woodwinds have a more difficult time playing fast, repeated notes, where brass and strings would not).
Composers and orchestrators have go-to combinations that are tried and true and deliver confident results (ever wonder why "movie" music sounds a certain way different than other types of orchestral music?) There are too many to list here, but there are many, many books written on the subject.
Thoughtful question and I hope my answer is helpful.
Comment: One could argue that a brass instrument has _many_ registers.  For a particular valve position, there is a lowest resonant frequency, but my lip tension controls which harmonic is the lowest you hear.  Better players can play more than the six I can do—and one of the ones I can do is lower than what I was taught is the lowest possible.
Comment: @WGroleau of course, I myself also play brass. As I said above "every instrument has unique characteristics" - I simply pointed to clarinet as a single example, but brass instruments have just as many unique characteristics as all of the other instruments.
Comment: Did you intend to add more examples after "EXAMPLE 1?"
Comment: @Bladewood Yeah I thought about it but then quickly realized I'd spend hours and hours typing so I didn't. Then I just didn't think about changing it.
Comment: Also note that the human ear only picks up so many harmonics. So not only the physical vibration of the instrument, but also a human ear's receptability will affect the relative strengths of the harmonics, and thus the timbre. This is one of the effects that makes an instrument sound differently in different registers, particularily the highest instruments, like piccolo flutes, where the highest note only has 3-4 harmonics that we can hear at all.
Comment: @Arthur - yes, obviously hearing has limits. To clarify, human hearing *does not* "affect the relative strengths of harmonics", but rather it is our hearing that affects *our perception* of those relative amplitudes. Further influence also comes from the Fletcher-Munson curve.
Answer: Other answers so far make good points -- matching timbres (and sound spectra) is actually essential to orchestration, and composers have been noticing these patterns (and using them in orchestration) even before analysis of harmonic spectra was possible.
I would add one other related issue to answering the title question about "differences in harmonic series" in general.  First off, there's an entire subgenre of modern art music, commonly called spectral music or spectralism that is based on manipulation of timbre and harmonic spectra.  There are all sorts of well-known effects that can be created with consonance, dissonance, and other musical parameters through manipulation of spectra, as many of these compositions have explored.
For an intro on how this sort of spectral manipulation can work, I might suggest a classic book: William Sethares's Tuning, Timbre, Spectrum, Scale.  (There are more recent books on this topic, but Sethares gives a reasonable intro to many of the issues, including timbral manipulation and its effects on consonance and dissonance.)
Sethares has posted a few musical examples that accompanied his book here.  It's one thing to consider instruments that have stronger or weaker harmonics, but what if we stretched or compressed the sound spectrum of instruments artificially, so that they no longer would produce consonance at the normal intervals?
Take a listen to his examples of this phenomenon:

First, a normal example in standard 12-tone equal temperament
Now, the same tune played with all the overtones "stretched" so they no longer correspond to the harmonic series: standard music intervals now sound dissonant
But what if we stretch the scale underlying the tune too?  We get this, which sounds weird, but at least with something resembling "consonant"-like intervals.
Note that if we fix the timbre back to "normal" (with overtones following the harmonic series), that last example with a stretched scale sounds dissonant and horrible too.

Basically, consonance and dissonance are fundamentally (no pun intended) wrapped up with the structure of overtones in sounds.  One can make a major seventh sound somewhat "consonant" by manipulating the overtones, and one can make an octave sound quite dissonant by changing the overtones as well.
This spectrum manipulation, by the way, is also really important to instrument building and construction.  Strings and long tubes are relatively "one-dimensional" and thus tend to have relatively "harmonic" spectra, i.e., with overtones resembling the harmonic series.  But other types of instruments (bells, drums, etc.) do not have overtones that fall nicely into that harmonic series patterns.  There's a whole ancient lore about church bells that basically involves casting patterns and shaving off metal in various places to try to make the bells sound more "harmonic" rather than dissonant (both with other bells and even "clangy" and unfocused in tone when rung alone).  And if you watch a professional timpanist who is making fine adjustments to "clear" a drum head and tune it, what the timpanist is really doing is manipulating the drumhead to produce a more harmonic sound (again, with overtones corresponding closer to the harmonic series, even though the sound is produced by a two-dimensional vibrating object with different modes of vibration than a string or air column would have), so it will have a clearer tone and will blend better with other instruments.
Answer:
Does the difference in harmonic series between instruments have a significant effect on the consonance of the sound?

Absolutely - and not only between instruments. Different ranges of the same instrument have different harmonic structures - a commonly-given example is the 'muddy' sound at the bottom end of the piano, caused partly by relatively weak lower harmonics.

Are there any theories about what I mentioned above?

One of the most general theories relating to this comes from Plomp & Levelt's work on consonance. The basic idea is that the dissonance of a sound at any time can be worked out from the pitch relationships of all sinusoidal pairs.
I think it's fair to say that once you really dig into the topic of what consonance and dissonance is, you'll get various different notions and ideas of what those words really mean - there isn't a single, specific, well-agreed-upon definition, as far as I am aware.
I'm sure different composers and arrangers have produced useful specific guidelines over the years - hopefully someone else can give some examples. But it may not be possible to make rules as simple as 'don't use this instrument in this situation', for an instrument's harmonic structure also varies over time, and depending on how it is played. In fact it's often down to the player to mould the timbre they produce to suit the composition.
Comment: I expect a lot of composers are at least sub-conciously aware of this, and mix accordingly. It could even be a 'trademark' of some of those composers.
Comment: Even in the Brass band scene it is possible  to identify different composers by their typical instrumentation and the "sound".
Answer: It would since the very nature of consonance vs dissonance is dependent on the interference of harmonics (in theory).  So it stands to reason that if a particular instrument had missing harmonics there would be fewer opportunities for dissonance with when playing intervals on one instrument (string, or piano) and harmony with other players.  However that is not to say that all opportunities for dissonance disappear when harmonics are absent.  The ear creates aural harmonics.  So even in the presence of two "pure tones" a listener will perceive standard consonance/dissonance as explained by standard theory.  Whether or not the strength of each harmonic has a significant effect on the perception of consonance/dissonance is an other issue.  I am not sure if the judgement of this quality is binary or even subjective.  Attempts to relate this to the physics of waves go back to Helmholtz but there are always outliers to this type of phenomenon.
I disagree that "muddiness" is the same issue or related to this issue but it might be.  There is a limit to pitch discrimination in humans and this is frequency dependent.  This is why large intervals are placed in the bass and smaller intervals in the higher register.  Once you reach the limit of pitch discrimination it almost doesn't make sense to say the interval is consonant or dissonant since you will probably hear the sum tone with a difference tone envelope.
Keep in mind that an instrument does NOT have a single spectrum.  The spectrum depends as much on the attack as on the physics of the instrument itself.  So you can adjust the attack to accentuate certain harmonics.  This is very easy to do on the guitar and gives it a characteristic versatility.  Perhaps not at easy for brass or woodwind but I am not sure as I don't play those families of instruments.  While holding a chord for a long time with 3 or 4 trumpets it would be interesting to hear how the harmony changes as the players adjust their embouchure gradually.  If that is easy enough to do.
Lastly, most models of musical instrument spectrum we have follow the harmonic series fn = n*f0.  It could be said that we modify the materials and construction to get close to this series.  But the fact is that not all physics of vibrating system following this series.  The stiff rod or plate with boundary conditions can have dissonant harmonics.  By that I mean the ratio of a harmonic to the fundamental can be an augmented 5th +/- a few cents, or some other note that isn't evne in the just or 12TET scale.  These instruments will sound intrinsically "out" and when played in harmony with other instrument would be quite a bit more dissonant.  Bells are an example, the basic xylophone bars can exhibit this, but they are usually modified with a variable cross section to "tune" them..
Answer:
Does the difference in harmonic series between instruments have a significant effect on the consonance of the sound?

My  personal experience (working with synthesizers (ADSR), Finale, VST and wavelab. There I encounter often the problems you are mentioning in your question.
The sound of different instruments is strong related to the question of timbre and formants.
So you probably know what timbre and formants mean.
If not ... these 2 wiki sites give a lot information about those terms.
https://en.wikipedia.org/wiki/Timbre
https://en.wikipedia.org/wiki/Formant
(while there seems to be great differing in  definition of timbre!)
Timbre has been called "...the psychoacoustician's multidimensional waste-basket category for everything that cannot be labeled pitch or loudness."
This article (wiki Timbre) discusses In music history also the examples I've mentioned in my first answer: Wagner and Debussy!
Instrumental timbre played an increasing role in the practice of orchestration during the eighteenth and nineteenth centuries. Berlioz (Macdonald 1969, 51) and Wagner (Latham) made significant contributions to its development during the nineteenth century. For example, Wagner's "Sleep motif" from Act 3 of his opera Die Walküre, features a descending chromatic scale that passes through a gamut of orchestral timbres. First the woodwind (flute, followed by oboe), then the massed sound of strings with the violins carrying the melody, and finally the brass (French horns).
http://musicweb.ucsd.edu/~trsmyth/timbre175/Musical_Instrument_Formants.html
while the English wiki site is focussing  on human voice and vocals the German wiki site gives a lot more of information (you can translate it to English. If I do it here it would be to broad and it is not the core of your question!)
And in the bibliography of the wiki sites you'll find links to literature about Theories for Orchestration.
http://musicweb.ucsd.edu/~trsmyth/timbre175/Musical_Instrument_Formants.html
(here you find also Pdf's)
e.g. this one
http://newt.phys.unsw.edu.au/jw/formant.html
Now to your question:

Are there any theories about what I mentioned above? Is it an important thing to consider in Orchestration?

I've found this article that I'd like to share the resume:
https://asa.scitation.org/doi/10.1121/1.4806102
Most of the music we enjoy uses the musical qualities of different instruments to create specific perceptual and emotional effects that composers sculpt over time. Timbre is the auditory attribute that distinguishes different instruments. Research on timbre perception has demonstrated that it is multifaceted and contributes in many ways to the perceptual organization of musical structures. The art of structuring music with timbre is orchestration. A survey of orchestration treatises reveals the dearth of underlying theory, in sharp contrast to other traditional areas such as harmony and counterpoint, which have long theoretical traditions. We seek to develop a theoretical ground for orchestration practice starting with the structuring role that timbre can play in music. Many aspects of musical structuring are achieved by auditory scene analysis, the perceptual processes that result in unified events, integrated streams of events, groups of events segmented into phrases and sections, and larger-scale units extended over time that we call orchestral gestures. The roles that timbre plays in the manifestation of these principles in orchestration practice will be considered as potential elements of a theory of orchestration. How such principles might be incorporated into computer-aided orchestration systems and computer-aided orchestral rendering systems will also be examined.
further I've downloaded this book:
https://de.scribd.com/doc/39643485/Walter-Piston-Orchestration
(you can read just the foreword of the book - without downloading it.)
https://ccrma.stanford.edu/~jmccarty/formant.htm
http://www.sengpielaudio.com/FormantenPraegenDieKlangfarbe.pdf
this pdf I've translated by Google for you:
Note: Formants are resonance-like amplified frequency ranges of partial tones in voices and musical instruments, the position of which is preserved, regardless of the fundamental frequency of the sound. They represent acoustic filters with low resonance circuit quality - a not too narrow-band increase (fifth to octave) - which are particularly noticeable with vowels. Partial tones = partials, harmonics - but also overtones.
....
Formant areas of woodwind instruments: *)
Instrument main area secondary area
around
Flute 810 Hz
Oboe 1400 Hz 2960 Hz
English horn 950 Hz 1350 Hz
Clarinet 1180 Hz 2700 Hz
Bassoon 440 Hz 1180 Hz
Contrabassoon 250 Hz 450 Hz
Double reed instruments have particularly distinctive formants.
Formant areas of brass instruments:
Instrument main area secondary area
 around
Horn 340 Hz 750 Hz
Trumpet 1200 Hz 2200 Hz
Trombone 520 Hz 1500 Hz
Bass trombone 370 Hz 720 Hz
Tuba 230 Hz 400 Hz
The formation of the formants in brass instruments is caused by the mouthpiece.
Formant areas of the strings:
Instrument main area secondary area
Violin 400 Hz 1000 Hz
Viola 220/350 Hz 600/1600 Hz
Violoncello 250/400 Hz 600/900 Hz
Double bass 70 to 250 Hz 400 Hz
The sound spectra of the string instruments are very individual due to the large differences in design. The areas of the formants are highlighted by the resonance of the resonance body and the enclosed air volume from the spectrum of the vibrating strings.
Directional tapes according to Jens Blauert (Blauertsche tapes):
Sensation main area secondary area around
present, front 3150 Hz 315 Hz
diffuse, rear 1000 Hz (10,000 Hz)
*) based on: Paul Heinrich Mertens, "Die Schumannschen Klangfarbengesetze und ihre Bedeutung für die Übertragung
von Sprache und Musik", Verlag "Das Musikinstrument" Erwin Bochinsky, Frankfurt/M, 1975. ISBN 3-920-11254-7
Comment: Calling timbre a 'waste-basket' seems a bit silly.... sure, it's a general term for the character of a sound, and as such is indeed multifaceted (as your other quote states).
Answer: It's essential to understand the difference between overtones and harmonics for one who wants to understand orchestration from a physical point of view. The easiest to understand are harmonics, which was originally a mathematical term associated with a harmonic series, in which each term has a whole number ratio to all other terms. Overtones rather are associated with a physical system and the term describes the different ways a vibrating system vibrates.
The piano is a good example. Its sound contains a fundamental and overtones. The overtones are close to, but not harmonic. This is because no real string is infinitely flexible, complications because of string length and tension, and the fact that the piano tone is a transient, not a steady periodic motion. But bear with me, and you will understand where I'm going.
Thus "overtones" can be characteristic of a single tone, with different frequency components making up the tone. Another example of overtones would be to excite a steel piano string with, say a periodic magnetic field. If you did it at the frequency of the fundamental, the string would vibrate at that frequency, and there would be very little other vibratory components – no overtones. Then you could excite it at the first overtone frequency that occurs during the conventional vibration. Again, the string will vibrate at that overtone frequency, with no fundamental and very little other components. You can excite the string at any frequency, but if that frequency doesn't match the fundamental or some overtone, the string will vibrate with little amplitude. This is called resonance. Stay with me.
Any steady, periodic tone must have overtones that are harmonic. If that weren't the case, the vibration would not be periodic. That's because the motion must repeat exactly every time, meaning all overtones must also repeat. It's mathematically impossible for the overtones to repeat as a multiple of the fundamental if they are not some whole number ratio of the fundamental frequency.
We come to the difference between the piano and the violin. The piano tone is not steady or periodic. It's a transient, made by striking the string, and there's no requirement that the vibration repeat exactly for all cycles. It doesn't, because of physics, not mathematics, and in addition the amplitude of all components during one cycle is less than the corresponding amplitude in the previous cycle. With the steady periodical vibration of other instruments, such as the violin, the vibration is "forced" or maintained by the action of the bow. That explains the periodic nature of the sound. Energy is steadily being transferred from the bow to the string.
So we have an example of the same vibrating sound source – a string – behaving in very different ways. With the violin, the tone contains overtones that are harmonics, and with the piano, the overtones are not harmonic. Of course, the violin can be played in transient ways, like other instruments can, using various techniques other than a steady draw with the bow.
To summarize, all musical tones that are steady and periodic have overtones that are harmonic, and all musical tones that are transients have overtones that are not harmonic, although some can be very close to harmonic.
What does this mean for orchestration? Well, first, I point out that some here seem to think that dissonance – non-harmonicity – is always bad. That's not true. The dissonance of a cymbal is a favored sound. The 20th century jazz bands of Stan Kenton and Maynard Ferguson are now forever in orchestral annals of examples of how to use dissonance to blood-boiling acoustic effect. Then we also have the later orchestral composers of the modern age. Also, the transient sounds of bells and chimes contain non-harmonic overtones, and it's an art to tune them for maximum effect.  The "bigness" of the sound of church bells is enabled by non-harmonic partials. Another example is the equal tempered scale, which has enormous advantages, but some people actually prefer it over other "natural" scales because of the inherent dissonance it provides.
It's worth looking with more detail at the "upper partials" of a musical tone in the example of the piano. As I mentioned, because the strings are not perfectly flexible, and because string vibrations in some cases produce tensile fluctuations that begin to be at the level of string tension, the overtones in the transient tone are not harmonic, but "stretched," meaning that the overtones are consistently larger than what the harmonic calculation would predict. And that characteristic makes the piano a beautifully sounding instrument. The stretched overtones mean that individual strings can be more easily discerned from each other and from other instruments, so that chords are vibrant and well identified. Compare that to the steady chords played by an accordion, which are harmonic, due to the steady nature of the sound source. With the accordion, chords are muddled, mushy, because of the exact harmonics. Say you play two notes an octave apart on the accordion. The upper note plays the exact same overtones as the lower note, with the only difference being their fundamentals. It's very difficult to discern the two notes, and when you could, it's usually because one note is out of tune.
I could explain much more about the beautiful piano tone and stretched harmonics, the effect of three strings playing together, and the interaction with the sound board. All of that involves overtones in very complicated ways. But I'd rather make corrections to the OP's comments.
"We all know that an instrument's timbre is uniquely determined by its harmonic series." This is incorrect because not all instruments have overtones that are a harmonic series. Additionally, the questioner may be confused in believing that we can identify the source of a musical tone only by its timbre. We also need to hear the "start transient." There are huge differences in start transients between the piano and violin, the accordion, and the wind instruments. The percussive start of the piano – or guitar – tone help us identify the instrument. In fact, there have been scads of experiments wherein people cannot tell the difference between musical tones from different instruments when the start transient is eliminated. Even with instruments that we know have significantly different overtone/harmonic structure. Many people think the clarinet contains ONLY odd harmonics, though that's not accurate, and when its musical tone is played without a start transient, it's easy to confuse it with the other steady tones.
I'd like to draw closer to what the OP wants to know, but there are too many misconceptions and the questions don't really make sense. The OP seems to believe that a harmonic overtone in one instrument can clash with a harmonic overtone in another instrument. Why so?
"if the relative loudness of the harmonic series of two instruments are different (of course the notes in it are the same), then when they play the same interval, one of them might sound more consonant than the other."
Why would one harmonic frequency be more consonant than another? Or why would the additional volume when a third harmonic of one instrument is added to a harmonic of another?  It's pretty much by definition that any harmonic is consonant with any other harmonic.  I suggest that the OP needs to understand the difference between overtones that are harmonic and overtones that are not.  The simplistic view by the OP is also evident in the steady tone spectrum examples shown.  These are steady periodic tones that are not often found in actual music. In practice, there are many dynamics and transients in the playing of any instrument and thus very few tones conform to the information contained in those Fourier spectrums.
The OP is worried that a predominant third harmonic of the trumpet might clash because, "when that third harmonic happens to be a very unpleasant note after combining with the rest of the orchestra, trumpets should not be used." Is the OP wondering about the clash only when the trumpet player is assigned "a very unpleasant note"? I can't make heads or tails out of what the OP wants to know.
"Question: Are there any theories about what I mentioned above? Is it an important thing to consider in Orchestration?"
I suggest the OP re-write this question, using hopefully a better understanding of the role of overtones and harmonics in music. Roughly speaking, and I'm not an orchestral composer, my guess is that composers attempt no theoretical applications concerning overtones, but rather rely on their experience of the total sound of each instrument and how they blend together in a very dynamic environment. It's bottom line experience and it's very subjective.  It would surprise me greatly if composers consulted graphs of steady-state Fourier series during composition.
Answer: In addition to the good answers you've already got I want to add that Ravels Bolero, Shostakovich's ostinato in his 7th Symphony (1. movement) or Lohengrin by Wagner are great studies of orchestration.

There are also interesting personal styles of composers: you can recognize like  e.g. Schumann leading the flutes parallel (or voicing identically) with the violins, that makes it easy to identify a piece as typical by his.

Are there any theories about what I mentioned above? Is it an important thing to consider in Orchestration?

There are surely theories and books about orchestration but a good method will be to experiment by yourself and learn by listening to orchestra music, analyzing and studying full scores, arranging and experimenting like we know of Debussy who was changing the parts even during the final rehearsal of his après-midi d'un faune.
With your question you are on a right way.
Answer:
Does the difference in harmonic series between instruments have a significant effect on the consonance of the sound?

No, not in the real world. In the real world, judgments about consonance and dissonance are based on culture, experience, and context. The psychoacoustic facts only have an indirect effect in most cases, because they set some parameters within which culture has to work.
Some of the earliest careful empirical work and detailed mathematical modeling on this was done by Kameoka and Kuriyagawa in 1969. They tested audio engineers who were musically untrained, and they tested them in artificial circumstances (designed, e.g., to avoid harmonic distortion) and without any musical context. They did find that consonance and dissonance were judged by these musically naive subjects to be well reproduced by a mathematical model involving clashing harmonics within a certain critical bandwidth of frequency (about 1-10%). For instance, pure sine waves in frequency ratios normally considered dissonant (e.g., a tritone) were judged by these subjects to be consonant.
However, none of this corresponds in any detail to how people actually perceive music if either (a) there is some musical context, or (b) the person is musically trained. For example, an equal-tempered minor third is a frequency ratio of 1.189. So if we have a minor third like A with C, the 5th harmonic of A and the 4th harmonic of C differ by only 5%. This lies right in the middle of the critical bandwidth, and therefore according to this type of model should produce a strong sensation of dissonance. Of course people raised in the modern Western musical tradition consider this interval to be sweet and consonant.
Comment: When using sounds that have very strong third and fifth harmonics (e.g. an organ pipe mixture that features 2 2/3' and 1 3/5' ranks), playing two notes a minor sixth apart can yield a rather unpleasant beat frequency which wouldn't be present when using other sounds a minor sixth apart.
Comment: Yes, and being used to Western music doesn't prevent one from perceiving Western harmony as dissonant when it's played on instruments where this harmony doesn't physically work. The easiest example are bells: play a piano piece on carillion, and you get a pretty unbearable cacophony. Vice versa, many Western people seem to quite like Gamelan music, whose harmony is tailored to the instruments with very different harmonics.


IIS Website not working?

Question: I have recently installed IIS on a Windows Server 2008 R2 Domain Controller.
If I type localhost on Google Chrome I get the welcome page. I created a simple test webpage and saved the file in C:\inetpub\wwwroot folder.
In binding I assigned the only IP address I have (static). Port is 5959. In hostname I am using "www.mysite.com".:
The problem is when I try to run the site from Google Chrome I get the error: "No Internet Connection". I created a new site with no hostname, ip address unassigned. I can access this new site with 192.168.1.1"5959
Comment: I would not run a web server from your domain controller o([|||||||||])::;;::;;::;;::;;::;;> STAB
Answer: Ports are defined with a : not an =
192.168.1.1:5959

Comment: that is a typo in my question. I did specify 192.168.1.1:595, but it still did not work!

IIS Website not working?


Pearson correlation test for non-gaussian data

Question: I want to perform significance test for correlation coefficient. However my data is not normally distributed. In my books I have found tests only for the normally distributed data. Is there such test I could apply to data having any distribution?
Comment: This is often fudged: people report P-value but flag that strictly it applies only to normally distributed data. In practice, a better procedure would be to bootstrap and get a confidence interval. In most research, correlations measure or indicate strength of relationships. If there is doubt about correlations being not zero, then perhaps the sample size is too small. Note that other assumptions, especially  independence of observations, are often dubious but more rarely discussed. Testing the corresponding regression coefficient downplays this problem and is often closer to the science.
Answer: I am assuming that you are interested strictly in finding a p-value to test $H_0: \rho=0$ and yet want to control Type I error rates. Then you may want to check out this article that discusses 12 tests of correlation, including familiar Pearson and Spearman as well as less known tests based on transformation and resampling approaches. The authors examine which tests are robust to various non-normal distributions across a range of sample sizes. Judging from the shape of your data's distribution and sample size, you can pick the best test.
Reference
Anthony J. Bishara, James B. Hittner, Testing the significance of a correlation with nonnormal data: comparison of Pearson, Spearman, transformation, and resampling approaches Psychol Methods, 17(3), 399-417 (2012)
Comment: Thanks for pointing out our work.  For those who don't have access to the journal, a free copy of Bishara & Hittner (2012) can be found [here](http://bisharaa.people.cofc.edu/preprints/BisharaHittner2012.pdf)
Answer: If you're testing that the correlation differs from zero you could do a permutation test (or a randomization test). This is probably the simplest to do.
Alternatively if sample sizes are not small, you could form a bootstrap interval for the correlation and see if it includes whatever value you want to test for a difference from.
If you are prepared to assume a distribution you may be able to derive a test or perhaps simulate the distribution of the correlation under independence.