Diatonic harmonica: draw bends from Hole 1 to Hole 6 - principles

Question: Why the diatonic harmonica have different draw bends available? What is the principle behind this setup?
Like:
Hole 1 draw bend has only 1 semitone down.
Hole 2 draw bend has 2 choices of semitones down.
Hole 3 draw bend has 3 choices of semitones down.
Hole 4 draw bend has only 1 semitone down.
Hole 5 draw bend has none (why?).
Hole 6 draw bend has only 1 semitone down.

Could we draw bend semitones from Hole 7 - 10?

Could we draw bend more semitones further than what is shown here from Hole 1 - 10?

Are all these draw bends achieved by the same principle as this:
Diatonic harmonica: How to play the draw bend with the three semitones down (effectively)?
Answer: The following answer pertains to diatonic harmonicas, a.k.a. blues harmonicas.
All the draw bends are produced by the same (two) principle(s).
To understand why the holes behave differently, it helps to understand how bends work. I quote my own answer to the linked question:

The sound of a harmonica is produced by reeds mounted over reed
slots. When air flows over the reed and pulls it into and through
the slot, it starts to vibrate and a tone sounds. Each hole has two
reeds, one mounted on the outside and one mounted on the inside.
During normal play, the inside reed sounds when you blow, pushing it
into its slot, and the outside reed sounds when you draw, sucking it
into the slot.
A harmonica reed can, however, also be made to sound with air
travelling in reverse, pulling the reed out of the sot instead, which
produces a note about one half step sharper that produced in normal
play.
Additionally, the tone of each reed is somewhat flexible, and can be
changed somewhat away from its natural frequency by the player.

You can see these effects for yourself by removing the cover plates of your harmonica and cover the slot of one of the reeds with a finger!
First cover the blow reed.
With only the draw reed available, you will note that it doesn't matter much which hole you choose, even the top octave behaves the same:
you can still bend the draw note a little bit, but it's hard to produce stable bends that are in tune. This is the same kind of bends that are available on chromatic harmonicas, heavily employed by players like Stevie Wonder and others.
In holes 1 through 6, the draw reed is tuned higher than the blow reed. When you start to draw bend a note, this is the first effect that comes in.
Now, cover the slot of the draw reed.
This might be trickier, but if you try to draw bend you might find a tone roughly one half step sharper than the blow note! By subtly changing the shape of your mouth, you might find that you can move this note around a bit.
When you play a draw bend, both these effects are in play!
If you draw without bending, only the draw reed sounds. As you start to bend, most of the sound still comes from the draw reed, which behaves in the same way as if the blow reed had been covered. As you go further down, the working-in-reverse blow reed comes into action and will eventually dominate the sound.
Because there is a strong resonance about half a step above the blow reed, it's hard ( if not impossible) to bend further. This explains the pattern of which bends are available, and can be summarised as follows:
In every hole, the higher note can be bent down to about one half step above the lower note.
In holes 2 and 3, there's a lot of space for the two effects to interact. This means large bends, but requires more precision.
In holes 1, 4 and 6, the blow and draw reeds are close enough in pitch that they can both sound strongly at the note in between, and these are the easiest bends, both to produce and to control.
In hole 5, if you try to bend you might get the blow reed working in reverse, but since this is already at the pitch of the draw reed you don't get any further.
As a bonus, this theory also explains overblows, also indicated in your table! If you cover one of the blow reeds (you might have to try different ones to find the best set-up hole!) and you try to blow bend, you get what is called an overblow, one half step above the draw note. With practice (and a good harmonica!) you can get this note sounding without covering the blow reed with your finger. When you learn this, the harmonica becomes a completely chromatic instrument, in theory able to play any tune in any key!
Comment: Thanks so much -- I read from https://www.bluesharmonica.com/sites/bluesharmonica.com/files/mri_bending_study_barrett.pdf saying "The amount of bend you  can  achieve  is  dictated  by  the  distance(interval) between  the draw and blow reeds in  the same hole. "
Comment: **"In holes 1 through 6 the draw reeds are higher in pitch than the blow reeds, allowing for draw bending. In holes 7 through 10 the blow reeds are higher in pitch than the draw reeds, allowing for blow bending."**


Array Multidimensional PHP foreach

Question: Gostaria de Saber como fazer uma pesquisa de modelo de um carro usando o foreach, dada a tabela abaixo:
<code> /*
Carro                       modelo                      ano

toyota          "corrola","allion","Ranx","mark"        2008
Mazda           "Atenza","Demio","MPV"                  2000

*/
</code>
Comment: Tem como colocar como essa tabela está estruturada no PHP? O carro é o índice?
Answer: Acredito que assim fica mais fácil de dar manutenção:
<code><?php
$carros["toyota"]["modelos"] = array("corrola","allion","Ranx","mark");
$carros["Mazda"]["modelos"] = array("Atenza","Demio","MPV");

$carros["toyota"]["ano"] = 2008;
$carros["Mazda"]["ano"] = 2008;

foreach($carros as $carro) {
    foreach($carro["modelos"] as $modelo) {
        if($modelo == "Demio"){
            echo "Modelo " . $modelo . " Encontrado";
            break;
        }
    }
}
</code>

Array Multidimensional PHP foreach


Tried to build an algorithm to certain numbers out of list, it skips numbers?

Question: I wrote a script that gives me a list of numbers at one point.
I only need the numbers in between 11 and 88.
This is what I tried, simplified:
m = [13, 2, 3, 23, 1]
for x in range(len(m)-1):
    if m[x] < 11 or m[x] > 88:
        del m[x]
print(m)

The list that gets printed is [13, 3, 23].
If I print the individual list items that go inside the for loop, I get this output:
13
2
23
1
[13, 3, 23]

Why does it skip the 3?
Answer: I think you need:
m = [13, 2, 3, 23, 1]

new_m = []
for i in m:
    if i> 11 and i<88:
        new_m.append(i)

print(new_m)

Refer why it is bad idea to remove element from list while iterating
Answer: You are changing the size of the list at the same time you are iterating through it, that in general is not a good idea. You should instead create a new list with the elements you want.
m = [13, 2, 3, 23, 1]
new = []
for i in m:
    if i > 11 and i < 88:
        new.append(i)
print(new)

And if you think of the case before
when x was 1 you removed 2 thus the new list was [13,3,23,1] so for the next x; x = 2 m[x] was 23 and not 3 as 3 is in index 1 now and that is why 3 was still there.
Answer: Try this:
m = [13, 2, 3, 23, 1]
newList = [x for x in m if not ((x<11) or (x>88))]
print (newList)

Output: [13,23]

Comment: the output incorrect. your output should be [2,3,1] and it is not he want
Answer: One liner to do this using for comprehension
m = [x for x in m if 11 <= x <= 88]

Answer: Because you use same array to in a loop, if you delete the value the array size will change. To avoid that, you can use While Loop to do on that.
Below script
Time O(n) SPace O(1)
m = [13, 2, 3, 23, 1]
i=0
while i < len(m):
  if m[i] < 11 or m[i] > 88:
    del m[i]
  else:
    i+=1
print(m)


PHP regex match Latin words may contains symbols, digits and spaces

Question: There are names of records in which are mixed Cyrillic and Latin words, symbols, spaces, digits, etc.
I need to preg_match (PHP) only Latin part with any symbols in any combinations.
Test set:
БлаблаБла Uty-223
Блабла (бла.)Бла CAROP-C
Бла бла ST.MORITZ
Бла бла RAMIRO2-TED
LA PLYSGNE 1 H - 001

(Блабла) - doesn't matter Cyrillic words.
So i tried pattern:
/[-0-9a-zA-Z.]+/

But [Блабла (бла.)Бла CAROP-C] and [LA PLYSGNE 1 H - 001] not found as string.
Next i tried to write more flexible pattern:
/[-0-9a-zA-Z]+(?:.)?+(?:\s+)?+[-0-9a-zA-Z]+/

But there is still problem with matching [LA PLYSGNE 1 H - 001].
Is there any idea how can this be solved?
Thanks.
Comment: Do you want to match this? `[0-9a-zA-Z]+(?:[.\h-]+[0-9a-zA-Z.]+)*`  https://regex101.com/r/2DP7Pg/1
Comment: Maybe you just want to remove all chars other than ASCII letters at the start of a string? `preg_replace('~^[^A-Za-z]+~u', '', $string)`? See https://regex101.com/r/kRuv0u/1
Comment: @The fourth bird - Yes, perfect!
Answer: If the . and - can not occur at the beginning or end, you can start the match with [0-9a-zA-Z] and optionally repeat one of the chars listed in the character class followed by again [0-9a-zA-Z]
\b[0-9a-zA-Z]+(?:[.\h-]+[0-9a-zA-Z]+)*\b

The \b is a word boundary preventing a partial word match
\h matches a horizontal whitespace character

See a regex101 demo.

Matching at least a single char [0-9a-zA-Z] with allowed chars . and - in the whole string, and asserting whitespace boundaries to the left and right
(?<!\S)[.-]*\b[0-9a-zA-Z](?:[0-9a-zA-Z.\h-]*[0-9a-zA-Z.-])?(?!\S)

Using (?<!\S) and (?!\S) are lookaround assertions that are whitespace boundaries, asserting not a non whitespace char to the left and the right.

See a regex101 demo.
Answer: You can also use a script run starting with a latin letter:
~(*sr:\p{Latin}.*\S)~u

demo
Comment: @Thefourthbird: Basically, a script run succeeds when all the characters in the subpattern have the same *script extension* unicode property (*Latin* here) or are common characters. There's a better explanation here https://www.pcre.org/current/doc/html/pcre2unicode.html#scriptruns , and 2-3 examples in the txt version (that are probably somewhere in the html version).
Comment: @Thefourthbird: take a look also here https://www.unicode.org/reports/tr24/#Script_Extensions
Comment: That is something new to me :-) I can find it here https://www.pcre.org/current/doc/html/pcre2syntax.html#SEC21 What exactly does it do?


Access the Application object inside a Window class in WPF?

Question: Can we access the current System.Windows.Application object inside a Window class in WPF ?
Answer: Yes sure. You can access it everywhere in a WPF application.
<code>// assuming that you derivate of Application is named App
((App)Application.Current).SomePropertyOfApp = ...
</code>
Answer: Yes - it's as easy as Application.Current.


Loading tree hierarchy asynchronously

Question: I'm developing an API that has a tree hierarchy. I thinking of supporting asynchronous load of all the nodes in the tree, and I'm not sure if it's a good idea. I'm planning on using reactive extensions for this.
Each node has a Load method which won't complete until all its child-nodes has been loaded (things are loaded depth first). So for a simple structure:
<code>1
|-- 1.1
| |- 1.1.1
| |- 1.1.2
|-- 1.2
  |- 1.2.1
  |- 1.2.2
</code>
Node 1 loads 1.1 and 1.2 asynchronously and waits for them to complete, which in turn loads 1.1.1, 1.1.2, 1.2.1, 1.2.2... so that is 6 asynchronous load operations. The tree can have potentially 10 000 nodes... that's a lot of asynchronous load operations - Question 1 - will this create problems?
I want to implement this in a way where I can spread the load across a certain time-span, so the user can tweak load time to avoid the application freezing if a lot of nodes needs to be loaded at once. Question 2 - How would I go about doing this in reactive extensions? What components do I need to look into, custom observables, subjects? Not sure where to start.
Comment: On Question 1.  No, it shouldn't, if you do it properly - using Tasks. :-)
Answer: My initial thoughts are to use Observable.Join patterns ... consider my answer here (and the link provided to an example, here:  https://stackoverflow.com/a/3868608/13131) https://stackoverflow.com/a/16462959/13131.
HTH

Loading tree hierarchy asynchronously


Showing the JSF Error Messages

Question: I am using JSF Myfaces Impl 1.2 without tomahawk and other libs :
I am using different styles + images to show JSF Error messages, find below a sample.
<h:panelGroup rendered="${adminBean.showErrorIcon==2}">

            <h:messages layout="table"
                errorClass="InfoMsg" />

Based on the int variable of the Backing Bean , I am displaying a diff image and the corresponding FacesMessage(s) in the screen - only 2 cases - error or an information.
I am using the below code to set the variable of the Backing Bean
//Checking if there are messages!
    log.debug("Checking if there are messages to be shown ]");
    if(getShowErrorIcon()==99){//Set only if the value is still the default :
        log.debug("getShowErrorIcon was DEFAULT - Changing it ]");
        Iterator<FacesMessage> messages = FacesContext.getCurrentInstance().getMessages();
        if(messages != null && getShowErrorIcon()==99){//Set Error/Info for messages that are not added here :
            while(messages.hasNext()){
                log.debug("There are ***messages***");
                FacesMessage aMessage =(FacesMessage) messages.next();
                if(aMessage.getSeverity().compareTo(FacesMessage.SEVERITY_ERROR)==0){
                    setShowErrorIcon(1);
                    break;//just once is enough
                }
                if(aMessage.getSeverity().compareTo(FacesMessage.SEVERITY_INFO)==0){
                    setShowErrorIcon(2);
                    break;
                }
            }
        }
    }//if it is not default, then something has been set already, why again?

Now the problem I have is , There are FacesMessage(s) that are added by the MyFacesImpl - like the required=true  and the custom validator messages which are added during PROCESS_VALIDATION Phase, These are not shown in the screen since my integer variable of the Backing Bean is not set , and since the INVOKE_APPLICATION Phase was not called (and that means the above code was not called!!!)
How do I resolve this? Or Whats the best way / Where's the best place to place the above checking code ?
Appreciate your help.Thanks!
Answer: I'm not sure, but this all look like unnecessarily overcomplicated. To change icons/styles based on the message severity, just make use of the CSS powers. You can specify different CSS classes based on message severity using infoClass and errorClass attributes of the <h:messages> and you can specify the icons as CSS background image.
JSF:
<h:messages id="messages" layout="table" infoClass="info" errorClass="error" />

CSS:
#messages .info td {
    background: url('info.gif') no-repeat left center;
    padding-left: 15px;
}
#messages .error td {
    background: url('error.gif') no-repeat left center;
    padding-left: 15px;
}

The <h:messages layout="table"> itself already renders a HTML
. I think the whole table around it is unnecessary as well. Just apply styles accordingly the usual CSS way.
#messages {
    width: 375px;
    margin: 0 auto;
    border: 1px black solid;
    border-collapse: collapse;
}

See also:

W3schools CSS tutorial/reference
CSStutorial.net CSS tutorial

Update: as per the comments, you're looking for something like this:
<h:messages layout="table" styleClass="messages info" infoClass="info" errorClass="error" />
<h:messages layout="table" styleClass="messages error" infoClass="info" errorClass="error" />

with CSS:
.messages {
    width: 375px;
    margin: 0 auto;
    border-collapse: collapse;
    border: 1px black solid;
}
.messages.info {
    background: url('info.gif') no-repeat left center;
}
.messages.error {
    background: url('error.gif') no-repeat left center;
}
.messages.info tr.error, .messages.error tr.info {
    display: none;
}
.messages td {
    padding-left: 15px;
}

This shows two separate message tables, one for info and other for error messages, each with a single icon on the left center.
Comment: You answer a lot of JSF's questions :P
Comment: Thanks BalusC. But Every FacesMessage is added in a single Row inside a new  and so the icons are shown as many messages are there. Is it even possible to control the table that JSF renders in css ? - like to put a single TD inside the table (for the image) and provide a corresponding colspan based on the number of messages? Are there any alternate thoughts?
Comment: Ah yes, I now understand the functional requirement. That's doable with just CSS as well. I'll edit the CSS accordingly.
Comment: Thanks BalusC. I will try that sometime later. I did a trick, I added the above code in the Original question in the getter of ShowErrorIcon and returned 1 or 2 based on the messages in the Context. This worked like a Charm. I had to find a spot the code wherein will definitely execute before the screen is rendered.I'll update if I face any problems. Btw , Do you see any problem here? doing this way?
Comment: Well, controlling the layout in the bean and duplicating the view code is a bit clumsy. I'd prefer CSS for that. You can for instance instead use `` and stick to one table. [DRY!](http://en.wikipedia.org/wiki/Don%27t_repeat_yourself)
Comment: Accepting this answer because what I was doing is not a best-practice or is a true JSF way.
Comment: It's possible to show an href inside the FacesMessage?

Showing the JSF Error Messages


bound set of reals

Question: Is $S$ is a bounded, non-empty set ($S \subset \mathbb{R}^n$), then I know it has the least upper bound property. Let $x = \sup S$.
Is $x \in S$? If no, counterexample please. Thank you.
Comment: You probably mean $S\subseteq\mathbb R$ equipped with common partial order $\leq$. If not then you should give the involved partial order.
Answer: No.
Observe that $1=\sup[0,1)$ while $1\notin[0,1)$.
Answer: On real line you can consider the open interval $(0,1)$ where the supremum is $1$ which does not belong to $(0,1)$
For higher dimensions you may define the supernum componentwise in which case the counter example is $(0,1)^n$ That is the Cartesian product of the unit interval in $R^n$

bound set of reals


How doI reduce an array to a specific amount in javascript/jquery/undescore?

Question: I have an array like:
["a", "b", "c", "d", "e"]

Now I want to just have the first 3 items. How would I remove the last two dynamically so that I could also have a 20 letter array, but reduce that down to the first 3 as well.
Comment: Please refer to similar question http://stackoverflow.com/questions/3954438/remove-item-from-array-by-value
Comment: What if you construct another array with the first three elements and than exclude that original array, if you don't need it anymore?
Answer: var a = ["a", "b", "c", "d", "e"];
a.slice(0, 3); // ["a", "b", "c"]

var b = ["a", "b", "c", "d", "e", "f", "g", "h", "i"];
b.slice(0, 3); // ["a", "b", "c"]

Answer: How about Array.slice?
var firstThree = myArray.slice(0, 3);

Answer: The splice function seems to be what you're after. You could do something like:
myArray.splice(3);

This will remove all items after the third one.
Answer: To extract the first three values, use slice:
var my_arr = ["a", "b", "c", "d", "e"];
var new_arr = my_arr.slice(0, 3); // ["a", "b", "c"]

To remove the last values, use splice:
var removed = my_arr.splice(3, my_arr.length-3); // second parameter not required
// my_arr == ["a", "b", "c"]

Answer: In underscore.js we can use the first function
_.first(array, [n]) Alias: head
Returns the first element of an array. Passing n will return the first n elements of the array.
_.first(["a", "b", "c", "d", "e"],3);
=> ["a", "b", "c"]


How to plot Spectrogram using STFT in python?

Question: I calculated STFT of uint8 I/Q data and stored it in a numpy matrix where each row stores STFT of one window as shown in sudo code below.
#k= length of window
#fs= Sampling frequency
#n= Number of STFT calculated
#matrix= Initially empty numpy array

for i in range(0,n):
  t=data[start:end,:]   #start & end calculated with each iteration
  t=t.flatten()
  t=t-127.5
  array = np.empty(t.shape[0]//2, dtype=np.complex128)
  array.real = t[::2]
  array.imag = t[1::2]

  transform=(np.fft.fft(temp_array))
  line = 2*abs(transform)/k

  #Inserting row into numpy array
  if(i==0):
     matrix = np.hstack((matrix, line))
  else:
     matrix = np.vstack((matrix, line))

Now how can I plot frequency vs time Spectrogram ?
Comment: have you looked into matplotlib?
Comment: Yes I did both into matplotlib as well as scipy but both were not working fine with complex numpy array
Comment: Why complex arrays? Taking the absolute value of the FFT should result in real values that can be easily plotted with matplotlib's [`imshow`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.imshow). Just take care *not* to initialize `matrix` with complex data type.
Comment: @kazemakase You mean using imshow with extent after taking absolute i.e ax.imshow(np.absolute(matrix),extent=[0,100,0,1]) ? I am assuming frequency will be on Y-axis.
Comment: @JayKrishna yes, that should work as expected. Stil... it looks like you only put absolute values into `line` and thus in `matrix` anyway so it is surprising that you have complex values in `matrix`.
Comment: See the example at the bottom of https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.spectrogram.html
Comment: Possible duplicate of [How to convert a .wav file to a spectrogram in python3](https://stackoverflow.com/questions/44787437/how-to-convert-a-wav-file-to-a-spectrogram-in-python3)
Answer: what you can do is use this
first method:
import scipy.io.wavfile as wav
import scipy.signal as signal
from matplotlib import pyplot as plt

sample_rate, samples = wav.read(filename)
f, t, Zxx = signal.stft(samples, fs=sample_rate)
plt.pcolormesh(t, f, np.abs(Zxx), cmap=cmap)

or the second method:
plt.specgram(samples, cmap=cmap, Fs=sample_rate)

I found the second one have a better visualization effect.
Not sure how to make the first one look as good as the second one though.
Comment: (second) cmap must be eplaced with the name of a colormap. In the Gallery on matplotlib.org is a drawing with all available colormaps, their names. and how to use them.
Comment: cmap is undefined.
Comment: Oops. Gallery is not on the front page anymore. It's under examples now. Check this: https://matplotlib.org/gallery/color/colormap_reference.html#sphx-glr-gallery-color-colormap-reference-py
Comment: To achieve on the first the looks of second just do np.log() of np.abs(Zxx)
Answer: import os
import librosa
import librosa.display
import IPython.display as ipd
import numpy as np
import matplotlib.pyplot as plt

filename = '<yourfile name/ location>'
x, sr = librosa.load(filename)

import librosa.display                   #explicitly import librosa.display
X = librosa.stft(x)                      #perform short-term fourier transfrom
Xdb = librosa.amplitude_to_db(abs(X))    #convert an amplitude spectrogram to dB-scaled spectrogram.
plt.figure(figsize=(15, 5))              #initialize the fig size
librosa.display.specshow(Xdb, sr=sr, x_axis='time', y_axis='hz')
plt.colorbar()```


Vote from list of existing nodes

Question: I have a Content Type "Picture". The contentmanager now wants to choose specific nodes of this ContentType and put them in a voteable list. The voting list should be auto generated if possible.
Users can vote one this list. A user can only vote once and give exactly one vote. After voting, the user should see the ranking results and within his profile he should be able to see for what he voted.
Whats the best way to achieve this?
I thought about using flags, but I would need to restrict a flag to a number of nodes and not per node. And with standard polling I don't see a way of generating the voting list.
Answer: You need to distinct those specific nodes using taxonomy or a custom field, like a boolean field, say, 0 means no vote and 1 means needs voting. Then use the the flag module to filter those nodes. like this

UPDATE :
The basic idea is, when user flags a content, you can set all of the 1s to 0 in this way no more content will be votable. To do so you need to use hook_flag_flag function. in this function use node_load to load the nodes of boolean value 1, set it to 0 then use node_save to save the node.
Comment: I like the idea of setting a boolean field to distinct the votable noded but I don't quite understand the rest - it seems like I can still flag/vote any of those distinct nodes right? What I want is that I can only vote on one of those distinct nodes.
Comment: From what I understood there is a content type, and it has many nodes and you need to make some of these nodes votable, right? so first add a boolean field and set the default to `0` and for votable nodes set it to `1`. To flag only the nodes with boolean value of `1`, on filter criteria, click on the `add` button, and then search for the name of that boolean field. add this field and set its value to `1`.
Comment: Ah let me explain a little bit better: yes, I need to make some of those nodes votable so the boolean field works fine. But now, from this list of nodes, the user should only vote on one. So those nodes can be ranked, like: "chose your best picture -> list of node pictures -> user sets his one vote". Can I do this with flags? Because from my understanding you can flag each votable node and not only one of them.
Comment: I updated the answer
Comment: thanks I'm trying it this way. One thing, isn't now the node only votable once for all users? And not once per user?
Comment: Yes in this way the node is votable only once, to handle this case you can use 2 fields, one for permanent unvoting (say, contents that are not image)  and one for temporary unvoting.

Vote from list of existing nodes


Application of Weierstrass' theorem

Question:
Consider $f \in C^1[0,1]$ where $C^1[0,1]$ is the space of functions of class $C^1$ on $[0,1]$ furnished with the norm $\|f\| = \|f \|_\infty + \| f' \|_\infty$. Prove that for $\epsilon > 0$, there is a polynomial $p(x)$ such that $\|f - p\|< \epsilon.$

So I thought that since $f'$ is continuous there is a polynomial $q(x)$ such that $\| f' - q \|_\infty < \frac{\epsilon}{2}$ by Weierstrass's theorem.
Now by fundamental theorem of calculus, $$f(x) = f(a) + \int_{a}^{x} f'(t) dt$$
$$f(x) - \int_{a}^{x} q(t) dt= f(a) + \int_{a}^{x} f'(t) - q(t) dt \leq f(a) + \frac{\epsilon}{2}(x - a).$$
I know that $p(x) = \int_{a}^{x} q(t) dt$ by my own intuition, but how do I rigorous prove this (because the degree of $q$ will be one higher after integration)?  Also how do I get rid of the $\frac{\epsilon}{2}x$ and $f(a)$ factor?
Answer: Let $q$ be a polynomial such that $\|f'-q\|_{\infty} \leq \varepsilon/2$ and set
$$p(x) := f(0) + \int_0^x q(y) \, dy.$$
Obviously, $p$ is a polynomial and $p' =q$. Moreover, by the fundamental theorem of calculus
$$\begin{align*} |f(x)-p(x)| &= \left| \left(f(0)+ \int_0^x f'(y) \, dy \right)- \left( f(0)+ \int_0^x q(y) \, dy  \right) \right| \\ &= \left| \int_0^x (f'(y)-q(y)) \, dy \right| \\ &\leq \int_0^x |f'(y)-q(y)| \, dy \leq \frac{\varepsilon}{2} \cdot x \leq \frac{\varepsilon}{2} \end{align*}$$
for all $x \in [0,1]$.
Comment: Why are you allowed to set $p(x) := f(0) + \int_{0}^{x}q(y) dy$? That's what I am mainly confused with.
Comment: @Hawk Well, the integral $\int_0^x q(y) \, dy$ is well-defined (it is an integral over a polynomial) - so why should it be *not* allowed to define $p$ this way?

Application of Weierstrass' theorem


How do I override the OS X hostname that is assigned by DHCP?

Question: I want to force OS X 10.6 to use the hostname that I assign it but still be able to use DHCP.
The old method of editinng /etc/hostconfig is not good anymore, the file containing "This file is going ways" message at the top.
How to do this?
Comment: LOL, I suppose you are working in a micro-environment :)
Comment: Why is DHCP issuing a hostname?  If no good reason, switch it off at DHCP level.
Comment: See also http://superuser.com/q/49891/57219
Answer: I ran into this problem too, at my wife's school, where they have a DHCP server. She's running 10.6.6 Snow Leopard. Everytime I'd open Terminal on this network, the hostname would be set to something else.
I found a solution posted by user "Wolf" on SuperUser.
If for some reason, the post is gone, here's what Wolf mentioned, that worked for me:

Set it in the Terminal with
sudo scutil --set HostName <putinyourhostname_or_fqdn_here>
  like in: sudo scutil --set HostName server1.mynetwork.com

Worked like a charm. I'm hoping when my wife takes her laptop home and returns on Monday I won't have to re-run this command. :)
Answer: Not sure if it still works on Snow Leopard, but this used to work on Tiger at least:
In /etc/hostconfig:
#HOSTNAME=-AUTOMATIC-
HOSTNAME=your.host.name

(See http://www.geektimes.com/macintosh/os/x/10_0/core/hostname.html )
Comment: This answer is no longer valid for current OS X versions. See the answer here http://superuser.com/a/50104/57219 which works at least up to 10.8.3


Default.aspx vs. Index.aspx

Question: I've been using Index.aspx as the 'home' file of my web applications directories for the past 5 years, but have only just recently started using Visual Studio for debugging sites.
The built in web server for Visual Studio has Default.aspx as the 'home' file.
When I click on a link such as /News?id=5, its not picking up on the Index.aspx file, and instead showing a directory listing.
This causes an issue because I'm sometimes passing querystring, which is then lost when going to the directory listing.
Therefore, should I cave in and do what Microsoft tells me, and use Default.aspx?
Is this what all other ASP.NET web developers do?
Comment: As much as it's always pained me, here we've always used Default.aspx purely because it's the microsoft 'way'
Comment: Cheers @Jroc, I hate how Microsoft throw their weight about with stuff like this!
Answer: I think you can set this up in the web.config file.
[CORRECTION]: What I was thinking of is actually the  section, which allows to setup 404 pages. You may use that to redirect to Index, but it might not be "good practice".
Hah, amazingly enough, somebody already asked almost the same question, and even another closely related one, that you probably may use to solve your issue.
You can also write an XML SiteMap file to setup Index.aspx as your toplevel page.
As per convention, as stated in my comment, ASPX.NET convention is to name the pages by the name of their controller's action method, such as Index.aspx, however all examples in the MS70-515 book are based on Default.aspx. My personal opinion therefore would be to use Default.aspx.
Comment: Ha that was me. I didn't find a way of changing it in the end. Changing in the web.config wouldn't work as the web.config isn't read when something like `/News` is requested. The system doesn't recognise this anymore as an ASP.NET file as it does a Jpeg.
Comment: Hmmm, I'm having a look into the MS70-515 book I happen to have on my desktop and tell you if I find stuff :D
Comment: ASPX.Net convention for naming views is to use "the action method in the controller, such as Index.aspx". Could that help somehow? That question actually tickles my brain ;)
Comment: Hmmm not really to be honest! :/
Comment: CustomErrors wouldn't be read, and I don't think this would be classed as a 404 error. To be honest I'm more interested in knowing what is the standard convention, and whether I should just start adopting `Default.aspx` in my future applications
Comment: @Curt let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/2608/discussion-between-kheldar-and-curt)

Default.aspx vs. Index.aspx


Andante assai usual interpretation

Question: Not being Italian myself, or fluent in the language generally, I usually think of "Andante" as meaning "walking," and "assai" as meaning "very."
Fine, but what the heck am I supposed to make of "Andante assai"?  'Very walking' seems pretty nonsensical, or at least ambiguous.  How would most musicians interpret it?  Slightly slower than Andante, or slightly faster than Andante, or something else?
All answers welcome, but if somebody fluent in Italian would care to answer that would be extra marvelous.
Comment: It maybe of interest that Prokofiev named the 2nd movement of his Violin Concerto No. 2 *andante assai*.  See sample performance [here](https://www.youtube.com/watch?v=4T_rBV_CKPU).
Answer: Musical terminology isn't "Italian" - it's mostly conventional words and phrases that just look like they might be Italian.
In Italian, "andante" actually means "cheap" or "second-rate" - nothing to do with "walking" at all.
And "assai" doesn't always mean "much" or "a lot" - it can mean the opposite. A phrase like "m'importa assai" means "what do I care?" or "I don't give a **** about that".
Musical instructions written by a real Italian speaker can be just as confusing - like Handel's "largo e allegro" (not alternately - simultaneously!)
Not to mention classics like "Non si deve usare qui il maledetto legato d'organista da chiesa anglicana" ...
"Andante assai" can mean either slower or faster than "Andante" - but since we don't have a precise definition for the tempo of "Andante" anyway, you just have to make up your own mind, or blindly follow whatever MM mark that an editor added to the score.
One theory is that "andante" is an incorrect form of some part of the verb "andare" - but "andare" simply means "to go" with almost the same range of literal and metaphorical meanings as in English - you can certainly "andare a piedi" (i.e. "walk") but food can "andare a male" (go bad) or something can "andare perduto" (go missing).
Comment: perhaps the language has changed somewhat in 400 years? I think that many of the Italian terms we use in music are completely different than what the modern slang uses them as.  Much like reading Shakespeare I expect...
Comment: I never have heard before that musical terms for tempo etc,. are not actually Italian, but just appear to be.  I've been taught that because the most successful composers in the early 1700s were Italian that that is why that language became dominant for musical directions.  If that isn't true, then where did they come from!?!  Or am I misunderstanding you?
Comment: @L3B most of them are real Italian *words*, but they don't have the same meanings. In ordinary Italian, "tempo" doesn't mean "speed", it just means "time" (as shown on clocks and calendars) or "duration" (i.e. a time interval). "Tempo primo" means the "first part" of something (like a soccer match), not "revert to the speed at the start" as in music. If you look at https://www.collinsdictionary.com/dictionary/italian-english/ you will find a separate definition for the *musical* meanings - and it gives the English translation of "Andante (music)" simply as "Andante"!
Comment: "Most successful *composers*" might have been disputed at the time in England, France, Holland, Germany, and Spain (all of which had some pretty good composers, writing very different music from the Italians) but it's certainly true that Italy exported a lot of *musicians* to the rest of Europe, and just as "fractured English" is now the world language for business and science, "fractured Italian" became the European-wide language for music, and continued to have a life of its own afterwards.
Comment: alephzero, your last comment has really opened my eyes.  Thanks so much.  I will never again tell students that Andante means 'walking'!
Answer: The basic tempo markings generally have a range of beats per minute. Andante sits between 76 - 108 on my metronome.
There are some additional qualifiers that may be added to the tempo marking to clarify which side of the tempo range the composer wishes. It is all somewhat subjective however on how much it means.
Adding Assai to the tempo, or "very much" would be play at the faster end of the Andante spectrum.  Adding Non Troppo or "not too much" would be at the slower end.
Comment: and here's a link to a funny about it:  http://www.tonedeafcomics.com/comic/brief-history-of-tempo-markings/
Comment: have you seen music references that support your third paragraph above, or is this rather something you know from training and experience?  Just curious, though your answer is valuable either way.
Comment: I had almost the very same question myself, about what some of the tempo markings actually mean.  In collage my instructors mostly said it was about "feel".  I have studied it since the question comes up when I teach. Historically the tempos were pretty much learning what each marking feels like, sometimes based on how other works were performed. There is more modern agreement about the marking's actual BPM, thus the metronome markings.  The additional modifiers are still interpretative though, such as when you get into moods like "Misterioso".  The wiki on "tempo" has a pretty full list.
Comment: This is the second time I've seen a comment on this site about a metronome marking for Andante which looks crazy, at least for classical music. Around 60 is often more sensible than 78-108 (which is more like Allegretto).
Comment: 76- 108 seems to be a standard definition of Andante.  I just looked an an old metronome I have from the 1960's and it lists it as that also. That being said,  I tend to use the arrangement's tempo suggestions as a rough guideline, and play at what the piece and my performance seem to want.  Considering that there wasn't a standard BPM set when many of these pieces were written one can assume that what Andante et. al. meant varied among regions and composers.
Answer: Most of the terminology used to denote tempo markings in classical music is indeed Italian, and came into use in the late 17th century. Originally, the majority of these tempo markings did not denote the speed at which music should be performed, but rather the character. 'Allegro' originally signified 'cheerful', as it still does in common, non-musical Italian usage. 'Vivace' meant 'lively', 'Presto' meant quickly, 'Grave' meant 'seriously', 'Andante' meant 'moving' (literally 'going') etc. By the mid-18th century, these terms had become associated with specific speeds which could be equated with pulse rates (See Quantz's famous treatise 'On Playing the Flute' (1752]).
As for 'assai', it is generally translated as 'very', but can also mean 'rather' or 'quite' depending on the context. 'Andante assai' therefore can be interpreted as being a very brisk walking pace, or a rather brisk walking pace.

Andante assai usual interpretation


Do we find music arranged according to Western Music Theory pleasing because of "biological instinct" or because of what we learn?

Question: I know that if I play an out of tune guitar, that it sounds unpleasant.  I know that if I play an arrangement on the piano (even one I am making up as I go) and accidentally play a note that does not belong in the key I am playing in, it sounds "bad" to me (and anyone within earshot)!
In Western Music Theory there are 12 notes. In some non Western cultures, each of these 12 notes may be divided in two - thus making 24 notes.  If I heard a composition in which some of these quarter tones of non-western music were used, it would sound "out of tune" and probably make me want to put my fingers in my ears.
We know that certain notes put together in a certain pattern according to certain accepted theories, sounds to us like "music" - whereas, similar patterns (played on the same instrument) that fail to conform to those tuning and arrangement "standards" - sound harsh and unpleasant? Have there been any studies, or research, or anecdotal observations that seek to determine or explain, why this is so?
Is because from the time we are born (or perhaps even in the womb) we hear music arranged based on commonly accepted "standards" - so we get used to hearing it that way and that becomes the way it's "supposed to sound"?  Or is there some biological predisposition in the human species to prefer certain patterns and sound frequencies arranged in certain ways?
Comment: I'm not an expert, but the general view I've picked up is that musical tastes are a little of both. Musical sounds have certain physical properties that other sounds don't that gives rise to some notes sounding empirically, quantifiably consonant or dissonant. In addition, different listeners from different cultures and backgrounds have acquired tastes for different musical constructs.
Comment: The alternative is specious. A huge part of what we transmit to our children culturally is *also* biologically constrained (but not determined). There are many different scales that peoples consider "natural", but only a tiny fraction of those that would be mathematically possible actually occur. Most of them would be hard-pressed to be accepted by *any* culture.
Comment: I really don't have the hit points available to take this question on, but let me just say that there are arbitrary conventions for creating musical sounds which we have been conditioned to expect, and there are also standards for creating musical sound which appear to be related to or derived from the order of the physical world and which human beings seem to universally prefer.
Comment: @Kilianfoth You have some interesting conjecture here; it would be interesting to see some examples.
Comment: The simplest chords use the lower values in the overtone series; I suspect that's part of the reason simple harmonies stick with those notes.  Quarter-tones represent much higher harmonics, which may be part of the reason they're hard for people to accept.  But then again, look at linguistics:  Inuit and some older African languages use a variety of click sounds that are indistinguishable to someone who didn't learn the language as a child. (Heck, as an American, I can't even tell 'dessus' from 'dessous' :-( )
Comment: @Kevin  so you are saying that some of our taste are acquired and some are inborn?
Comment: @Grey - what do you mean by "there are arbitrary conventions for creating musical sounds which we have been conditioned to expect" ???
Comment: @KilianFoth  I am not familiar with the word "specious".  Could you explain what you mean by that please?
Comment: @RockinCowboy "wrongly convincing". Asking whether something is "due to instinct" or "due to learning" implies that either one or the other is the case, but in fact almost certainly *both* mechanisms are operating. People are quite bad at understanding mixed-causality situations, which is why there are so many "false dichotomies". Arguments based on these are usually specious :)
Answer: Basically music is very similar to languages. There is a reasoning behind its structure but you can't understand (or get into) it without getting familiar with the grammar, expressions, phrasing, cultural references, mimics...etc. You can know them natively by growing in a culture or get to know them later.
In its infrastructure, there are sure some physical reasons in western music and human recognition but there are also some reasons behind non-western music. So it is not really a distinctive character. You can take a look at the overtones and their relationship with western harmony for a starting point. You will see that western music quantizes the overtone structure down to well tempered system and construct a vertical harmony structure, while some other cultures use the overtone structure as it is and construct music horizontally in time monophonically.
A side note about this is when western little children singing songs are analyzed, their use of scale is very close to the overtone scale. That means later, overtone scale is culturally overwritten by the quantized well tempered scale, which is a very good example of perception of music also depends on culture.
And like any other taste, personal differences are also very effective. Some people are more open, capable, or gifted... to alien things and some may not.
Comment: So based on your side note - I would conclude that the overtone scale is more "natural" whereas the "quantized well tempered scale" is more "cultural".  I am not familiar with the overtone scale.  Can you tell me where to learn more about this?  Thanks.


Using Saved Video from Camera Roll with AVRURLAsset - initWithURL - iPhone

Question: I have the following code which saves a UIImage or video which has been selected from the camera roll.
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];

[self dismissModalViewControllerAnimated:YES];

if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
    introImage = [info objectForKey:UIImagePickerControllerOriginalImage];

    //Unhide our UIImage Preview and insert our chosen Video or Intro.
    selectIntroButton.hidden = YES;
    selectedIntro.hidden = NO;
    cancelIntroChoiceButton.hidden = NO;
    selectedIntro.image = introImage;
}
else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie])
{

    //Create variable for video.

    AVURLAsset *asset=[[AVURLAsset alloc] initWithURL:??? options:nil];
    AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    generator.appliesPreferredTrackTransform=TRUE;
    [asset release];
    CMTime thumbTime = CMTimeMakeWithSeconds(0,30);

My question is how do I feed the selected video into AVURLAssset initWithURL ? What type of object is [info objectForKey:UIImagePickerControllerOriginalImage] returning ?
Thank you.
Answer: You can get at the asset's URL with the UIImagePickerControllerReferenceURL key.
[[AVURLAsset alloc] initWithURL:[info objectForKey:UIImagePickerControllerReferenceURL]]


What would be sensible weights when fitting simulated probabilities?

Question: I have simulated a set of probabilities $\{p_n\}$ by the hit-or-miss Monte Carlo method. Specifically, my program checks whether or not an $n\times n$ matrix has a certain feature or not; say that, out of $N$ trials, $k_n$ have this feature (success). Then $p_n=k_n/N.$
Question: Now, I want to find the uncertainty (or standard error) $\sigma_{p_n}$ on $p_n$. I'd like to do this so that I can weigh my probabilities when fitting these probabilities as a function of $n.$ My weights are defined as $w_n=\sigma_{p_n}^{-2}.$ This definition seems to be completely standard, but it doesn't go well with my intuition, as explained below. I'd like to know if my intuition is simply wrong (and why), or if there are more suitable weights I could be using.
My problem: As far as I understand, $k_n$ is distributed binomially, so $$\sigma_{p_n}=N^{-1/2}\sqrt{p_n(1-p_n)}$$
This means that a $p_n,$ smaller than some $p_m\leq1/2,$ has a smaller uncertainty than $p_m.$ This makes sense to me (a random walk will not go very far from its starting point if it has a very low probability of taking a step). However, it seems very counter-intuitive to me to weigh a very low probability $p_n$ (where my program perhaps only had $10^2$ successes out of $10^9$ trials) higher than a high probability $p_m$ (which had success, say, half of the time). Using a "relative fluctuation" away from some $p_n$, defined as $$\sigma_{p_n}/p_n=N^{-1/2}\sqrt{\frac{1}{p_n}-1},$$
as my effective uncertainty seems closer to what my intuition tells me is important when choosing my weights.
I'm having a hard time formulating why this is, but it is like this: Flip a coin $100$ times: It comes up heads $54$ times. Flip another coin $100$ times: It comes up heads a single time. Now estimate the bias of each coin. Which estimate are you most confident in? I would say that I'm much more confident in my estimate for the first coin. Should I be? This is the essence of my question.
Comment: Assuming your matrix simulations are independent then $k_n$ does indeed have binomial distribution.  However, the success probability ('$p$') is the probability that a realisation of your matrix has the particular feature.  Your estimate $\sigma_{p_n}$ would itself be subject to uncertainty, depending on how rare your event is and how big $N$ is etc.  Perhaps you can use some elementary probability bounds to estimate the variance of your $\sigma_{p_n}$,
Comment: You could use either (or even something else).  It depends on whether you want to measure the goodness of fit in terms of relative or absolute differences.  If it's the former, which might be wise, you should favor a generalized linear model with a Binomial or Poisson response.
Comment: Btw, yes it's true that the variance for a binomial with low or high success probability $p$ is smaller than that with moderate $p$. .... consider the limiting cases $p = 0$ or $p=1$.  In your example, what is the probability that the true '$p$' for coin B is bigger than $0.1$?  Perhaps you're more confident of your estimate of the bias for coin A because you're in a Bayesian world and have a prior belief distribution on the bias :D
Comment: @P.Windridge 1st comment: I'm assuming that my found $p_n$ are my best guess at a mean, and I therefore use it as the true value in my formulas for $\sigma_{p_n}$. Is this approach flawed? 2nd comment: Perhaps :P, but my point was that coin $A$ has more successes, which just happens to happen around $p=1/2.$
Comment: To help your intuition: with $54$ successes out of $100$ flips, a $95\%$ confidence interval for the underlying probability is (approximately) $[0.45,0.64]$. With $1$ success out of $100$ flips, the interval is (again approximately) $[0.0025, 0.055]$. The uncertainty in the latter is clearly much less than in the former.  The *relative* uncertainty in the latter is much *greater* than in the former.  (That concept is best expressed on an odds scale rather than a probability scale.)
Comment: @whuber Yes, that I think I understand. My question is whether to use the uncertainty or the relative uncertainty when constructing my weights for my fit.
Comment: You write "which might be wise" - could you expand on why that is? Intuitively I'd agree, but I can't seem to formulate a rigorous argument for it. Also, why would one choose a Poisson response? Thanks.
Comment: This does not answer your question. But I would like to add two comments. First, if you have $10^9$  trials, the variance is going to be so tiny, that you could ignore it in your regression. Second, if you have really tiny probabilities and you'd like to use those in a linear regression, you could use log-odds. You could then either compute or simulate the variance of those log-odds values if you wanted to weigh the observations in your regression.
Answer: I performed a simple experiment in R where I performed a Monte Carlo simulation to estimate probabilities in the range 0.01 to 0.5 using 50 samples. I then fit the results using two different weighting methods. The first is the inverse of the variance and the second is the inverse of the coefficient of variation. For the second model, I log transformed the data before fitting.
The first model has lower RMSE and the second model has lower MAPE (mean absolute percentage error). If you are trying to minimize the error in your predictions then you may wish to use the first method. If you are trying to minimize the relative error then you may wish to use the second method.
Side note: You may wish to consider an adaptive sample size in your MCS since it is relatively easy to add the estimate of the error and increase the sample size until it is below a desired threshold.

<code>library(tidyverse)

# Monte Carlo Simulations -------------------------------------------------

N = 50
p <- seq(0.01, 0.5, 0.01)
phat <- NULL
for (i in 1:length(p)) {
  phat[i] <- sum(rbinom(N, 1, p[i])) / N
}

shat <- sqrt(phat * (1 - phat)) / N

myData <-
  data_frame(
    p = p,
    phat = phat,
    shat = shat,
    cv = shat / phat,
    lb = phat - 1.96 * shat,
    ub = phat + 1.96 * shat,
    w1 = 1 / shat^2,
    w2 = 1 / cv
  )

# Plot results ------------------------------------------------------------

ggplot(data = myData, aes(
  x = p,
  y = phat,
  ymin = lb,
  ymax = ub,
)) +
  geom_point(aes(size = w1)) +
  geom_errorbar() +
  labs(title = "weighting by inverse of variance",
       x = "true probability",
       y = "estimated probability") +
  geom_line(aes(x = p, y = p), color = "black", linetype = "dashed")

ggplot(data = myData, aes(
  x = log10(p),
  y = log10(phat),
  ymin = log10(lb),
  ymax = log10(ub)
)) +
  geom_point(aes(size = w2)) +
  geom_errorbar() +
  labs(title = "weighting by inverse of coefficient of variation",
       x = "log true probability",
       y = "log estimated probability") +
  geom_line(aes(x = log10(p), y = log10(p)), color = "black", linetype = "dashed")

# Weighted least squares --------------------------------------------------

fm1 <- lm(phat ~ p, data = myData %>% filter(shat != 0), weights = w1)

fm2 <- lm(log10(phat) ~ log10(p), data = myData %>% filter(shat != 0), weights = w2)

myData <- myData %>%
  filter(shat != 0) %>%
  mutate(pred1 = predict(fm1),
         pred2 = 10^predict(fm2)) %>%
  gather(key, value, pred1, pred2)

myData %>%
  group_by(key) %>%
  summarize(RMSE = sqrt(sum(value - p)^2/n()),
            MAPE = (100/n())*sum(abs((p - value)/p)))

ggplot(data = myData, aes(x = log10(p), y = log10(value), color = key)) +
  geom_line() +
  geom_line(aes(x = log10(p), y = log10(p)), color = "black", linetype = "dashed") +
  labs(title = "ture value vs predictions",
       x = "log true probability",
       y = "log estimated probability")
</code>
Comment: A relevant comparison would be to the unweighted regression.


How to create rule to redirect an admin after log in to an admin specific node?

Question: I have different roles for users of my Drupal 7 site. I have added a rule that whenever an authenticated user logs in they are directed to a node (say node/90). This works fine: both admin and authenticated users are redirected.
However I want that the admin be redirected to a different node say node/25. So I added a new rule and selected under condition that user role is administrator and in action also forced a redirect. However the admin still redirects to node/90. Why so and how can I achieve my use case?
As suggested by NikhilM, I have created a custom module for it and the .module file has
    <?php

function redirect_ad_help($path, $arg) {
  switch ($path) {
    case "admin/help#redirect_ad":
      return '
' . t("Redirect") . '
';
      break;
  }
}
function redirect_ad_user_login(&$edit, $account) {
 if($account->uid == 1)
  drupal_goto('node->97');
 else
  drupal_goto('node->69');
}

I also tried doing $edit['redirect'] = 'node/97'; instead of drupal_goto() but I am taken to the home page only and not to the desired node.
Comment: can you update your question with your latest module i.e after replacing `node->97` with `node/97` ?
Comment: @2-Stroker..have done that...thanks for your concern but its still not working...any suggestions
Answer: My guess would be that your rule weights are not as they should be.  If your rule that matches the admin role fires first and your rule that matches all authenticated users fires second then admins will always be redirected to node/90.
Check on the weights.  In your case, you want the more specific rules (the one for admins) to fire second.  So you need to make its weight larger than the more general rule.
Does that make it work for you?  I don't think you should need a custom module for this...
Also - disable the custom module while you're testing this out, to make sure the two are not interfering.
Comment: how can i change the weights for rules...even i thought of that option but was not getting how to do it
Comment: ok that did it..quite simple actually
Answer: You can do that with hook_user_login
function hook_user_login(&$edit, $account) {
 if($account->uid == 1)
  drupal_goto('node/25');
 else
  drupal_goto('node/90');
}

replace drupal_goto('node->97'); with drupal_goto('node/97');
Give it a try let me know the result.
Comment: replace `drupal_goto('node->97');` with `drupal_goto('node/97');`
Comment: ...setting weights to rules did it....quite simple actually...no need to add any custom module
Comment: I am not sure about the possibility to do this with Rules.
Comment: ok..i have created a small custom module for this and in the .module file i have added: ' . t("Redirect fro admin") . '';
      break;
  }
}
function redirect_ad_user_login(&$edit, $account) {
 global $user;
 if($user->uid == 1)
  drupal_goto('node->97');
}....but then the admin is taken to the home page
Comment: ...i added the module code in the question
Comment: Make sure the node exists.
Comment: yes i already tried that but it takes me to homepage only ,i.e, localhost/node
Comment: and yes the node exists as i can navigate to it by typing in the address in the browser
Comment: replace drupal_goto('node->97'); with drupal_goto('node/97');
Comment: i have tried that (i.e, replacing node->97 with node/97) but it takes me to homepage only ,i.e, localhost/node
Comment: i even tried with an external address such as http://google.com but it still takes me to the homepage
Comment: disable your rules and do exactly in my example.
Comment: tried that...disabled the rule...copied the exact same code from you...tried both node->97 and node/97...doesn't work
Comment: just to confirm did you enabled the module ?
Comment: yes...i have enabled the module
Comment: i do have another redirect rule enabled but that redirects when a relationship action takes place so it should not effect this. However i will just disable this too and try again
Comment: Please do that .
Comment: still not working
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/7964/discussion-between-nikhil-m-and-kewal)
Answer: Even though the currently accepted answer may have helped to solve the issue in the question, I think it is not 100% accurate (not correct, maybe even a bit misleading). Moreover there is an alternative solution also. Read on for more details ...
About using Rules Weight
To indicate a "weight" for a custom rule, you use the field in the rules UI that looks like so:

Note what is written below that weight field, i.e "Order rules that react on the same event. Rules with a higher weight are evaluated after rules with less weight".
Let's apply this to what's suggested in the currently accepted answer:

There are 2 rules, which both seem to react to the same event (= "User has logged in").
By changing the weights of both rules, the rule with the lower weight is executed first, and the one with the higher weight afterwards. Quote from the accepted answer:

... you want the more specific rules (the one for admins) to fire second. So you need to make its weight larger ...

That's indeed "a" way to get it to work (to meet the specs as in the question). However, it does also mean that BOTH rules are executed, for anybody (not just admins ...) who performs a login:

The 1st rule for authenticated users gets executed for anybody who performs a login (note: so also for admins ...). That is, the redirect to node/90 gets executed.
Authenticated users that do not have the admin role, do not satisfy the Rules Condition, so the Rules Action of the 2nd rule for admin does not execute.
Authenticated users that do have the admin role, do satisfy the Rules Condition, so the Rules Action of the rule for admin does execute. That is, the redirect to node/25 gets executed also.

The result of this is that for a use that has the admin role, actually 2 redirects are performed: first to node/90 (as per the 1st rule), followed by a redirect to node/25 (as per the 2nd rule). For those who don't believe (or get) it: just add a Drupal action like "Show a message on the site" in both rules (for admins you'll get both messages).
Alternative to using Rules Weight
Apart from redundant Rules logic that gets executed (as explained above),  using Rules Weights to get things to work (= implement the appropriate execution sequence) has some challenges, which I try to avoid whenever possible.
In this case (= scenario in the question), an alternative solution appears to be to use the Conditional Rules module. Have a look at this rule (in Rules export format) which uses this module, and which also implements the very same logic as described in the question:
{ "rules_redirect_each_role_to_separate_page" : {
    "LABEL" : "Redirect selected roles to selected pages",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules_conditional", "rules" ],
    "ON" : { "user_login" : [] },
    "DO" : [
      { "CONDITIONAL" : [
          {
            "IF" : { "user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "3" : "3" } } } },
            "DO" : [ { "redirect" : { "url" : "node\/25" } } ]
          },
          { "ELSE" : [ { "redirect" : { "url" : "node\/90" } } ] }
        ]
      }
    ]
  }
}

After you enabled the Conditional Rules module, just use the Rules UI to import the above rule in your own site, enable the rule, and see what happens ... No need for "Rules Weight", and only using a single rule (to see the entire Rules logic in a single screen when using the Rules UI). And for users that do have the admin role, there is no (repeat: no) redundant redirect to node/25.
What is more: imagine that you'd have to implement a redirect that depends on (say) 5 roles, so that you need to redirect to one of 5 pages. All it's take is to extend the IF/THEN/ELSE logic with 3 more appropriate redirects (instead of tuning the Rules Weights for 5 different rules ...).


In Javascript does async await wait for all nested functions to complete?

Question: In the example below I need to reset some values before making the fetchData call in the fetch method. Does async await wait for all functions in the reset method to complete before continuing?
fetch = async () => {
  await this.reset();
  this.props.fetchData();
};

reset = () => {
  this.props.resetFilter();
  this.props.resetClient();
  this.props.resetUser();
};

Or do you have to do something like below?
fetch = () => {
  this.reset().then(() => {
    this.props.fetchData();
  });
};

reset = async () => {
  await this.props.resetFilter();
  await this.props.resetClient();
  await this.props.resetUser();
};

Thanks :)
Comment: reset functions return a promise?
Comment: @MohammedAshfaq no they don't return a promise. They are actions which will reset values in a reducer
Answer: async/await does not magically deal with asynchronous function.
It is a syntax addition that allows you to easier work with promises.
So whenever a function returns a Promise, you need to wait for it explicitly.
Either by writing await in front of each if you want to execute them in order, as you have shown in your second example:
reset = async () => {
  await this.props.resetFilter();
  await this.props.resetClient();
  await this.props.resetUser();
};

Or if you want to allow that those asynchounous function to interleave Promise.all:
reset = async () => {
  await Promise.all([
    this.props.resetFilter(),
    this.props.resetClient(),
    this.props.resetUser()
  ])
};

If you do not wait for the Promises like in your first example:
reset = () => {
  this.props.resetFilter();
  this.props.resetClient();
  this.props.resetUser();
};

then the promise chain is broken for that three call, this might not look like be a problem at first, especially if you assume that they always resolve. But can result in an unhandled rejection if on of this promises is rejected.
Answer: This function returns undefined without waiting for all function calls to be settled.
reset = () => {
  this.props.resetFilter();
  this.props.resetClient();
  this.props.resetUser();
};

If you want to make sure that a value is returned only if all calls are settled, you would need to await (or chain promises, or ...)
Thus
reset = async () => {
  await this.props.resetFilter();
  await this.props.resetClient();
  await this.props.resetUser();
};

is one correct way to go to archive your desired behaviour.


Distribution of $2X$

Question: I'm fairly new to statistics
I'm confused if the distribution of a random variable $X$ and $2X$ are the same, since the variance of the latter is $\mathbb{V}(2X) = 4 \mathbb{V}(X)$. Is it exactly the same distribution or the statistical distance is negligible that they are considered the same distribution?
Comment: It is certainty not the exactly the same distribution, but it may be in the same family of distributions. You are considering a particular example of a [location-scale family](https://en.wikipedia.org/wiki/Location%E2%80%93scale_family)
Answer: No, they have a different distribution (though in some cases they still have the same distributional family).  There are some simple rules for deriving one distribution from the other, which depend on whether you are working with discrete or continuous distributions.  To faciliate the analysis, let $Y=2X$ denote the random variable that comes from doubling $X$.  The rules for the distributions are as follows.

Discrete case: If $X$ is a discrete random variable then the probability mass of $Y$ is:
$$p_Y(y) = p_X(\tfrac{y}{2}).$$
Continuous case: If $X$ is a continuous random variable then the probability density of $Y$ is:
$$f_Y(y) = \frac{1}{2} \cdot f_X(\tfrac{y}{2}).$$
Comment: Thanks. If X is a discrete Gaussian, is the statistical distance between X and 2X small? It is not intuitive to me yet
Comment: The Gaussian distribution is a *continuous* distribution, not discrete.  In any case, the "distance" between $X$ and $2X$ is presumably always $|X-2X| = |X|$.

Distribution of $2X$


Thread blocked when using Infinispan 9 embedded cache with L1

Question: I'm using Infinispan 9.4.16 in embedded mode. Here is the config of a cache:
<code><distributed-cache name="mycache" mode="SYNC" remote-timeout="15000" l1-lifespan="60000" owners="1" segments="80">
    <locking striping="false" concurrency-level="100" acquire-timeout="60000"/>
    <persistence>
        ...
    </persistence>
    <state-transfer chunk-size="512" timeout="240000"/>
</distributed-cache>
</code>
I run a cluster of 4 nodes. The entries in this cache could be read, updated or removed concurrently.
So randomly, a thread got blocked (waiting indefinitely) with this stack trace:
<code>"a-thread-1" #403 daemon prio=5 os_prio=0 tid=0x0000000023acf800 nid=0x5257 waiting on condition [0x00007fc801941000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x000000066c879658> (a org.infinispan.interceptors.distribution.L1WriteSynchronizer$L1WriteSync)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.parkAndCheckInterrupt(AbstractQueuedSynchronizer.java:836)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.doAcquireSharedInterruptibly(AbstractQueuedSynchronizer.java:997)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireSharedInterruptibly(AbstractQueuedSynchronizer.java:1304)
    at org.infinispan.interceptors.distribution.L1WriteSynchronizer$L1WriteSync.innerGet(L1WriteSynchronizer.java:93)
    at org.infinispan.interceptors.distribution.L1WriteSynchronizer.get(L1WriteSynchronizer.java:142)
    at org.infinispan.interceptors.distribution.L1NonTxInterceptor.abortL1UpdateOrWait(L1NonTxInterceptor.java:335)
    at org.infinispan.interceptors.distribution.L1NonTxInterceptor.removeFromL1Command(L1NonTxInterceptor.java:405)
    at org.infinispan.interceptors.distribution.L1NonTxInterceptor.lambda$handleDataWriteCommand$10(L1NonTxInterceptor.java:382)
    at org.infinispan.interceptors.distribution.L1NonTxInterceptor$$Lambda$1347/746020467.apply(Unknown Source)
    at org.infinispan.interceptors.impl.SimpleAsyncInvocationStage.addCallback(SimpleAsyncInvocationStage.java:70)
    at org.infinispan.interceptors.InvocationStage.andHandle(InvocationStage.java:65)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNextAndHandle(BaseAsyncInterceptor.java:190)
    at org.infinispan.interceptors.distribution.L1NonTxInterceptor.handleDataWriteCommand(L1NonTxInterceptor.java:362)
    at org.infinispan.interceptors.distribution.L1NonTxInterceptor.visitRemoveCommand(L1NonTxInterceptor.java:247)
    at org.infinispan.commands.Visitor.visitRemoveExpiredCommand(Visitor.java:66)
    at org.infinispan.commands.write.RemoveExpiredCommand.acceptVisitor(RemoveExpiredCommand.java:63)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNextThenApply(BaseAsyncInterceptor.java:74)
    at org.infinispan.interceptors.impl.DistCacheWriterInterceptor.visitRemoveCommand(DistCacheWriterInterceptor.java:107)
    at org.infinispan.commands.Visitor.visitRemoveExpiredCommand(Visitor.java:66)
    at org.infinispan.commands.write.RemoveExpiredCommand.acceptVisitor(RemoveExpiredCommand.java:63)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNext(BaseAsyncInterceptor.java:54)
    at org.infinispan.interceptors.impl.CacheLoaderInterceptor.visitDataCommand(CacheLoaderInterceptor.java:197)
    at org.infinispan.interceptors.impl.CacheLoaderInterceptor.visitRemoveCommand(CacheLoaderInterceptor.java:164)
    at org.infinispan.commands.Visitor.visitRemoveExpiredCommand(Visitor.java:66)
    at org.infinispan.commands.write.RemoveExpiredCommand.acceptVisitor(RemoveExpiredCommand.java:63)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNextThenAccept(BaseAsyncInterceptor.java:98)
    at org.infinispan.interceptors.impl.EntryWrappingInterceptor.setSkipRemoteGetsAndInvokeNextForDataCommand(EntryWrappingInterceptor.java:671)
    at org.infinispan.interceptors.impl.EntryWrappingInterceptor.visitRemoveExpiredCommand(EntryWrappingInterceptor.java:363)
    at org.infinispan.commands.write.RemoveExpiredCommand.acceptVisitor(RemoveExpiredCommand.java:63)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNextThenApply(BaseAsyncInterceptor.java:74)
    at org.infinispan.interceptors.distribution.L1LastChanceInterceptor.visitDataWriteCommand(L1LastChanceInterceptor.java:136)
    at org.infinispan.interceptors.distribution.L1LastChanceInterceptor.visitRemoveCommand(L1LastChanceInterceptor.java:82)
    at org.infinispan.commands.Visitor.visitRemoveExpiredCommand(Visitor.java:66)
    at org.infinispan.commands.write.RemoveExpiredCommand.acceptVisitor(RemoveExpiredCommand.java:63)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNext(BaseAsyncInterceptor.java:54)
    at org.infinispan.interceptors.locking.AbstractLockingInterceptor.visitNonTxDataWriteCommand(AbstractLockingInterceptor.java:124)
    at org.infinispan.interceptors.locking.NonTransactionalLockingInterceptor.visitDataWriteCommand(NonTransactionalLockingInterceptor.java:40)
    at org.infinispan.interceptors.locking.AbstractLockingInterceptor.visitRemoveCommand(AbstractLockingInterceptor.java:102)
    at org.infinispan.commands.Visitor.visitRemoveExpiredCommand(Visitor.java:66)
    at org.infinispan.commands.write.RemoveExpiredCommand.acceptVisitor(RemoveExpiredCommand.java:63)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNextAndHandle(BaseAsyncInterceptor.java:183)
    at org.infinispan.statetransfer.StateTransferInterceptor.handleNonTxWriteCommand(StateTransferInterceptor.java:309)
    at org.infinispan.statetransfer.StateTransferInterceptor.handleWriteCommand(StateTransferInterceptor.java:252)
    at org.infinispan.statetransfer.StateTransferInterceptor.visitRemoveCommand(StateTransferInterceptor.java:108)
    at org.infinispan.commands.Visitor.visitRemoveExpiredCommand(Visitor.java:66)
    at org.infinispan.commands.write.RemoveExpiredCommand.acceptVisitor(RemoveExpiredCommand.java:63)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNextAndFinally(BaseAsyncInterceptor.java:150)
    at org.infinispan.interceptors.impl.CacheMgmtInterceptor.visitRemoveCommand(CacheMgmtInterceptor.java:431)
    at org.infinispan.commands.Visitor.visitRemoveExpiredCommand(Visitor.java:66)
    at org.infinispan.commands.write.RemoveExpiredCommand.acceptVisitor(RemoveExpiredCommand.java:63)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNext(BaseAsyncInterceptor.java:54)
    at org.infinispan.interceptors.impl.IsMarshallableInterceptor.visitRemoveCommand(IsMarshallableInterceptor.java:63)
    at org.infinispan.commands.Visitor.visitRemoveExpiredCommand(Visitor.java:66)
    at org.infinispan.commands.write.RemoveExpiredCommand.acceptVisitor(RemoveExpiredCommand.java:63)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNext(BaseAsyncInterceptor.java:54)
    at org.infinispan.interceptors.DDAsyncInterceptor.handleDefault(DDAsyncInterceptor.java:54)
    at org.infinispan.interceptors.DDAsyncInterceptor.visitRemoveCommand(DDAsyncInterceptor.java:65)
    at org.infinispan.commands.Visitor.visitRemoveExpiredCommand(Visitor.java:66)
    at org.infinispan.commands.write.RemoveExpiredCommand.acceptVisitor(RemoveExpiredCommand.java:63)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNextAndExceptionally(BaseAsyncInterceptor.java:123)
    at org.infinispan.interceptors.impl.InvocationContextInterceptor.visitCommand(InvocationContextInterceptor.java:90)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNext(BaseAsyncInterceptor.java:56)
    at org.infinispan.interceptors.DDAsyncInterceptor.handleDefault(DDAsyncInterceptor.java:54)
    at org.infinispan.interceptors.DDAsyncInterceptor.visitRemoveCommand(DDAsyncInterceptor.java:65)
    at org.infinispan.commands.Visitor.visitRemoveExpiredCommand(Visitor.java:66)
    at org.infinispan.commands.write.RemoveExpiredCommand.acceptVisitor(RemoveExpiredCommand.java:63)
    at org.infinispan.interceptors.DDAsyncInterceptor.visitCommand(DDAsyncInterceptor.java:50)
    at org.infinispan.interceptors.impl.AsyncInterceptorChainImpl.invokeAsync(AsyncInterceptorChainImpl.java:234)
    at org.infinispan.cache.impl.CacheImpl.executeCommandAndCommitIfNeededAsync(CacheImpl.java:1930)
    at org.infinispan.cache.impl.CacheImpl.performRemoveExpiredCommand(CacheImpl.java:717)
    at org.infinispan.cache.impl.CacheImpl.removeLifespanExpired(CacheImpl.java:698)
    at org.infinispan.cache.impl.CacheImpl.removeLifespanExpired(CacheImpl.java:690)
    at org.infinispan.expiration.impl.ClusterExpirationManager.handleLifespanExpireEntry(ClusterExpirationManager.java:143)
    at org.infinispan.expiration.impl.ClusterExpirationManager.entryExpiredInMemory(ClusterExpirationManager.java:201)
    at org.infinispan.container.impl.AbstractInternalDataContainer.containsKey(AbstractInternalDataContainer.java:168)
    at org.infinispan.container.impl.AbstractInternalDataContainer.containsKey(AbstractInternalDataContainer.java:178)
    at org.infinispan.interceptors.distribution.L1WriteSynchronizer.runL1UpdateIfPossible(L1WriteSynchronizer.java:173)
    at org.infinispan.distribution.impl.L1ManagerImpl.remoteValueFound(L1ManagerImpl.java:196)
    at org.infinispan.interceptors.distribution.BaseDistributionInterceptor.lambda$remoteGetSingleKey$1(BaseDistributionInterceptor.java:211)
    at org.infinispan.interceptors.distribution.BaseDistributionInterceptor$$Lambda$1388/1407890021.accept(Unknown Source)
    at java.util.concurrent.CompletableFuture.uniAccept(CompletableFuture.java:670)
    at java.util.concurrent.CompletableFuture.uniAcceptStage(CompletableFuture.java:683)
    at java.util.concurrent.CompletableFuture.thenAccept(CompletableFuture.java:2010)
    at java.util.concurrent.CompletableFuture.thenAccept(CompletableFuture.java:110)
    at org.infinispan.interceptors.distribution.BaseDistributionInterceptor.remoteGetSingleKey(BaseDistributionInterceptor.java:200)
    at org.infinispan.interceptors.distribution.BaseDistributionInterceptor.visitGetCommand(BaseDistributionInterceptor.java:666)
    at org.infinispan.interceptors.distribution.BaseDistributionInterceptor.visitGetKeyValueCommand(BaseDistributionInterceptor.java:672)
    at org.infinispan.commands.read.GetKeyValueCommand.acceptVisitor(GetKeyValueCommand.java:39)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNextAndFinally(BaseAsyncInterceptor.java:150)
    at org.infinispan.interceptors.distribution.L1NonTxInterceptor.performL1Lookup(L1NonTxInterceptor.java:157)
    at org.infinispan.interceptors.distribution.L1NonTxInterceptor.performCommandWithL1WriteIfAble(L1NonTxInterceptor.java:132)
    at org.infinispan.interceptors.distribution.L1NonTxInterceptor.visitDataReadCommand(L1NonTxInterceptor.java:123)
    at org.infinispan.interceptors.distribution.L1NonTxInterceptor.visitGetKeyValueCommand(L1NonTxInterceptor.java:112)
    at org.infinispan.commands.read.GetKeyValueCommand.acceptVisitor(GetKeyValueCommand.java:39)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNext(BaseAsyncInterceptor.java:54)
    at org.infinispan.interceptors.DDAsyncInterceptor.handleDefault(DDAsyncInterceptor.java:54)
    at org.infinispan.interceptors.DDAsyncInterceptor.visitGetKeyValueCommand(DDAsyncInterceptor.java:106)
    at org.infinispan.commands.read.GetKeyValueCommand.acceptVisitor(GetKeyValueCommand.java:39)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNext(BaseAsyncInterceptor.java:54)
    at org.infinispan.interceptors.impl.CacheLoaderInterceptor.visitDataCommand(CacheLoaderInterceptor.java:197)
    at org.infinispan.interceptors.impl.CacheLoaderInterceptor.visitGetKeyValueCommand(CacheLoaderInterceptor.java:130)
    at org.infinispan.commands.read.GetKeyValueCommand.acceptVisitor(GetKeyValueCommand.java:39)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNextThenAccept(BaseAsyncInterceptor.java:98)
    at org.infinispan.interceptors.impl.EntryWrappingInterceptor.visitDataReadCommand(EntryWrappingInterceptor.java:204)
    at org.infinispan.interceptors.impl.EntryWrappingInterceptor.visitGetKeyValueCommand(EntryWrappingInterceptor.java:192)
    at org.infinispan.commands.read.GetKeyValueCommand.acceptVisitor(GetKeyValueCommand.java:39)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNext(BaseAsyncInterceptor.java:54)
    at org.infinispan.interceptors.DDAsyncInterceptor.handleDefault(DDAsyncInterceptor.java:54)
    at org.infinispan.interceptors.DDAsyncInterceptor.visitGetKeyValueCommand(DDAsyncInterceptor.java:106)
    at org.infinispan.commands.read.GetKeyValueCommand.acceptVisitor(GetKeyValueCommand.java:39)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNext(BaseAsyncInterceptor.java:54)
    at org.infinispan.interceptors.locking.NonTransactionalLockingInterceptor.visitDataReadCommand(NonTransactionalLockingInterceptor.java:34)
    at org.infinispan.interceptors.locking.AbstractLockingInterceptor.visitGetKeyValueCommand(AbstractLockingInterceptor.java:107)
    at org.infinispan.commands.read.GetKeyValueCommand.acceptVisitor(GetKeyValueCommand.java:39)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNextAndHandle(BaseAsyncInterceptor.java:183)
    at org.infinispan.interceptors.impl.BaseStateTransferInterceptor.handleReadCommand(BaseStateTransferInterceptor.java:193)
    at org.infinispan.interceptors.impl.BaseStateTransferInterceptor.visitGetKeyValueCommand(BaseStateTransferInterceptor.java:168)
    at org.infinispan.commands.read.GetKeyValueCommand.acceptVisitor(GetKeyValueCommand.java:39)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNextAndFinally(BaseAsyncInterceptor.java:150)
    at org.infinispan.interceptors.impl.CacheMgmtInterceptor.visitDataReadCommand(CacheMgmtInterceptor.java:120)
    at org.infinispan.interceptors.impl.CacheMgmtInterceptor.visitGetKeyValueCommand(CacheMgmtInterceptor.java:95)
    at org.infinispan.commands.read.GetKeyValueCommand.acceptVisitor(GetKeyValueCommand.java:39)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNext(BaseAsyncInterceptor.java:54)
    at org.infinispan.interceptors.DDAsyncInterceptor.handleDefault(DDAsyncInterceptor.java:54)
    at org.infinispan.interceptors.DDAsyncInterceptor.visitGetKeyValueCommand(DDAsyncInterceptor.java:106)
    at org.infinispan.commands.read.GetKeyValueCommand.acceptVisitor(GetKeyValueCommand.java:39)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNext(BaseAsyncInterceptor.java:54)
    at org.infinispan.interceptors.DDAsyncInterceptor.handleDefault(DDAsyncInterceptor.java:54)
    at org.infinispan.interceptors.DDAsyncInterceptor.visitGetKeyValueCommand(DDAsyncInterceptor.java:106)
    at org.infinispan.commands.read.GetKeyValueCommand.acceptVisitor(GetKeyValueCommand.java:39)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNextAndExceptionally(BaseAsyncInterceptor.java:123)
    at org.infinispan.interceptors.impl.InvocationContextInterceptor.visitCommand(InvocationContextInterceptor.java:90)
    at org.infinispan.interceptors.BaseAsyncInterceptor.invokeNext(BaseAsyncInterceptor.java:56)
    at org.infinispan.interceptors.DDAsyncInterceptor.handleDefault(DDAsyncInterceptor.java:54)
    at org.infinispan.interceptors.DDAsyncInterceptor.visitGetKeyValueCommand(DDAsyncInterceptor.java:106)
    at org.infinispan.commands.read.GetKeyValueCommand.acceptVisitor(GetKeyValueCommand.java:39)
    at org.infinispan.interceptors.DDAsyncInterceptor.visitCommand(DDAsyncInterceptor.java:50)
    at org.infinispan.interceptors.impl.AsyncInterceptorChainImpl.invoke(AsyncInterceptorChainImpl.java:248)
    at org.infinispan.cache.impl.CacheImpl.get(CacheImpl.java:527)
    at org.infinispan.cache.impl.CacheImpl.get(CacheImpl.java:520)
    at org.infinispan.cache.impl.AbstractDelegatingCache.get(AbstractDelegatingCache.java:438)
    at org.infinispan.cache.impl.EncoderCache.get(EncoderCache.java:660)
</code>
After some investigation, I found out that the thread is blocked by itself. But I don't know how it is possible. Is this an issue of Infinispan ?
Comment: 1) Thread cannot deadlock itself
2) Your stack trace is not deadlocked, it is just waiting on some condition
Comment: "parking to wait for  <0x000000066c879658" means waiting for this lock, you can take full thread dump and check which thread is holding it. Probably, it will give you some clue
Comment: I'm sorry, I must not say "deadlock" here, I edited my question. The problem is the thread is waiting for something that will never be done, because the thread is blocked when doing this thing. This is what I understand from the code.
Comment: it cannot write because smth holds the write lock.
Comment: Yes, the lock is hold by the thread itself, at the line L1WriteSynchronizer.runL1UpdateIfPossible(L1WriteSynchronizer.java:173)
Answer: From the stack trace it appears that the entry had expired via lifespan expiration at the same time. I would suggest logging a JIRA to https://issues.redhat.com/projects/ISPN. This seems to be an unexpected interaction between expiration and L1 usage.
I am assuming you must be using the programmatic method with lifespan when inserting values as well, since your configuration does not have expiration enabled.
Comment: I noticed that somehow the entry expired but I don't use expiration at all so I really don't understand why it happened.
Comment: You're using expiration indirectly, L1 entries automatically expire after 10 minutes. Setting the L1 lifespan to -1 should disable the expiration.
Comment: If I disable the expiration, the entries will stay forever in the L1 and occupy memory ?
Comment: They will only stay in L1 as long as the entry is not changed. Also if you enable eviction that will clear out old unused L1 entries.


Deducing the number of divisors if we know their form

Question: The task is to find out how many positive integers divide at least one of the given numbers:
$10^{60}$, $20^{50}$, $30^{40}$. This is easily calculated using the inclusion-exclusion principle.
First, we have to figure out the form of divisors for each of these numbers.

$10^{60}=(2\cdot5)^{60}=2^{60}\cdot5^{60}$, which means divisors of
this number are of form $2^{i}\cdot5^{j}$ where $0\le{i},j\le{60}$

$20^{50}=(2\cdot2\cdot5)^{50}=2^{2\cdot50}\cdot5^{50}$, divisors:
$2^{2\cdot{i}}\cdot5^{j}$ where $0\le{i},j\le{50}$
$30^{40}=(2\cdot3\cdot5)^{40}=2^{40}\cdot3^{40}\cdot5^{40}$,
divisors: $2^{i}\cdot3^{j}\cdot5^{k}$ where
$0\le{i},{j},{k}\le{40}$

Number of divisiors of form $2^{i}\cdot5^{j}$ where $0\le{i},j\le{60}$ equals $61\cdot61$, because we have 61 combinations for both $i$ and $j$. Following this logic, number of divisiors of form $2^{2\cdot{i}}\cdot5^{j}$ where $0\le{i},j\le{50}$ should be $51\cdot51$, because we have 51 choices for $i$ and $j$. But, the solution I read said the number of these divisors is $101\cdot51$. I feel like this has something to do with $2^{2\cdot{i}}$, although this equals to $4^{i}$ and shouldn't change anything. Could the solution be wrong?

Thank you in advance.
Comment: You should just express $20^{50}$ as $2^{100}\cdot5^{50}$
Comment: Why do you say a divisor of $20^{50}$ has to be of the form $2^{2\cdot i}\cdot5^j$? Isn't $2$ a divisor of $20^{50}$? How is $2$ of that form?
Answer: Note that $2^{2*50}=2^{100}$. Thus, there are $101$ such numbers of the form $2^j$ such that $0 \leq j \leq 100$. You reasoned about this the right way but got a little too caught up! The first and last problems behave similarly since their exponents were such that $i=j=k$.
Just to complete the problem: Using the reasoning you mentioned, we have that there are $101*51$ ways to make numbers of the form $2^j5^k$ such that $0\leq j \leq 100$ and $0 \leq k \leq 50$.


Calculate integral with $z^a$ using residue theorem

Question: I am trying to solve the following:

Find $\int_0^\infty \frac{x^a}{x^2+3x+2}dx$ for $0<a<1$ by using the residue theorem.

I thought to let $f(z)=\frac{z^a}{z^2+3z+2}$ and by taking the branch cut on $\mathbb C$ minus the positive reals, I could integrate over the keyhole contour formed by a circle of radius R with the keyhole lying on the positive reals and an epsilon ball around 0 (I can include a picture if this is not clear enough).
If I calculated my residues at $-2$ and $-1$ correctly, then the integral over the entire contour should be $-2^a(2\pi i)$. The integrals over the circular parts should go to 0. But I am having trouble making the integrals over the horizontal line segments look like the original integral I wanted to calculate; I know they're not supposed to cancel each other out but I can't figure out how to combine them correctly. Any tips would be appreciated!
Answer: HINTS:
On the "upper" part of the branch cut, $z^a=x^a$, while on the lower part, $z^a=x^a\,e^{i2\pi a}$.
Hence, you will obtain
$$(1-e^{i2\pi a})\int_0^\infty \frac{x^a}{x^2+3x+2}\,dx=2\pi i \times \text{Sum of the Residues}$$
Now, check.your calculation of the residues.  On the negative real axis $z^a=|x|^a e^{i\pi a}$
Comment: Ahh, gotcha. I realize I had my contour wrong: I had only been considering horizontal line segments but I see now that I should've been looking at radial line segments, where the angle is a third parameter $\delta$ that tends to 0. And yes, my residue calculations were wrong. Thanks!
Comment: You're welcome.  My pleasure.


Error Calculating MVN Likelihood of Time Series with AR(1) Errors in R

Question: I'm having trouble calculating the likelihood of a time series with AR(1) errors. I am generating my covariance matrix according to page 2 of (http://cran.r-project.org/doc/contri...regression.pdf), using the library mvtnorm and the multivariate normal density function dmvnorm(). Here's some example code:
library(mvtnorm)

# Generate a basic time series with AR(1) Errors:

t <- 1:100

error <- as.numeric(arima.sim(n = length(t), list(ar = c(0.8897)), sd = 10))

series <- 5*t + error

# Fit the series using a basic linear model assuming errors are IID Normal

naive.model <- lm(series ~ t -1)

# Examine and model the residuals

residuals <- series - t*coef(naive.model)

residual.model <-  arima(residuals, c(1,0,0), include.mean=F)

# Construct the covariance matrix, assuming the process variance (10^2) is known

sigma <- diag(length(t))

sigma[(abs(row(sigma)-col(sigma)) == 1)] = as.numeric(coef(residual.model))

sigma <- sigma*10^2

# Calculate the MVN density...

dmvnorm(series, t*coef(naive.model) ,sigma, log=T)

Without fail, I get the following error message:
Warning message: In log(eigen(sigma, symmetric = TRUE, only.values = TRUE)$values) : NaNs produced.

It's worth noting that the matrix from the following (https://stat.ethz.ch/pipermail/r-hel...ay/131728.html) "works", but I think is actually for an MA(1) process rather than an AR(1) process.
I gather the message means the proposed covariance matrix may not be invertible. This said I'm stuck on how to proceed and would be extremely appreciative of any thoughts.
Thank you very much,
Answer: Your covariance matrix construction is incorrect. In particular, you have a tridiagonal matrix, but an AR(1) covariance matrix has no zeros. The offdiagonal elements should have correlations that are the AR(1) coefficient raised to the difference in times between the two observations, i.e. the difference between the row and column number.
Define sigma using this code:
D     = diag(length(t))
rho   = coef(residual.model)
corr  = rho^abs(row(D)-col(D))
sigma = 10^2/(1-rho^2) * corr

This AR(1) covariance matrix construction in R was taken from here.
Comment: You forgot to multiply by the variance, which depends on rho. The correct code would be `sigma=rho^abs(row(Sigma)-col(Sigma))/(1-rho^2)`, where `rho=coef(residual.model)`
Comment: You're absolutely correct. I have updated my answer to fully define sigma.


Eloquent select from database, get results newer than a given unix timestamp

Question: I would like to select rows from my database newer than some specified UNIX timestamp specified in the parameters.
The column created_at is a datetime in the table tracks.
The parameter $timestamp is a UNIX timestamp (an integer).
So I am trying with
Tracks::where('created_at','>=',$timestamp)->get(); which simply returns all tracks, no matter which $timestamp I specify.
However I can see the type problem, and I have tried different things like writing 'UNIX_TIMESTAMP(created_at)' instead of created_at, but with no luck.
So I assume there is some elegant and simple way of doing this. Can you help me?
Answer: There are 2 ways to solve this.

Use Tracks::where(DB::raw('UNIX_TIMESTAMP(created_at)'),'>=',$timestamp)
Use a DateTime or Carbon object.

like this:
$timestamp = Carbon\Carbon::createFromTimestamp($timestamp);
Tracks::where('created_at','>=',$timestamp)->get();

Comment: Beautiful. Thanks. Used the Carbon-method.


Office365 licenses management with powershell

Question: We have a hybrid office365, I wrote a script that creates users in our AD and it assigns our default office365 package. Everything works, but since we don't usually have free licenses, I need to log into office365, buy the new licenses and then run the script.
The question is: is it actually possible to buy licenses from powershell or exists some magic way to do that? I don't mean assign licenses, that's easy, but buy new licenses ready to be assigned.
It's not a huge problem to buy some licenses before running the script, it just doesn't make sense to run a script if I need to use the dashboard anyway.
Thanks!
Comment: @iwasatenbyagrue
I appreciate the correction, but your edit leaves people thinking that I didn't spent a second searching for this answer, while I've read every single post on google about this argument with no luck.
Answer: Short answer: No, I don't think so.
For Enterprise tenants, licenses are generally purchased ("Reserved") through the Volume License Service Center.  From here, processes may vary (resellers, etc.), but eventually the tenant ends up with new licenses.
For Retail tenants, a transaction needs to occur.  It's been a while, but you pick the licenses from a big list, and then there is a credit card order processing page, then licenses appear in the tenant.
Either way, there are no MSOL nor Azure AD PowerShell cmdlets to add a license to a tenant.
Comment: I usually go under "Subscriptions" of our office365 admin page, and I just "Add" licenses from there, a credit card is already linked. So, because is that simple, I just thought some kind of powershell command could achieve that. I'm really disappointed, I wanted my script to work without any intervention and this makes it impossible :(
Comment: Well, after the hours spent on this and your answer, I think this question can be closed, maybe in future..


How to get a part of a current content in umbraco

Question: My question is: How can I get a part of a current content in Umbraco CMS in backend file (*.master.cs)? About 350 characters, but i'm sure, that a large does not matter. Is there any useful method to do it?
Umbraco version: 4.6.2.
Regards
Answer: I found solution myself:

<code>   string part = currentNode.GetProperty("bodyText").Value.Substring(0, 450) + "...";
</code>


Can't Click on the First Image in the crossfading effect

Question:

var timer = setInterval(nextImage, 4000);
var curImage = 0;
var numImages = 2;

function nextImage() {
    var e;
    // remove showMe class from current image
    e = document.getElementById("slideimg" + curImage);
    removeClass(e, "showMe");

    // compute next image
    curImage++;
    if (curImage > numImages - 1) {
        curImage = 0;
    }

    // add showMe class to next image
    e = document.getElementById("slideimg" + curImage);
    addClass(e, "showMe");
}

function addClass(elem, name) {
    var c = elem.className;
    if (c) c += " ";  // if not blank, add a space separator
    c += name;
    elem.className = c;
}

function removeClass(elem, name) {
    var c = elem.className;
    elem.className = c.replace(name, "").replace(/\s+/g, " ").replace(/^\s+|\s+$/g, "");  // remove name and extra blanks
}

$('#cf4a').on('click', '.slide.showMe', function () {
    let url = $(this).attr('data-url')
    console.log(url)
    //location.href = url (this is where the user should go when clicking on the image)

})
#cf4a {
    position: relative;
    width: 5em !important;
}

.container {
  width: 100vh;
  height: 60vh;
}

.slide {
    border: none;
    opacity: 0;
    position: absolute;
    top: 0;
    left: 0;
    -webkit-transition: opacity 2s linear;
    -moz-transition: opacity 2s linear;
    -o-transition: opacity 2s linear;
    transition: opacity 2s linear;
}

.showMe {
    opacity: 1;
}

Run the code Snippet and click on the image, the URL situated in img data-url="/ /" should be printed on the console. For some reason console doesn't print when clicking on the first img having class .showMe. /actors/al-pacinois somehow not printing. Because the .showMe is dynamically added and removed I used the .on() function of JQUERY but this doesn't work on the first image.
Answer: Since both images are absolutely positioned to the same place, the click event isn't being sent properly to the image that's visible.
Use the pointer-events style to prevent clicks from being sent to the hidden images.
I've also changed the addClass() and removeClass() functions to use the classList property rather than performing string operations on className.

var timer = setInterval(nextImage, 4000);
var curImage = 0;
var numImages = 2;

function nextImage() {
    var e;
    // remove showMe class from current image
    e = document.getElementById("slideimg" + curImage);
    removeClass(e, "showMe");

    // compute next image
    curImage++;
    if (curImage > numImages - 1) {
        curImage = 0;
    }

    // add showMe class to next image
    e = document.getElementById("slideimg" + curImage);
    addClass(e, "showMe");
}

function addClass(elem, name) {
    elem.classList.add(name);
}

function removeClass(elem, name) {
    elem.classList.remove(name);
}

$('#cf4a').on('click', '.slide', function () {
    let url = $(this).attr('data-url')
    console.log(url)
    //location.href = url (this is where the user should go when clicking on the image)

})
#cf4a {
    position: relative;
    width: 5em !important;
}

.container {
  width: 100vh;
  height: 60vh;
}

.slide {
    border: none;
    opacity: 0;
    position: absolute;
    top: 0;
    left: 0;
    -webkit-transition: opacity 2s linear;
    -moz-transition: opacity 2s linear;
    -o-transition: opacity 2s linear;
    transition: opacity 2s linear;
    pointer-events: none;
}

.showMe {
    opacity: 1;
    pointer-events: auto;
}


Criar arquivo de áudio, a partir de URL

Question: Preciso do arquivo de áudio do messenger, para usar na api Google Cloud Speech API. Quando um áudio é recebido no messenger, é gerada uma url que faz download de desse arquivo em .mp4. Como eu posso  a partir dessa url recuperar o áudio, e usar na API Google?
Comment: Em node ainda estou pesquisando, mas em Java tive que implementar em um projeto algo similar. Para simples tive que abrir apenas uma InputStream recebendo um Objeto URL e chamando o metodo openStream(),

`InputStream input = new URL("http://www.somewebsite.com/a.txt").openStream();`
Comment: Encontrei um blog com uma postagem interessante sobre:

[link]https://subvisual.co/blog/posts/39-tutorial-html-audio-capture-streaming-to-node-js-no-browser-extensions[link]
Answer: O truque aqui é pegar em streams, com o modulo http (ou equivalente) fazer download do ficheiro de audio e depois pipe para um stream, e aí fazer o que quiser.. Neste exemplo, guardar num ficheiro:
<code>var http = require('http');
var fs = require('fs');

var audioUrl = "http://www.exemplo/audio.mp4",
    fileName = "audio.mp4";

var file = fs.createWriteStream(fileName);
var request = http.get(audioUrl, function(response) {
  response.pipe(file);
});
</code>

Criar arquivo de áudio, a partir de URL