Recording an acoustic guitar with passive under-saddle pickup-system and having much noise

Question: I tried to recorde myself with my new guitar through the internal passive pickup, and got some serious noise issues. First, when I am recording plainly, the signal is very silent, and when I am applying Effects/Compressor in Audacity to make it louder it becomes very noisy.
I tried an identical setup with my bass guitar, and with it the noise was much lower, so it must be an issue with the guitar.
What can I do to lower the noise? Are there some special thinks to pay attention to when using an passive pickup?
The guitar is an Journey OF660 with an "Proprietary under-bridge transducer pickup system", I am hoping the guitar is not broken as it would be very involved to claim warranty as I ordered it overseas. And according to some youtube videos (like this and some other reviews) the pickup system in general should work fine.
I append a picture of the preamp I am using, with the settings:
Comment: Is there a battery and volume controls built into the guitar or are you using an external preamp? If the answer to both of those questions is "no" then that's probably the cause. BTW that picture is not what I would normally call a preamp, it's an audio interface with a high impedance 1/4" input but often those inputs are not very good at what they are supposedly good at. Undersaddle piezo pickups generally need dedicated preamps.
Comment: Okay, thought this interface would be enough, for my mic it works wells. No my guitar has not any batterie or volume controls, just something to plug the cable in.
Comment: Quality of the piëzo aside: I hope you only use it as a _supplementary_ means for recording the guitar, and the mic input is occupied by a decent condenser mic that's the main channel for the guitar? For even the best piëzo recording won't sound as good one with a properly mic'd guitar (provided the room acoustics permit it).
Comment: Seems odd in the picture: Phantom power probably shouldn't be on for most transducer pickups. Is there a reason for that? Also, try setting the `mic/line : guitar` switch to `mic/line`. It's a slightly different signal strength, and sometimes that works better on acoustic pickups.

P.S. You can get great sound with an under saddle/piezo pickup; don't believe the hype. I know professionals who use them to record. Practicing is more important.
Comment: @dogoncouch: Yes, as I was also recording with my mic which is connected through XLR, and it needed Phantom power. According to the manual "[...] 48V phantom power supplied to the MIC IN jacks [...]", so the LINE IN should not receive any power, but suprisingly if I switch off the phantom power the noise lever for the pickup indeed reduces, strange or???
Answer: I don't know this instrument, but a passive transducer  "suitable for any PA system" is hard to believe. An under the sadle pickup is most likely a piezo pickup  (unless there's some technology inovation I'm not aware of, but the manufacturer web site does not mention any). If it is a piezo pickup it requires a very high impedance preamp input, not normally found in most "normal" equipments (mixers, etc.)
Without a very high impedance input results can vary a lot, depending on circumstances and requirements , from passable to very bad. A loss of low frequencies (thanks @leftaroundabout for correcting my mistake) will almost for sure happen. Noise is also very likely, as you will need to put your preamp gain very high to have a minimum of signal level, and that will bring up the noise level of most preamps (but the very high-end ones). Distortion by the preamp may also occur.
A good branded piezo preamp is (for some reason I fail to understand) quite expensive  (100 to 200 euros), but that would be the recommended solution if you can afford it.
As a cheaper alternative you can buy a Chinese piezo kit for guitars for less then 20€ and canibalize the preamp. It's not pretty and the sound quality will not be that good, anyway, but it will put the signal at an appropriate level and will help match the input impedance of the preamp in the mixer, allowing it to work to its best.
Edit:
 You'll need to adapt the input jack, but other than that it should work seamlessly. You can leave the preamp lying on the floor beside you or use putty to attach it to the back, or wrap the cable around the guitar strap, or some other solution that suits you as best as possible. As I said,  not pretty, but should work.
Comment: Thanks for the good answer, could you also please suggest some good branded piezo preamps? I guess you do not mean something like this: https://www.amazon.com/Pickup-Pre-Amp-Acoustic-Guitars-EQ-7545R/dp/B004P4PZHA I do not plan to cut something out of my guitar to install such a thing....
Comment: Spot on. However: plugging a piëzo into a preamp with insufficiently high impedance actually leads to a loss of _low_ frequencies, not high frequencies (because the piëzo has a capacitive impedance, not an inductive one like magnetic pickups).
Comment: Also: the US144mkii guitar input has an impedance of 1 MΩ. That's not _a lot_ for a piëzo preamp, but it should be enough for _acceptable_ result with a properly-working piëzo PU.
Comment: @StefanH, yup, by "cheap Chinese" I do exactly mean something like that. As I said,, it's a hack,  but one I've found that can turn a completely useless passive pickup into one that's at least usable for some purposes.
Comment: @RockinCowboy it's possible, however a "clean, exact reproduction" input as found on interfaces should have an essentially pure ohmic impedance, i.e. not make any difference between magnetic and piëzo PUs. Now, in reaility, Tascam may well deviate substantially from this ideal (for whatever cost/space/power related reasons), but if anything this would most likely have an additional _capacitive_ load, and that's actually more problematic for magnetic PUs (lowering the resonance frequency) than for piëzos (where it just reduces both signal and noise proportionally). ...
Comment: ... A piëzo would have more problem with an inductive load like a passive DI box, however inductive transducers are rather bulky and therefore unlikely to be used in a compact audio interface like the US144mkii.
Answer: Nice guitar!  I looked up the specs on the manufacturer's website and they suggest it is in fact a "passive" under saddle pickup which means the pickup does not have "active electronics" or a built in pre-amp and therefore would not  require a battery.  I don't believe the problem is in your guitar.
The undersaddle pickup in your guitar is most likely a piezo pickup which would be a high impedance pickup which basically means the signal will have a high resistance and need an extra boost in the chain to get enough volume.  Without a pre-amp the amplifier or mixer must supply this extra boost or compensate for the higher impedance in the circuitry.
The Tascam interface you pictured does have an input switchable to "guitar" - which is short for - high impedance input from a source such as an electric guitar or bass with passive magnetic pickups or an acoustic guitar with a passive pickup as yours seems to have.  This is accomplished on your interface with a switch that can switch the right input from "mic/line" to "guitar".
Theoretically an interface or mixer with a "guitar" level input or "Hi-Z" input should allow you to input the signal from your passive pickup with good results. Checking some on-line reviews of the Tascam you are using suggests that other users have experienced noise and electrical interference issues with that interface similar to what you have described.  So the issue may be in the Tascam itself.
The better results you have with your bass might reflect the difference between the way the signal is processed and output from a passive magnetic pickup (typical on most electric guitars and electric bass guitars)  which is quite different than from a passive Piezo pickup which your acoustic guitar likely has.
Your guitar connected to the right mixer and amplification system (PA or acoustic amp) may not require a standalone Piezo Pre-amp.  But you may benefit tremendously in most applications (particularly recording) by using what is known as a DI Box (which is abbreviation for Direct Injection or Direct Input) also referred to as simply a "Direct Box".  I recommend that you try one that is made specifically for acoustic guitars.
Besides acting as a pre-amp for your passive pickup - The most important thing a Direct Box will do is convert the unbalanced signal (subject to the noise you are experiencing) to a balanced signal that will cancel out or otherwise eliminate much of the electronic noise in the signal chain.  The output from the DI Box will plug into a balanced XLR input on your interface.
Since your guitar has a passive pickup you will most likely want to use an active Direct Box made specifically for acoustic guitars.  See picture below of one example. An active DI (a/k/a Direct Box) will act as a pre-amp for your passive pickup as well as balance the signal from the guitar pickup so that noise is eliminated. Most will also give you other controls such as volume and EQ.
A pre-amp alone would boost the input signal and give you more volume, but would not solve the noise issues resulting from the unbalanced signal (and might even amplify them).  What you need is an active direct box which will act as a pre-amp but will also create a balanced signal between pickup and recording interface so that the noise should be abated dramatically if not eliminated altogether.

Pictured above is the LR Baggs Para Acoustic DI  Also check out the LR Baggs Venue
The Radial PZ DI box pictured below is advertised as being optimized for piezo input.

Another acoustic DI with good reviews is the Fishman Aura Spectrum DI.
Good luck with your music and enjoy that fine guitar!
Comment: Good, practical answer. The Para-Acoustic DI is definitely a great tool for getting acoustic instruments live to the PA; it has long been my preamp of choice. But José David is quite right that it's a bit ridiculous to spend hundreds of $$ on piëzo preamps, since all that would be needed to drive any old low-Z mic input (with 48V phantom) is a single, good-quality jFET transistor. I wish all the PU manufacturers built one (for, like, 3€) into their products. Unfortunately, these brands all make their own seperate preamps, which are probably just too good a source of revenue.


Emails are not sent to outside domains

Question: I deployed a Drupal 8 website, on a hosting service with cPanel, with domain mydomain.com.
If I set this email address on the user profile: email@example.com, that is an email address with a domain different from mydomain.com, then I go to:
mydomain.com/user/password

and I click to "Send" trying to receive the "reset password" email, it give me the error below and I don't receive the email:

Unable to send e-mail. Contact the site administrator if the problem
  persists.

Same problem on contact forms.
If I set an email address within my domain, for example firstname.lastname@example.com, all works and the email is correctly sent.
Any idea why this is happening and how to solve this problem?

NOTE
I tried to create this php script inside the server in order to check if there is some issue on the server configuration:
<?php

$to = "firstname.lastname@example.com";
$subject = "Test mail";
$message = "This is a test message.";

$headers = [];

$headers[] = "From: email@example.com";
$headers[] = "MIME-Version: 1.0";
$headers[] = "Content-type: text/plain; charset=UTF-8; format=flowed; delsp=yes";
$headers[] = "Content-Transfer-Encoding: 8Bit";
$headers[] = "X-Mailer: Drupal";
$headers[] = "Reply-To: firstname.lastname@example.com";

$res = mail($to, $subject, $message, implode("\n", $headers));

echo "Mail Sent.
\n";
echo "Res: " . $res . "
\n";

When I run this script it correctly works and sends the email, either if the $to property is from my domain or if it is from an external domain.
So I excluded it is a server configuration issue.
Answer: I solved the problem.
Taking inspiration from this thread, I figured out that, for some obscure reason, I need to set the email setting under "Administration > Configuration > System > Basic site settings > E-mail address" to an existing email address on my hosting service.
So, I created a new email with cPanel, firstname.lastname@example.com, then I setted this email address in the above configuration.
Now seems that all is working perfectly.

Emails are not sent to outside domains


Proof by induction that $x_{n} + by_{n} = a$

Question: I have an algorithm where a and b $\in$ Z+
MUL(a,b)
   x = a
   y = 0
WHILE x >= b DO
   x = x-b
   y = y+1
IF x = 0 THEN
   RETURN(y)
ELSE
   RETURN(-1)

I need to prove by induction that
$x_{n} + by_{n} = a$
is true if $x_{n}$ and $y_{n}$ are the values for x and y after n runs of the WHILE-loop.
My approach is to to prove that its true for the basecase where the WHILE-loop runs 0 times.
When the WHILE-loop runs 0 times (n = 0), we know that y = 0 since y is counting the amount of times the WHILE-loop is ran.
So we have:
\begin{equation}
\begin{split}
    x_{0} + by_{n} =& a \\
    x_{0} + b*0 =& a \\
    x_{0} =& a \\
\end{split}
\end{equation}
If we input $a = 1$ og $b = 2$ into $MUL()$. The result will be be $y = 0$ and $x = 1 = a$.
I'm not sure if this basecase step is correct and I am not sure how to proceed from here. I know I need to prove if it's true for n + 1. But how I do it I don't know. I hope somebody can help me!
Answer: Strictly speaking, we do not know anything like "$y$ is counting the amount of times the WHILE loop is run" beforehand; however, this (i.e., $y_n=n$) may be a corollary of an analysis of the code.
After $0$ loops, i.e., immediately before entering the while loop, only x = a and y = 0 are executed, hence indeed $x_0=a$ and $y_0=0$. Thus
$$\tag1 x_n+by_n=a\qquad\text{and}\qquad y_n=n$$
holds for the base case $n=0$
Assume $x_n+by_n=a$ and $y_n=n$ after $n$ loops. Then in the next loop, the statements x = x - b and y = y + 1 are executed. It follows that $x_{n+1}=x_n-b$ and $y_{n+1}=y_n+1$. Therefore, using the induction hypothesis,
$$x_{n+1}+by_{n+1}=x_n-b+b(y_n+1)=x_n+by_n=a $$
and
$$y_{n+1}=x_n+1=n+1,$$
i.e., $(1)$ with $n\leftarrow n+1$. Therefore we have shows that $(1)$ holds for all $n\in\Bbb N_0$.

Once this is shown, we see from $(1)$ that
$$x_n=a-by_n=a-bn. $$
So for $n$ large enough, $x_n\ge b$ will not hold, and the WHILE loop will terminate.
Let $n$ be minimal with $x_n<b$. Then the return value of MUL will be $y_n$ if $x_n=0$, and $-1$ otherwise. As $x_n=0$ implies $by_n=a$, we conclude that for $a,b\in \Bbb Z^+$,
$$\text{MUL}(a,b)=\begin{cases}\frac ab&\text{if }b\text{ divides }a\\-1&\text{otherwise}\end{cases} $$
Comment: Thanks, Hagen von Eitzen. Very intuitive in the way you present it. Thanks a bunch! <3


How to use my own GObject instace with C++ programs

Question: i would like to know how i can use my own created GObject objects with my c++ code.
I have a simple libary compiled in C that define a GObject object, i would like to use this object defined there in my c++ code.
I have seen some example here
http://developer.gnome.org/gtkmm-tutorial/3.0/sec-basics-gobj-and-wrap.html.en, where the documentation teaches how to get a Gobject object instace from a C GTK+ API function.
I would like to do the same but using the object created from my libary.
Thanks.
Answer: You can always extend their GObject class and use that as a wrapper but the thing is that the GTK+ library uses the GObject internally I don't know why you would want to replace it (and it might complain that you've redefined a symbol somewhere or won't let you call any methods using your custom object as a parameter as the types won't match if you do extend it).
If you want to use it as a wrapper you should extend GObject and write a constructor that takes the GObject (and any other things that you need) and simply wrap the GObject into your custom class every time it's required.


A problem about elliptic functions

Question: I am trying to solve some problems in complex analysis, but I am not succeeding in the following problem. Suppose that $f$ is a function with the following properties:

$f$ is non-constant;
$f$ is meromorphic on $\mathbb{C}$;
$f(z)=f(z+\sqrt{2})=f(z+i\sqrt{2})$ for $z\not\in P$, where $P$ is the set of poles of $f$;
$f$ has at most one pole in $\{z\in\mathbb{C}:|z|\leq 1\}$.

Then $f$ has exactly one non-simple pole in $\{z\in\mathbb{C}:|z|\leq 1\}$.
I guess I can solve it if I change two things:

the subset where $f$ has at most one pole, I assume that $f$ has at most one pole in $P_0:=\{z\in\mathbb{C}:z=a+b\tau$, $0\leq a<1$ and $0\leq b<1\}$, the fundamental parallelogram, where $\tau:=\frac{\sqrt{2}i}{\sqrt{2}}=i$;
the periodic condition is valid for all $z\in\mathbb{C}$.

In this case, all the data about $f$ is in $P_0$. Hence, if $f$ does not have poles in $P_0$, then $f$ is analytic in $P_0$ (I'm not sure about this), implying that $f$ is constant, contradiction. Thus, $f$ has exactly one pole. Finally, since the total number of poles of an elliptic function in $P_0$ is always $\geq 2$, we have that the pole is not simple.
So, my question is how to solve this problem without the changing in the assumptions, or how to prove that my assumptions are equivalent to the original hypotheses of the problem.
Thank you!
Comment: I'm not sure I believe this: what's stopping the Weierstrass elliptic function $\wp(z)$ with periods $\sqrt{2}$ and $i\sqrt{2}$ satisfying the conditions while not having a non-simple pole at $0$? Either way, it's worth asking why this is not a counterexample.
Comment: Sorry! I typed wrong. Now I believe that is correct.
Answer:
Denote the only pole inside $|z|\leq 1$ by $a$ and show that it is also the only pole inside $|z-a|\leq 1$.
Consider the square $C$ with vertices $a\pm\frac{\sqrt2}{2}$, $a\pm\frac{i\sqrt2}{2}$ inscribed inside the circle $|z-a|\leq 1$, and oriented counterclockwise.
Integrate $f$ along $C$: if the pole is simple, the result should be non-zero by residue theorem. However, this contradicts the periodicity properties of $f$.

Remark: The case with no pole inside $|z|\leq 1$ is trivial (use a similar square and periodicity to show that $f$ is then analytic in the entire complex plane, hence constant).

A problem about elliptic functions


$1^n +2^n + \cdots +(p-1)^n \mod p =$?

Question: Calculate for every positive integer $n$ and for every prime $p$ the expression
$$1^n +2^n + \cdots +(p-1)^n \mod p$$

I need your help for this. I don't know what to do, but I'll show you what I know.

Wilson's theorem
The identity $X^p-X = \prod_{a \in \mathbb{F}_p-1}(X-a)$
$\exists a \in \mathbb{Z}, \ a^2 \equiv -1 \mod p \qquad \iff \qquad p \equiv 1 \mod 4$

Now can you please provide me a hint?
Comment: Can you use a primitive root, that is, a generator of the multiplicative group?
Comment: Hint: Do the case $n\equiv 0 \pmod{p-1}$ separately from the rest.
Comment: Beyond what was already said, please note that there's a mistake in the expression found for $f(1,p)$.
Comment: @KoenvanDuin: $kp\equiv0\pmod p$ for every integer $k$. Especially for $k=\frac12(p-3)$.
Comment: I did the case $n \in (p-1) \mathbb{Z}$ seperate from the rest using André's hint, and obtained that the expressions equals $p-1$ in that case, but I don't see how I could use this. COuld you tell me a little more?
Comment: That is the result of the sum for that value of $n$.  The full result is a piece wise function of $n$, and I think you have all the pieces listed here.
Comment: Related ; http://math.stackexchange.com/questions/197469/value-of-sum-i-1p-ik-pmodp
Answer: Hint: If $a^n \equiv 1 \pmod{p}$ for all $1 \leq a \leq p-1$ you know what the sum is.
Otherwise, if $a^n \neq 1 \pmod{p}$ for some $a$, then use the fact that $\{ a, 2a, 3a, .., (p-1)a \} = \{1,2,3,.., p-1\} \pmod{p}$. Thus
$$ 1^n +2^n + \cdots +(p-1)^n =a^n +(2a)^n + \cdots +[(p-1)a]^n \\
 = a^n \left( 1^n +2^n + \cdots +(p-1)^n  \right)  \pmod{p}$$
You also need to figure out for which $n$ you have $a^n \equiv 1 \pmod{p}$ for all $1 \leq a \leq p-1$...
Comment: @abiessu Things are a little more complicated in the even case, the odd case is pretty simple, and your answer is the best approach in that case. Now, in general $a^n \equiv 1 \pmod{p}$ for all $a$ implies $n$ is divisible by $p-1$ (hence Calvin's hint). Thus it follows immediately that for all $n$ excepting multiple of $p-1$ the sum has to be zero. And, UNLESS $p=2$, $p-1|n$ implies $n$ even, which is why this proof doesn't contradict your proof, again UNLESS $p=2$, in which case your proof is wrong ;)
Comment: Hmm... your answer appears to be correct in ways that makes my answer incorrect.  I'm having trouble figuring out why my answer is wrong...  Or is it perhaps that my answer simply fails for those $n$ when $a^n\equiv 1$(mod $p$)?
Comment: Just verifying, did you mean $\{ a, 2a, 3a, .., (p-1)a \} = \{1,2,3,.., p-1\} \pmod{p}$?  If the sum only goes up to $(p-a)$ then I think you have some congruence classes missing...
Answer: From Fermat's little theorem, $x^{p-1}-1=0 \mod p$. From Vieta, this means that all the elementary symmetric polynomials in the x's of order less than p-1 must equal zero mod p. Thus any symmetric polynomial in the x's of order less tha p-1 must equal zero mod p. Is it really that simple, or am I missing something?
Comment: You are using the fact that every symmetric pol can be expressed as a polynomial in elementary pols, but what if this polynomial had non-zero constant term?
Comment: I suspect that proving the constant term of that polynomial is zero mod $p$ is equivalent to the original problem, that would make this answer a circular argument.
Answer: Hint:
Consider the reordered sum:
$$1^n+(p-1)^n+2^n+(p-2)^n+...+\left({p-1\over2}\right)^n+\left({p+1\over2}\right)^n$$
For $p=2$, the sum resolves to $1^n$.  To see other values it would take on, assume $p\gt 2$.
If $n=1$, then the sum is the well-known binomial $\binom{p-1}2={(p-1)(p-2)\over 2}\equiv 1\mod p$.  This should be a good start for induction or direct proof for odd $n$.  Can you analyze the sum further and complete it for even $n$?
Answer: I don't see the simple answer plainly stated so I will state it here. For $p=2$, the only term in the sum is $1^n$ which is identified in a previous answer as $\equiv 1 \bmod 2$, but for consistency with the larger scheme of things, might better be stated as $\equiv -1 \bmod 2$
For odd $p$ and odd $n$, there are an even number (i.e., $p-1$) of addends, and the sum may be arranged as $1^n+(-1)^n+2^n+(-2)^n+\dots \equiv 0 \bmod p$
If $n$ is even, and if $(p-1)\mid n$, then every addend is a $(p-1)$ power of an integer, so every addend is $\equiv 1 \bmod p$ and the $(p-1)$ addends sum to $(p-1)\equiv -1 \bmod p$
If $n$ is even, and $p\equiv 1 \bmod 4$, and if $(p-1)\not \mid n$, then since quadratic residues in this case come in pairs $a, (p-a)$, the sum is $\equiv 0 \mod p$
If $n$ is even, and $p\equiv 3 \bmod 4$, and if $(p-1)\not \mid n$, I am without a proof, but empirically for several small primes, the sum is $\equiv 0 \mod p$
Overall, if $(p-1)\mid n$, the sum $\equiv -1 \bmod p$; otherwise, the sum $\equiv 0 \bmod p$
Answer: Take the group $G=(\mathbb{Z}_{p},\cdot)$ with the multiplication.
Since $p$ is prime then the order of $G$ is $p-1$.
Then  using $n=k(p-1)$ and $p-1=-1 \pmod p$.
$1^n +2^n +...+(p-1)^n=1+1+...+1=p-1=-1 \pmod p$
Comment: This answer isn't correct.

$1^n +2^n + \cdots +(p-1)^n \mod p =$?


Implement timeout for function/block

Question: I would like to do sth like this pseudo-code:
try for new Timespan(0,0,4) {
    // maximum execution time of this block: 4 seconds
    result = longRunningFunction(parameter);
    doSthWithResult(result);
    ...
} catch(TimeOutException) {
    Console.WriteLine("TimeOut occured");
}

Is such a construct available in C#, and if not, how would I implement a behaviour that allows trying to execute a function/block for a certain amount of time?
If that helps: I am searching for ASP.NET WebAPI (although I could use the timeout in a WinForms App as well).
Comment: Depends upon what that `longRunningFunction` does. You need to support cancellation in that method.
Comment: @Thomas Yes you're right. There is no guarantee that cancellation will be responded immediately. So, yes you can't say it must time out strictly in given time. Or  something like `Task.WhenAny` could be useful ignoring the `longRunningFunction` after timed out. Another evil and unreliable option is `Thread.Abort`, I don't recommend it but you can(won't work always).
Comment: At least with winforms you would have a problem if you want to make sure that it does only execute for that span. The problem is you need multiple threads and even if you tell a child-thread to shutdown (kill the thread) there is no guarantee that the thread does stop until the application itself stops (it gets worse if its a background thread as that one can survive the end of the application). ASP.NET I don't know if it has a similar problem or not. Winforms sadly has that problem
Comment: http://stackoverflow.com/questions/4238345/asynchronously-wait-for-taskt-to-complete-with-timeout
Comment: @SriramSakthivel even if he has support for it problem is that if he needs to make sure taht it stops at exactly that time....then its not possible in winforms as there is no guarantee that it really stops at that millisecond (it stops only when the cancellation token is checked which can be at that millisecond or seconds later or never depending on the implementation, luck and possible errors). so the mainquestion is: is it necessary that the timeout is a hard timeout or is it more meant "stop beginning here" Alexander ?
Comment: I have been there and I have to say even when it works it has the same problem that it is no guarantee taht it can cancel on exactly that millisceond sadly. So @Alexander how hard is the timeout? Does the longrunningfunction need to stop right away at that millisecond (if so then sadly no way I know of that it is possible in winforms) or is it a soft timeout so that it can stop after a while later (be it a few milliseconds or seconds depending on when the cancel-token is reached)?
Comment: It's more or less telling the function: "I won't wait for you any longer, and because you are not yet finished, I will proceed in a 'catch block'".
Comment: Ah ok so a soft timeout in essence. That is possible in winforms (quite easy even). ASP.NET I sadly dont know if possible/how best possible. Is it then necessary to tell the subfunction that it can abort/cancel at all (currently thinking already of how to do the winforms code example)?
Answer: If you want the longRunningFunction() itself to stop, then you need to implement logic in that method to do so. How to do that depends on the exact implementation of the method, which you haven't provided, so that would be unanswerable given your current question.
However, in many cases it's sufficient to simply abandon an operation, letting it run to completion on its own but simply ignoring the result. You might call that "getting on with your life". :)
If that's the case here, then something like this should work for you:
Task<T> resultTask = Task.Run(() => longRunningFunction(parameter));

// maximum execution time of this block: 4 seconds
await Task.WhenAny(resultTask, Task.Delay(4000));

if (resultTask.IsCompleted)
{
    doSthWithResult(resultTask.Result);
}
else
{
    Console.WriteLine("TimeOut occurred");
}

Replace T in the resultTask declaration with whatever the actual return type for longRunningFunction() is.
Note that the above is opportunistic, in that even if the long-running operation takes longer than 4 seconds and the Task.Delay(4000) wins the race, as long as it completes by the time your code gets back to the if (resultTask.IsCompleted check, it will still be considered a success. If you want to give it a strict cut-off, ignoring the result if the Task.Delay(4000) completes first even if the operation finishes by the time you actually check which finished first, you can do that by looking at which task finished first:
Task winner = await Task.WhenAny(resultTask, Task.Delay(4000));

if (resultTask == winner)
{
    doSthWithResult(resultTask.Result);
}
else
...

Finally: even if you do need the longRunningFunction() to stop, you can use the above technique and then interrupt the operation in the else clause where you report the time-out (via whatever mechanism is appropriate in your case…again, without the actual code it's not possible to say exactly what that would be).

Implement timeout for function/block


Displaying user related content

Question: Im trying to figure out what contextual filters to use but im getting no where, im trying to display content related to that user through an attachment on a page listing all users. So for example if I had user 1 it would display content from user 1 and if the user is user 2 and the attachment would display the content under user 2 and so on.
In the image below, I have the filters and relationships I am using on my attachment. on the page itself I have no contextual filters or relationships on it. I think that is fine since I am displaying just the users themselves, however I could be wrong.
as you can see I have no contextual filters added on to the attachment because I am not sure which one is the correct one, I have tried different combinations with User: Uid and Content: Author Uid but have had no luck.
Any help is appreciated.
Comment: Is the end goal a listing of all nodes the current author is also an author of?
Comment: yes, I was able to partially do this but with aggregation but the fields using the nodes were only showing 1 node instead of all the nodes
Answer: You're over-complicating this with the extra relationships.
Drop everything under relationships and make sure your drop your relationship references on your fields as well.
Then just add a contextual filter for Content:Author uid and you should be all set as long as that uid is correctly getting passed to the attachment. You will want to end up with something that looks more like the attached screenshot.
Comment: it has to have a relationship to get the node fields, if not then it is only listing user fields and no node fields.
Comment: Why start with a user view if the content is what you want?
Comment: because as mentioned above, i would like to display the user info, I have additional user fields that are in the layout, please take a look at the image attached to see what im trying to achieve http://i.imgur.com/wWCdP.jpg
Comment: Starting with a user view or a node one there shouldn't be any need to have both relationships. I would start with a node view because those are a lot more flexible then attach the two user fields as your attachment, then you'll only need a single 'Content:Author' relationship.
Comment: I found it, i will be posting the answer shortly
Answer: I was able to achieve what I wanted in views by creating a user type view adding the relationship User: Content authored and going under Format and settings and grouping the fields that I wanted to display, I then went back to those fields under "Fields" and excluded them from displaying so it does not show duplicate fields on the page. No attachment was needed.

Displaying user related content


Open Source Crawler

Question: I came across an open source crawler that recently hit my site.  I was wondering, 1.  How do you get a list of sites to crawl?  2.  Can you get a list of sites to crawl in your city?  3.  If you have all this information, where is this readily available from and what APIs are there to access this information?
Thanks,
Walter
Comment: Belongs on StackOverflow. But to be helpful, you need to seed your crawler with links and then let it explore. If you wanted to explore sites from your city, you'd need to start with a say, "Boston" portal type site and go from there. There's no real master list or API for it, it's clever programming and focus upon target sites.
Comment: Ok, I should ask it there instead.  I thought all companies have to register and that information was a public record.  I already have a simple crawler, need to give it some starting information though.
Answer: To start crawling, normally you hand the crawler an address, and let it run.
If you want to look only for "local" results, you may need to get clever with your spawning of the crawling process, and seed it with known URLs of local companies, which you might need to find the old-fashioned way: eg using a phonebook :)
Comment: Ok, I was hoping there was some all knowing source, but then again if there why, what would I need this for?  Yeah, the crawler works fine for my internal site finding everything in there, but the problem is just giving it the initial address(es) to start from.
Answer: I was hoping for more ideas as to what other information is out there for me to reference and then do intelligent things with.  I have a rough idea of what is, of course, I can always use Hacking Exposed to find other sources that I originally hadn't thought of.
Answer: To find local websites you can use those websites that do use Geo Coordinates as your starting points.
And then while indexing sites without geo coordinates you have to check them for referencing certain address relevant strings (as in the area zip/postal code and the citys name).
You can use this geourl websites index to automate the process by using certain long/lat values as a parameter like i did for fresno here:
http://geourl.org/near?lat=36.78&long=-119.79

Open Source Crawler


Animated Childrens Book App (iOS & Android)

Question: I have a project where client wants to create children story book apps for both iOS & Android platform. They want something similar to these two apps:
https://itunes.apple.com/us/app/marie-de-paris/id586520420?ls=1&mt=8
https://itunes.apple.com/md/app/hello-i-am-charlie-from-london/id566826418?mt=8
There will be simple animation & sound effects in the app.
My question is what would be the best way to accomplish this? Are there any animation frameworks best suited for animated ebooks?
I'm familiar with native programming for both iOS & Android and I'm also open to Hybrid Development (HTML5).
Any suggestions?
Answer: If its simple animation you can use default or customized android animations. if the animations are complex, you may go ahead and use some opensource android framework engine like AND3D etc..


How to configure dependency injection in angularjs?

Question: I'm a little bit confused about how angularjs application works.
First of all I should say I'm a newbie angularjs user but I'm familiar with other DI frameworks in other languages (like symfony in PHP, spring in Java, a bit Unity).
Each of these DI implementations requires class definitions and DI configuration.
Configuration usually includes:

how should be class injected (automatically by name or type, or manually)
if container should return a singleton instance
what factory class should be used for creating object
serviceIds - each service can be retrieved by serviceId. This serviceId says configuration of creating instance (what services should be injected and what params should be used).
etc.

And this configuration I'm missing in angularjs.
There is an dumb example how I expect such a configuration should work. I have two services, each does similar thing but with different implementation.
<code>angular.module('notify', [], function($provide) {
    $provide.factory('LogNotifier', function($window) {
        return {
            messageMe: function(message) {
                $window.console.log(message);
            }
        }

    });
    $provide.factory('AlertNotifier', function($window) {
        return {
            messageMe: function(message) {
                $window.alert(message);
            }
        }
    });
});

angular.module('myModule', ['notify'], function($provide) {
  // as notifier dependency I must specify its type.
  // is there any way how I would configure after its definition
  // which notifier implementation should be used?
  $provide.factory('DataLoader', function(AlertNotifier) {
      var loader = {
          loadAllItems: function() {
              AlertNotifier.messageMe('Loading items');
              // let's asume there is ajax call and promise object return
              return [
                    {name: 'Item1'},
                    {name: 'Item2'}
                ];
          }
      }
      return loader;
  });
});
</code>
See http://jsfiddle.net/5ZDe6/1/
I would like to switch between LogNotifier and AlertNotifier without changing source code of DataLoader service. Is that possible?
Thank you
Answer: After a week fiddling with angularjs I realized one very important thing. All angularjs examples actually include the DI configuration I looked for. The configuration is actually a module definition itself.
All I had to do was to separate module definition from class definitions.
Here is solved fiddle of my question - http://jsfiddle.net/5ZDe6/7/
<code>/**
* app module configuration
*/
angular.module('app', ['debug'], function($provide) {
    var dataLoaderFactory = function(Notifier) {
        return new my.model.DataLoader(Notifier);
    }
    // if you want to change notifier just change this injection to AlertNotifier
    dataLoaderFactory.$inject = ['LogNotifier'];
    // Specify factory with service ID DataLoader for class my.model.DataLoader
    $provide.factory('DataLoader', dataLoaderFactory);
})
.controller('AppCtrl', my.controller.ItemCtrl); // you can even specify AppCtrl implementation (e.g. CachedCtrl)
my.controller.ItemCtrl.$inject = ['$scope','DataLoader']
my.controller.CachedCtrl.$inject = ['$scope']

/**
* debug module configuration
*/
angular.module('debug', [], function($provide) {
    $provide.factory('LogNotifier', function($window) {
       return new my.debug.LogNotifier($window);
    });
    $provide.factory('AlertNotifier', function($window) {
       return new my.debug.AlertNotifier($window);
    });
});
</code>
And there are class definitions separated from DI configuration.
<code>/**
* Controller class definition
*/
my = window.my || {};
my.controller = my.controller || {};
my.controller.ItemCtrl = function($scope, loader) {
    $scope.items = loader.loadAllItems();
};

my.controller.CachedCtrl = function($scope) {
    $scope.items = [
        { name: 'Cached ctrl value 1'},
        { name: 'Cached ctrl value 2'}
    ]
}

/**
* Model class definition
*/
my.model = my.model || {};
my.model.DataLoader = function(notifier) {
    this.notifier = notifier;
    this.loadAllItems = function() {
        this.notifier.messageMe('Loading items');
        // let's asume there is ajax call and promise object return
        return [
            {name: 'Item1'},
            {name: 'Item2'}
        ];
    };
};

/**
* Some debug classes definition
*/
my.debug = my.debug || {}
my.debug.LogNotifier = function($window) {
    this.$window = $window;
    this.messageMe = function(message) {
        this.$window.console.log(message);
    }
};
my.debug.AlertNotifier = function($window) {
    this.$window = $window;
    this.messageMe = function(message) {
        this.$window.alert(message);
    }
}
</code>
I suppose that is the cleanest way how to achieve my requirements. Unfortunately if you really want to do this way you have to write a bit more code.
Frank
Comment: I wonder how to bring AngularJS's elegant DI to PHP DIs. Currently PHP DIs seem too much like service containers.


Munkres topology Exercise 26.10

Question:
Let $f_n:X\to\Bbb R$ be a sequence of continuous functions with $f_n(x)\to f(x)$ for each $x\in X$. If $f$ is continuous and if the sequence $f_n$ is monotone increasing and if $X$ is compact, then the convergence is uniform.

Proof. For each $x\in X$, by the continuity of $f_n$, there is $U_x$ such that for any $y\in U_x$, $|f_n(x)-f_n(y)|<\epsilon/3$. Also by the continuity of $f$, there is $V_x$ such that for any $y\in V_x$, $|f(y)-f(x)|<\epsilon/3$. Let $W_x:=U_x\cap V_x$ which is nonempty open set as $x\in W_x$. Then $\{W_x\}_{x\in X}$ is an open covering of $X$ so by compactness, there is a finite subcover $\{W_{x_1},...,W_{x_n}\}$. Note that for each $x\in X$, there is a number $N_x$ such that $n\geq N_x$ implies $|f_n(x)-f(x)|<\epsilon/3$. So define $N = \max\{N_{x_1},...,N_{x_n}\}$.
Now let $y\in X$ be given. Then there is $i$ such that $y\in W_{x_i}$. For $n\geq N$,
$$|f_n(y)-f(y)|\leq |f_n(y)-f_n(x_i)|+|f_n(x_i)-f(x_i)|+|f(x_i)-f(y)|<\epsilon.$$
I think I didn't use monotone increasing condition. I can't find the error. Could you help?
Answer: The error lies in your first sentence. That set $U_x$ depends not only on $x$ but on $n$ too.
Comment: @love_sodam maybe a totally different approach? Have you done a search on this site? It's an old problem….
Comment: Thanks. But it seems monotonicity does not fix that problem directly.
Comment: JSC means, these sets $U_x$ are not the sets that you should be concerned with covering $X$ with. Perhaps consider that for a fixed $\epsilon \in (0, \infty)$ the fact that $\lim_{n \to \infty} f_n(x)=f(x)$ guarantees that the sets $\{x: |f_n(x)-f(x)|<\epsilon\}$  ($n=1,2,\ldots$) cover $X$.
Comment: @HennoBrandsma Yeah I know this is an old problem. I just wonder why the above proof is wrong. Also I wanted to conclude the statement that frequently appears in analysis proofs $|-|\leq |-|+|-|+|-|<3\cdot\frac{\epsilon}{3} = \epsilon$ which failed eventually though.
Comment: @love_sodam See [here](https://math.stackexchange.com/q/2912999/4280) for a better proof. The linked question in it is also relevant, as it gives examples where this fails if we drop assumptions.

Munkres topology Exercise 26.10


Use webpack to bundling node_modules and running code in multiple entry points?

Question: I'm running a system which runs node on a server but it does not allow me to deploy node_modules
In order to work with dependencies, I see the only solution to bundle them inside a vendors.js file.
Furthermore, the system only allows for es5 javascript so the javascript needs to be transpiled and polyfilled.
The current setup I have today looks something like this:
webpack.config.js:
const path = require("path");
const { promisify } = require("util");
const glob = promisify(require("glob"));

const babelconfig = require("./.babelrc");

const generateEntries = async () => {
  return (
    await glob("./src/**/*(*.ts|*.mjs)", {
      ignore: "./src/**/*.d.ts"
    })
  ).reduce((acc, item) => {
    const chunkName = path.basename(item, path.extname(item));
    acc[chunkName] = item;
    return acc;
  }, {});
};

module.exports = async () => {
  return {
    target: "node",
    entry: await generateEntries(),
    mode: "production",
    resolve: {
      extensions: [".ts", ".js", ".mjs"]
    },
    externals: /(\*|server)/i,
    optimization: {
      minimize: false,
      runtimeChunk: {
        name: "vendor"
      },
      splitChunks: {
        cacheGroups: {
          commons: {
            chunks: "initial",
            minChunks: 2,
            maxInitialRequests: 5,
            minSize: 0
          },
          vendor: {
            test: /node_modules/,
            chunks: "all",
            name: "vendor",
            priority: 10,
            enforce: true
          }
        }
      }
    },
    output: {
      path: path.join(__dirname, "/lib"),
      filename: "[name].js"
    },
    module: {
      rules: [
        {
          test: /(m?\.js|\.ts)/,
          loader: "babel-loader",
          options: babelconfig
        }
      ]
    }
  };
};

.babelrc.js
module.exports = {
    presets: [
        [
            "@babel/typescript",
            {
                debug: true,
            },
        ],
        [
            "@babel/env",
            {
                useBuiltIns: "entry",
                targets: {
                    ie: "9",
                },
                corejs: "3",
                debug: true,
            },
        ],
    ],
    plugins: [
        "add-module-exports",
        "@babel/proposal-class-properties",
        "@babel/proposal-object-rest-spread",
        [
            "@babel/plugin-transform-runtime",
            {
                regenerator: true,
            },
        ],
    ],
}

The transpilation/compilation works fine, however when i try to run the actual code, the compiled methods do not seem to execute:
When taking a very simple typescript file with the following source:
test.ts
console.log("Hello World");

The tranpiled version looks like this:
exports.ids = [2];
exports.modules = {

/***/ 8:
/***/ (function(module, exports) {

console.log("Hello World");

/***/ })

};;

Which of-course doesn't output anything since its wrapped in exports.modules
What am I doing wrong here?
Running the file (test.ts) directly with babel-cli produces the following file:
"use strict";

console.log("Hello World");

Which works perfectly
Answer: Solved it using rollup rather than webpack with the following config:
const extensions = [".mjs", ".ts", ".js"]
const bundle = await rollup.rollup({
    input: (
        await glob(`${options.outDir}/${cartage}/${TARGET_FILES}`, {
            ignore: `${options.outDir}/${cartage}/**/*.d.ts`,
        })
    ).reduce((acc, file) => {
        const pathName = file.substring(options.outDir.length + 1)
        const entryName = path.basename(pathName, path.extname(pathName))

        acc[
            `${(pathName.indexOf("/") !== -1 &&
                `${path.dirname(pathName)}/`) ||
                ""}${entryName}`
        ] = file
        return acc
    }, {}),
    external: id => id == "server" || /^\*/.test(id),
    plugins: [
        resolve({ extensions }),
        babel({
            extensions,
            runtimeHelpers: true,
        }),
        commonjs({ extensions }),
        strip({
            labels: ["outer"],
        }),
    ],
})

const outputOptions = {
    dir: CARTAGE_TRANSPILE_DIR,
    format: "cjs",
    sourcemap: true,
    chunkFileNames: `${cartage}/[name]-[hash].js`,
}

await bundle.write(outputOptions)


Mean Value Theorem Proofing For all $ x>0$

Question: By applying the Mean Value Theorem to the function $f(t)=e^t$ defined on the interval $[0, x]$, where $x > 0$, show that for all $x > 0$, $e^x>1+x$.
What I have done...
$f(t) = e^t$
$f$ is continuous on $[0,x]$ and differentiable on $(0,x)$.
For at least one $C$ in domain $(0,x)$ such that
$(f(b)-f(a))/(b-a) = f'(C)$
$(e^0 - e^x)/(-x) = e^c$
$1-e^x = -xe^c$
How do I continue the proof from here?
Comment: What I have done...

f(t) = e^t
f is continuous on [0,x] and differentiable on (0,x)

For at least one C in domain (0,x) such that
(f(b)-f(a))/(b-a) = f'(C)

(e^0 - e^x)/(-x) = e^c

1-e^x = -xe^c

How do i continue proofing from there?
Comment: Then what have you done?
Comment: What do you get when you simply apply the mean value theorem? Also do you 'know' that $e^x$ is an increasing function also? Because those two facts give what you want straightaway
Comment: @user222180 Welcome to stackexchange!
Answer: By the mean value theorem, we have $c\in[0,x]$ such that
$f(x)-f(0)=f'(c)(x-0)$
That is, $e^x-1=e^cx$
Since $e^x$ is increasing and $c>0$ then $e^c>e^0=1$
Thus $e^x-1=e^cx>x$ and thus $e^x>1+x$
Answer: Hint: f'(c) is greater than 1, c in (0,x).


Possible Solution for Setting up a Linux VPN Server to Encrypt WLAN Traffic of Macs and iPhones on

Question: I would like to set up a VPN server on debian linux to encrypt wireless traffic coming from my Mac or iOS device. I would like to use a certificate-based solution. Setting up a PKI infrastructure and managing certificates is OK for me.
1. Which server to pick?
By looking through the internet and here on stackoverflow I found the following possible solutions:

strongSwan
IPSec and racoon

Which solution is feasible for a linode running debian squeeze?
2. How to configure the network?
If I understood correctly a VPN has a virtual network interface as an endpoint on the server side. Naively I would think that I need a DHCP server running on the server to assign a dynamic private IP (like of the class C network 192.168.xxx.xxx) to the connecting clients. Next I think I would need to set up masquerading to NAT the incoming VPN traffic to the real interface directly connected to the internet.
Is this the right way to go? Do you have any configuration examples? I often saw VPN configurations used to connect to your home network, but that is not what I am looking for. I have a server up in the internet and want to use it as a proxy to encrypt traffic in insecure network environments like public WLANs.
Comment: Not sure about those VPN systems you mention, but many like OpenVPN have the VPN server act as the DHCP server.
Comment: I'm no fan of WPA, but the cost-benefit of that versus setting up some unholy mess of IPSec weighs *firmly* in favour of WPA.
Comment: @womble You are right about WPA, but sometimes you are using a public WLAN and you want to take care of your encryption yourself. It is more like a road warrior setup.
Comment: @Zoredache That is exactly my question. Unfortunately I cannot use OpenVPN because jailbreaking my iOS devices is not an option.
Comment: I'm in the process of decommissioning my OpenVPN connection from my laptop to my Linode; it turns out that using SSL for everything important (IMAP, IRC proxy, etc) is less annoying than dealing with the VPN, and now that I have (reasonably) ubiquitous wireless connectivity, the "tunnel everything over OpenVPN on tcp/443" requirement is gone too.
Comment: obviously setting up a VPN is a more advanced topic. thanks for your thoughts. This question seems to be discussed many times here but there is no complete solution including the network setup. I think I have to try things using a Linx VM befo deploying it to a server.
Answer: Finally I figured out how to use it. I chose strongswan with xauthrsasig authentication. It works flawlessly with iOS. I managed to implement it along the lines of this blogpost: http://www.hosthop.com/hop/knowledgebase/21/StrongswanorOpenswan-Pure-IPSEC-Tunnel-Configuration-for-iPhone-and-Similar-Devices.html


Ansible provided user always asking passpharse

Question: I created a jenkins user with Ansible, when I would connect to the machine its always asking passpharse. I didn't set it. The provided key has no passpharse
Here is the user creation:
- name: Create Jenkins user
  user:
    name: jenkins
    state: present
    shell: /bin/bash
    home: /home/jenkins
  tags:
    - debug

- name: Set authorized key for Jenkins user
  authorized_key:
    user: jenkins
    state: present
    key: https://mystorage.blob.core.windows.net/config/{{ env }}id_rsa.pub
  tags:
    - debug

After when I would connect to the machine via ssh
ssh -i azureid_rsa.pub email@example.com
Enter passphrase for key '../../../../blob/azureid_rsa.pub':

What is the problem? I didn't set the passpharse and the key hasn't have it.
Comment: Why do you try to connect with **public key**?
Comment: OMG! I go to burn myself somewhere!
Comment: @GergA Yes, you should need use private key to login, I add it as an answer. Hope it will help more people.
Comment: @GergA Don't be too hard on yourself. The ssh command could have been a bit more helpful and not ask for passphrase for a file which isn't even in an encrypted format.
Answer: Yes, you should use private key azureid_rsa to login. You could check this link:How Do SSH Keys Work?
SSH key pairs are two cryptographically secure keys that can be used to authenticate a client to an SSH server. Each key pair consists of a public key and a private key.
The private key is retained by the client and should be kept absolutely secret. Any compromise of the private key will allow the attacker to log into servers that are configured with the associated public key without additional authentication. As an additional precaution, the key can be encrypted on disk with a passphrase.
The associated public key can be shared freely without any negative consequences. The public key can be used to encrypt messages that only the private key can decrypt. This property is employed as a way of authenticating using the key pair.
The public key is uploaded to a remote server that you want to be able to log into with SSH. The key is added to a special file within the user account you will be logging into called ~/.ssh/authorized_keys.


Show Description Field on Individual Webform Submission Result

Question: I would like to include the description field when viewing individual webform submissions for each component. The standard webform individual submission display shows the label and the answer, but the description field for the component is not shown.
I had a look at webform-submission.tpl.php but wasn't sure how I could modify this to include the description being displayed.
Can anyone tell me how I can get the description to display?
I'm using Drupal 7 with Webform 7.x-4.19
Answer: After looking through the webform module I found out how to achieve this.
I used hook_webform_component_display_alter() which is there to enable customising the display of components in display only contexts. This function is in webform.api.php. I created my own function using this hook in a custom module to add the description to all textfield components as follows:
<?php
function my_mod_webform_component_display_alter(array &$element, array &$component) {
  if ($component['type'] == 'textfield') {
    $element['#description'] = $component['extra']['description'];
  }
}

For reference, the notes and example given from the webform module for hook_webform_component_display_alter() are:
/**
 * Allow modules to modify a "display only" webform component.
 *
 * @param array $element
 *   The display element as returned by _webform_display_component().
 * @param array $component
 *   A Webform component array.
 *
 * @see _webform_display_component()
 */
function hook_webform_component_display_alter(array &$element, array &$component) {
  if ($component['cid'] == 10) {
    $element['#title'] = 'My custom title';
    $element['#default_value'] = 42;
  }
}


May we annotate style for TargetApi in android

Question: I am trying to define the style

but fontFamily is not available for api 10, which I am using. So is there a way to use annotation in a stylesheet? Such as maybe @TargetAPI?
Answer: Add the xmlns:tools="http://schemas.android.com/tools" definition to your top-level XML tag, and then just add tools:targetApi="10" to the item defining fontFamily.


openssl update 1.0.1f to 1.0.1g broke sendmail (SSL23_GET_SERVER_HELLO:tlsv1 alert decode error)

Question: Two days ago I updated openssl 1.0.1f to 1.0.1g. Everything seemed fine. But after a while an error popped up in the sendmail log:
OpenSSL 1.0.1g fails

Apr 10 10:13:45 mail sendmail[17568]: STARTTLS=client, error: connect
failed=-1, reason=tlsv1 alert decode error, SSL_error=1, errno=0,
retry=-1
Apr 10 10:13:45 mail sendmail[17568]: STARTTLS=client:
17568:error:1407741A:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert
decode error:s23_clnt.c:762:
Apr 10 10:13:45 mail sendmail[17568]:
ruleset=tls_server, arg1=SOFTWARE, relay=mail.example.com,
reject=403 4.7.0 TLS handshake failed.

The mail has not been delivered.
OpenSSL 1.0.1f works
Then I downgraded to 1.0.1f and the mail has been sent with:

Apr 10 10:17:31 mail sendmail[31809]: STARTTLS=client,
relay=mail.example.com., version=TLSv1/SSLv3, verify=FAIL,
cipher=DHE-RSA-AES256-SHA, bits=256/256

It seems that there is another difference between the two openssl versions than only the heartbleed bugfix.
Version comparison
Then I tried on both OpenSSL versions:

openssl s_client -starttls smtp -connect mail.example.com:25

Output of OpenSSL version 1.0.1g:

CONNECTED(00000003)
140370040759952:error:1407741A:SSL
routines:SSL23_GET_SERVER_HELLO:tlsv1 alert decode
error:s23_clnt.c:762:

no peer certificate available

No client certificate CA names sent

SSL handshake has read 131 bytes and written 552 bytes

New, (NONE), Cipher is (NONE)
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE

Output of OpenSSL version 1.0.1f (parts):

CONNECTED(00000003)
depth=0 C = US, ST = California, L = San Bruno, O = "IronPort Systems,
Inc.", CN = IronPort Appliance Demo Certificate
verify error:num=20:unable to get local issuer certificate
verify return:1
depth=0 C = US, ST = California, L = San Bruno, O = "IronPort Systems,
Inc.", CN = IronPort Appliance Demo Certificate
verify error:num=21:unable to verify the first certificate
verify return:1

Certificate chain
0 s:/C=US/ST=California/L=San Bruno/O=IronPort Systems,
Inc./CN=IronPort Appliance Demo Certificate
i:/C=US/ST=California/L=San Bruno/O=IronPort Systems,
Inc./CN=IronPort Appliance Demo Certificate

Server certificate
---snipped---

No client certificate CA names sent

SSL handshake has read 1771 bytes and written 552 bytes

New, TLSv1/SSLv3, Cipher is DHE-RSA-AES256-SHA
Server public key is 1024 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
SSL-Session:
Protocol  : TLSv1

Cipher    : DHE-RSA-AES256-SHA

---Snipped---

What now?
I interpret, that the presented certificate from mail.example.com is one not meant for productive usage...
Is there a way how I can handle such certificates with openssl 1.0.1g? mail.example.com is one of several communication-partners which I have problems with.
Thanks
Teddy
Comment: Exactly how did you upgrade openssl? How was it originally installed? What sort of hardware and OS is this?
Answer: Circumstances forced me to compile openssl 1.0.1g from sources and I encountered behavior identical to that reported above.  This is under Fedora 18 on a 64-bit Intel.  Like the original poster reports, most mail went out OK but one mail destination suffered the same TLS handshake failures.
The openssl change log (brief CL here, detailed CL here) showed only three changes from 1.0.1f to 1.0.1g:

a security update
another security update
Add TLS padding extension workaround for broken servers.

Speculating that third change was responsible for the problem I commented out one line in ssl/tls1.h that appears to control presence of this "TLS padding" modification, like so:
/* #define TLSEXT_TYPE_padding 21 */
Compiled again, put the library .so files in place, restarted sendmail, and out went the queued mail with no problems.  I hope I haven't opened up new issues as a result.
Answer: Yes, there are two solutions:

Use SSLv3
compile without
/* #define TLSEXT_TYPE_padding 21 */

Reference here.
Comment: So in order to work around one broken middlebox (F5) they found out that another middlebox was broken (IronPort). Hate those broken middleboxes :(


Stream closed Exception while adding for 2nd time

Question: I am trying to index documents using Lucene... However I am getting a StreamClosed exception..
I think it is related more to Java then Lucene....
Can someone please guide..
The code snippet is as follows:
<code> static void indexDocs(File file,boolean flag,Directory dir,IndexWriterConfig iwc)
  throws IOException {
  // do not try to index files that cannot be read

      FileInputStream fis = null;
 if (file.canRead()) {

    if (file.isDirectory())
    {

     String[] files = file.list();
     System.out.println("list "  + files.length);
      if (files != null) {
        for (int i = 0; i < files.length; i++) {
            System.out.println("Invoked for  "  +  i  +  "and  "  +   files[i]);
          indexDocs(new File(file, files[i]),flag,dir,iwc);
        }
      }
   }
    else {

        boolean flags=true;

      try {
        fis = new FileInputStream(file);

     } catch (FileNotFoundException fnfe) {

       fnfe.printStackTrace();
     }
      try {
          Document doc = new Document();

          LineNumberReader lnr=new LineNumberReader(new FileReader(file));

          Field pathField = new StringField("path", file.getPath(), Field.Store.YES);
          doc.add(pathField);

          String line=null;
          int i=0;

          doc.add(new StringField("TT",file.getName(),Field.Store.YES));

          BufferedReader br=new BufferedReader(new InputStreamReader(fis));

           doc.add(new TextField("DD", br));

           System.out.println("Looping Again");

          while(flags)
          {
              IndexWriter iwcTemp1=new IndexWriter(dir,iwc);

          while( null != (line = lnr.readLine()) ){

            i++;

          StringField sf=new StringField("EEE",line.trim(),Field.Store.YES);
            doc.add(sf);

            if(i%10000==0)
            {
                System.out.println("Breaking   " +  i);
                lnr.mark(i);
                break;
            }
            sf=null;
          }
          if(line==null)
          {
              System.out.println("FALSE "   );
              flags=false;
          }

          System.out.println("FILE NAME IS FTP "  +   file.getName());

          if (iwcTemp1.getConfig().getOpenMode() == OpenMode.CREATE_OR_APPEND) {

              try
              {
                iwcTemp1.addDocument(doc);
                iwcTemp1.commit();
                iwcTemp1.close();

              }catch(Throwable t)
              {
                  lnr.close();
                    br.close();
                    fis.close();
                  t.printStackTrace();
              }

          } else {
              try
              {

            System.out.println("updating " + file);
            iwcTemp1.updateDocument(new Term("path", file.getPath()), doc);
              }catch(Exception e)
              {
                  e.printStackTrace();
              }
          }
          System.out.println("END OF WHILE");
          lnr.reset();
          }//end of While
      }catch (Exception e) {
         e.printStackTrace();
      }finally {
       fis.close();
      }
    }
  }
}
</code>
Exception I am getting is on the line where I am adding Document to Writer...
Exception trace:
<code>java.io.IOException: Stream closed
        at java.io.BufferedReader.ensureOpen(BufferedReader.java:114)
        at java.io.BufferedReader.read(BufferedReader.java:270)
        at org.apache.lucene.analysis.standard.StandardTokenizerImpl.zzRefill(StandardTokenizerImpl.java:923)
        at org.apache.lucene.analysis.standard.StandardTokenizerImpl.getNextToken(StandardTokenizerImpl.java:1133)
        at org.apache.lucene.analysis.standard.StandardTokenizer.incrementToken(StandardTokenizer.java:171)
        at org.apache.lucene.analysis.standard.StandardFilter.incrementToken(StandardFilter.java:49)
        at org.apache.lucene.index.DocInverterPerField.processFields(DocInverterPerField.java:102)
        at org.apache.lucene.index.DocFieldProcessor.processDocument(DocFieldProcessor.java:245)
        at org.apache.lucene.index.DocumentsWriterPerThread.updateDocument(DocumentsWriterPerThread.java:265)
        at org.apache.lucene.index.DocumentsWriter.updateDocument(DocumentsWriter.java:432)
        at org.apache.lucene.index.IndexWriter.updateDocument(IndexWriter.java:1513)
        at org.apache.lucene.index.IndexWriter.addDocument(IndexWriter.java:1188)
        at org.apache.lucene.index.IndexWriter.addDocument(IndexWriter.java:1169)
        at com.rancore.MainClass2.indexDocs(MainClass2.java:236)
</code>
Can someone please guide...Where am I going wrong...Kindly guide...
Answer: Your exception handling is incorrectly structured. It shouldn't be possible to continue with the read code if new FileInputStream() throws an exception.
Comment: Well I know that exception handling is not properly done because I have not yet done it... I am concerned about the stream closed exception...
Comment: So fix your code. At present if you get an exception on the open, you are continuing with the read, and getting the exception. If you fix your exception handling it won't happen. Proper exception handling isn't optional, or something you just lather on afterwards. It's an essential part of your program design. For one thing, it prevents self-inflicted bugs like this from ever happening in the first place.
Comment: It is possible that you don't close the writer. Why are you closing writer only on CREATE_OR_APPEND... IndexWriterConfig creation is out of the scope of the snippet. (btw it's very hard to read/understand your code...)


Determine whether $f(x)$ and $g(x)$ is decreasing or increasing without derivative

Question: Consider $f(x) = \frac{1}{\sqrt{x}} - x + 5$ and $g(x) = \frac{1}{\sqrt{x-1}} - \frac{1}{\sqrt{2-x}}$. We want to know that these functions are increasing or decreasing. I know that we can use determination sign of first derivative for checking it but I want the other ways to solve it. Also , one of the ways for doing it is that suppose $x_1<x_2$ and then prove $f(x_1) < f(x_2)$ or $f(x_1) > f(x_2)$ but I can't implement this method.If someone provide better ways or using this method is helpful.
Answer: Let us consider $0<x_1<x_2$
Since the square root function is strictly growing, $\sqrt{x_1} < \sqrt{x_2}$ and since the inverse is strictly decreasing, $\frac{1}{\sqrt{x_1}} > \frac{1}{\sqrt{x_2}}$
Obviously, $-x_1 > -x_2$
By summing, we get $f(x_1)>f(x_2)$
I let you do the other one in a similar fashion (this time, take $1<x_1<x_2<2$).
Following comment, hint for $g$
$x \rightarrow \frac{1}{\sqrt{x-1}} $ is strictly decreasing on $]1,2[$
$x \rightarrow \frac{1}{\sqrt{2-x}} $ is strictly increasing on $]1,2[$
You can show these in a similar fashion
Comment: Thank you , I've got the first function .  Unfortunately , I tried for $g(x)$ but didn't get result. Can you help me?


Why do some Drush commands only run from docroot?

Question: Wondering if anyone knows why some Drush commands (with file parameters) only run from the docroot and won't run from the project/composer root?
Commands such as drush sql-query and drush locale-import are among these.
For example, with standard Drupal folder structure:
/ (composer root)

composer.json
vendor
translations

translations.fr.po

web (docroot)

running from composer root:

vendor/bin/drush locale-import fr translations/translations.fr.po

gives file not found error. Even using ./translations/translations.fr.po gives same error
but going to docroot and running:

../vendor/bin/drush ../translations/translation.fr.po

works fine.
Our deploy scripts always run composer, drush and other commands from the composer root folder. So a bit of a pain to have to cd /web and then cd .. for these couple "special" Drush commands. Guessing there must be something I am doing wrong.
Comment: IIRC Drush commands tend to run with the web root (not execution path) as the working directory -  does `vendor/bin/drush locale-import fr ../translations/translations.fr.po` from the project root work?
Comment: @Clive, yes, that's the answer. I can run in project root but Drush still thinks of things as from docroot. Excellent. Thank you.
Comment: It might depend a on the version of Drush and the composer.json template you are using. Is the web root defined in composer.json? What version of Drush?
Comment: But in the end I think it's always safer to execute Drush commands from within the webroot.
Comment: Not sure how to mark a comment as the answer :(
Comment: @liquidcms – You can add and accept that as answer yourself then to help future readers find the solution quickly.
Answer: If you use a drush alias, it shouldn't matter where you run the command from e.g
drush @site some-command

The webroot is specified in the alias.
More info https://www.drush.org/latest/site-aliases/
Comment: That's an alias to the site url. It won't have any impact on Drush not handling path to file arguments correctly.
Comment: @liquidcms The drush alias contains various settings including the webroot directory specified in the root setting eg "root: /other/path/to/live/drupal"
Answer: Clive didn't post as an answer so I will just copy here:
Drush commands run as if from the web root (not execution path) as the working directory. So even though running command from the project root; argument paths have to be entered as if coming from the web root.
vendor/bin/drush locale-import fr ../translations/translations.fr.po

from the project root

David's answer would also work if you were using aliases (which I am not).


Counting TINYINT values in MySQL

Question: The table structure is like this:
actions: int(10)
unlock: tinyint(1)
user_id: int(20)
name: varchar(50)

I have such query:
SELECT SUM(actions) AS "sum_actions", SUM(unlock) AS "sum_unlock", user_id, name
 FROM mytable AS `Results` WHERE user_id != 0 GROUP BY user_id
 ORDER BY sum_actions DESC LIMIT 0,300

This gives #1064 - You have an error in your SQL syntax error.
When I remove SUM(unlock) AS "sum_unlock" then query works. So I thought that it is not possible to summing TINYINTs. So I changed to COUNT(unlock) as "count_unlock" but this didn't help. I don't want to change "unlock" table to INT because it only has boolean values. How can I count the unlock table with summing for each user_id ?
Comment: You also need to add `name` into your `GROUP BY`.
Answer: unlock is a reserved word.  Try this:
SELECT SUM(actions) AS "sum_actions", SUM(`unlock`) AS "sum_unlock", user_id, name
FROM mytable AS `Results`
WHERE user_id != 0
GROUP BY user_id
ORDER BY sum_actions DESC
LIMIT 0,300

Here is a list of reserved words.
Comment: @trante . . . For some reason, MySQL allows double quotes for string literals.  Most databases only allow singla quotes and double quotes play the role of back quotes in MySQL.  That's just the way it is designed, I guess.
Comment: That worked thank you. But it worked like this: SUM('unlock') When I changed it to SUM("unlock") it didn't work. What is the difference between *"* and *`* for SQL queries.
Answer: You can try SUM(CAST(unlock AS INT)) to count as if the column was an INT column without actually changing it to be an INT column:
SELECT
    SUM(actions) AS "sum_actions",
    SUM(CAST(unlock AS INT)) AS "sum_unlock",
    user_id,
    name
FROM
    mytable AS `Results`
WHERE
    user_id != 0
GROUP BY
    user_id,
    name
ORDER BY
    sum_actions DESC
LIMIT 0,300

Comment: I still get `#1064 - You have an error in your SQL syntax` error.

Counting TINYINT values in MySQL


How do i differentiate a crash cymbal from a ride cymbal which looks so similar

Question: Today I was practicing for a drum performance in school and I didn't know the positions of the crash cymbal and ride cymbal were different from the usual drum set up. I only realised the mistake halfway through the practice when the sound produced was weird.
How do I differentiate between the "Crash Cymbal" and "Ride Cymbal", which look so similar in appearance assuming you do not know the position of it in the drum set?
I am open to other answers which would allow me to differentiate between the two.
Comment: About the position, a ride cymbal is usually placed lower than the others cymbals : its allow us to hit the 3 parts (edge/bow/bell) easily at a high tempo. Its the hit-hat big sister.
Comment: Be prepared! I'd suggest turning up to class a few minutes early to familiarise yourself with the supplied kit. Then you can see where which cymbals are available, and you can adjust if someone else has changed the height and angle of the toms, changed the snare tuning, adjusted the height of the hi-hats, and so on.
Comment: ride is bigger than the crash
Comment: Related: https://music.stackexchange.com/questions/41554/difference-between-a-ride-and-a-crash-ride-cymbal?rq=1
Answer: The purist, jazz drummer in me will tell you there is no difference. You can place a cymbal wherever you want and play it however you want regardless of what word the manufacturer decided to print on it. You can ride a crash and crash a ride. "Crash" and "ride" are just divisions we've made based on how well they produce certain kinds of sounds. So really the only distinctions you can make are based on sound. Do you like the way it sounds when you crash it? Then crash it. Do you like the way it sounds when you ride it? Then ride it. But crash and ride don't have to be different cymbals - just different play styles. I often run an 18" "crash/ride" on the left and a thicker 20" "ride" on the left but I crash and ride both of them interchangeably depending on the music. So which one is my ride cymbal? Both. Which is my crash cymbal? Both. They just crash and ride in different ways and at different intensities. I also have a 17" "dark crash" that I like to ride in smaller venues and stuff. It's small and light and opens up at a pretty low volume. So it works pretty well in small, intimate spaces and playing lightly with light sticks. Alternatively, it makes an excellent crash cymbal in sort-of medium-loud live music or in the studio where volume doesn't really matter so much. So I feel it has pretty diverse applications.
Idk, that's a pretty philosophical approach to a simple question, but I legitimately feel the boxes we place on ourselves - you can only crash and crash and ride a ride - are limiting and inhibit our creativity and musicality. So go, crash your rides and ride your crashes. Experiment. Find what sounds good and let that be the ultimate measure of what a cymbal is. Size, thickness, position, even the label on the cymbal - no one in the audience or listening to your record is going to know or care about these trivialities - only sound matters.
Comment: Note that the question contains this: "I didn't know the positions of the crash cymbal and ride cymbal were different from the usual drum set up. I only realised the mistake halfway through the practice when the sound produced was weird." I think the question asker, Computernerd, would disagree with you. This person already rode a crash and crashed a ride, then didn't like what s/he heard.
Comment: Dekkadeci, Good observation. It sounds like Computernerd is already doing the right thing - trusting their ear. In that sense the question is already somewhat self-answering. "I only realized the mistake halfway through the practice when the sound produced was weird." followed immediately by: "How do I differentiate between the "Crash Cymbal" and "Ride Cymbal", which look so similar in appearance?" If it sounds weird, then it mustn't be your preferred setup. Differentiation achieved.
Answer: Hit both the cymbals once .
The "Crash Cymbal" should produce a loud, sharp "crash"
The "Ride Cymbal" should produce a  sustained, shimmering sound
Sample of Crash Cymbal sound
Sample of Ride Cymbal sound
Answer: As @Meaningful Username pointed out, the ride is usually heavier than the crash. It is also typically larger than the crash (ride usually 20 inches in diameter and crash mostly 14 to 18 inches).
If you hit the center region of a ride, it produces a bell-like sound.
Comment: If you hit the cup of a crash it will also produce a bell-like sound ;)
Comment: @BartoszKP really? I have never tried that!
Comment: Flat rides are designed without a bell.  They do not have a bell sound.
Comment: The crash cymbal is easily identified: it is far and away the more annoying of the two. Optimal placement is usually outside the auditorium, where no-one will have their hearing assaulted.
Answer: More often than not the word "crash" or "ride" is printed somewhere on the cymbal in question. A ride usually is thicker and heavier than a crash.
Answer: To add to what's here:
Ride cymbals will not be very loud when struck (comparitively), but will have overtones that last for much longer than crash cymbals.
Crash cymbals, for the most part, are meant to accent the beat - be loud when hit, then fade quickly.
If you hit both very hard, across the edge of your stick, listen to see what is still ringing many seconds later.
Comment: Actually, ride cymbals sound louder when played loud as they are bigger than crashes.  Most often, crashes are 16 to 19 inches, rides are 20 to 22 inches, and hi hats are 13 to 15 inches big.
Answer: There are already some great answers here, but in general, a ride cymbal will be wider than a crash cymbal, and will also have a larger, more pronounced bell in the center. There are exceptions, of course.
Answer: What makes Crash and Ride cymbals different is their sound, hence function. Putting it a little bit black and white:

a Crash asks for attention, i.e. is fine for certain accentuation ("LISTEN, here's something new ! ...")
a Ride you love listening to for a longer period of time ("what a nice contrast to the drums ...")

"Sound" depends on many circumstances, like:

the cymbals design, see other posts here
how you hit it (chopping vs. caressing)
where you hit it (bow, bell, rim)
hitting device, i.e. the contact point and its material (sticks, brushes, broomsticks, mallets, fingers ...)
the band/orchestra (i.e. its floor of frequencies, loudness, noise)
the room (broom closet vs. hall/outdoors)

etc. Which implies, as was already stated here, that you can:

"abuse" a Ride as a Crash (hit harder)
being gentle to the Crash for a Ride (softer stick control)

Like almost all things on the drumset it's subjected to the drummers preference, what she or he deems a good sound.


using hook_update to add a new cck field

Question: I am using d6.
I have a live site with an already built content type. I needed an extra column in the table, so I added this on install... I know realize how limiting this is and have rebuilt the content type to include this column as a field and I have unset the field in the form.
I have updated the code for this content type to include the new field, but when I move the code to my dev site, I do not see the new field.
Note: The content type was exported to code using the features module.
I thought maybe I need to run hook_update, but I haven't worked out how to do this.
This is what I have so far.
<code>function mymoduel_update_6004(){
  #REF: http://drupal.org/node/1031548
  drupal_load('module', 'content');
  drupal_load('module', 'mymodule');
  content_notify('install', 'mymodule');
  content_notify('enable', 'mymodule');
  return array();
}
</code>
I run update.php... but no visible changes :(
Has anyone got any ideas how I can update my cck content types?
Answer: After hours of searching, I finally found a post by Drewish that solves this.
http://drewish.com/node/118
The key to this is letting drupal core know you want to create a new field instance using
content_field_instance_create()


Why isn't a harp in a logarithmic shape?

Question: I was watching a harp, yesterday, and thought about the mathematics involved. I know that music is closely related to logarithms, because having a string or pipe twice as long produces the same note.
As an octave contains 7 notes, I would expect the strings 8 to be twice as long as the string 1, the string 9 to be twice as long as the string 2, etc.
Instead of that, the strings are strained between an oblic plane and a "S" shaped holder that reminds me a little of a $\frac{\sin(x)}{x}$ function.
I see two possibilities:

This shape is precisely calculated to produce the right notes.
This shape is only a matter of esthetic and the right pitch of the notes are mainly produced by the string diameter and tension.

Is there a mathematical reason to make the harps with such a non-logarithm shape?
Comment: An observation: classical pianos seem to have this shape too, turned on its side, whatever it is.
Comment: I guess Railsback curve also applies to harp.
Comment: [string calculator](http://www.harpsatsang.com/harp_design/data/stringcalculator.html)
Comment: @alex.jordan I've seen a joke somewhere: "The harp is a vertical naked piano".
Answer: You would expect it to have an exponential shape. Which it does, more or less, until the bottom end of the scale $-$ where practical considerations rule out 5-metre-tall harps.
Answer: the length would grow exponentially, if all the strings would be the same diameter and weight. however, they are not, to avoid 7 meter tall harps. the tension varies as well, because it's much harder to pluck a thicker string then a thinner one under the same tension.
Answer: The shape has little to do with the pitch. Pitch only deals with the string length to tension ratio. Obviously then the shape can effect the length BUT a harp could be "square". What it might require then is some very loose or tight strings... which then will, on practical matters, require very thick or thin strings.
Because a harp is "fretless" it allows one to vary the lengths of the individual strings (which would otherwise cause issues with the temperament). Hence the lengths of the strings can be adjusted to counter the above mentioned issues. I.e., increasing length allows one to increase the tension but have the same pitch. Of course there may be a special "curve" that maximizes all benefits of intonation for a harp but since a harp is fretless it wouldn't be all that useful, say, if one could do it on a fretted instrument (which you can't to any significant degree).
$$\begin{align*}
&f=\frac{\sqrt{T/u}}{2L}\\\\
\text{CP 12TET}\implies &f=440\cdot2^{p/12}
\end{align*}$$
which can be solved to relate the pitch in terms of tension, density, and length. You can figure out some "optimal" shapes (in the sense of the equation, not necessarily in practice) by, say, setting one of those variables as constant. If length is constant then it will produce the box pattern and you can see the required tensions and densities.
You could also "plug in the length curve for an actual harp and see how the tension and density are affected.
Comment: There is another variable to consider: the mass of the string per unit length. Wrap your string in heavy wire, and it sounds a lower pitch: look inside any piano.
Comment: @Lubin That is called the density! (The effect is more than density. Obvious the physical equation is simplified but density is what you are talking about and I did include that.
Answer: Another factor which many of you are missing is the fact that harp strings are made of different materials in different areas of the harp. I am a harpist myself by the way. The three types of strings are (from the large bass end to the small high end) wire, catgut, and nylon. These different materials require different lengths (and diameter and tension as well).
The long wire strings are different lengths because the body of the harp is angled down, while the neck (top part) is relatively straight here. These strings are changed primarily by tension rather than length or diameter.
The center portion (gut strings) has the most dramatic length change. The diameter is also significantly varied as you compare strings from different octaves.
Finally, the top portion (nylon strings) has the least variety in length, with the neck and body almost parallel. I do not now exactly why this is (the diameter is not greatly altered). My guess is that the tension makes the greatest impact on these strings. I can tell you that turning the tuning key results in a larger change on the nylons than the catgut, but not as much as on the wire strings.
I hope this is helpful! The shape of a harp is fascinating and surprisingly logical and mathematical.


While creating dummy variables with n values why cant we just create a single variable?

Question: For a variable that can take on n values, we create n-1 dummy variables, and that part is perfectly understood by me, but why cant we just create a single variable and load it with n unique values. For example if we have a categorical variable which can take on 3 values-India, USA, UK. We can simply create a single variable and put India=0, USA=1, UK=2, whats the problem with doing that?
Answer: Let's examine the regression model which would have the variables coded as indicated, but which is passed as a single column instead of dummies.
If India is the reference group, then the coefficient for country would be $\beta$.  It would represent the difference in the outcome between India and the USA.  Now, $2\beta$ would represent the difference between UK and India but forcing the effect to be twice that of the effect between USA and India seems a bit restrictive.  Its better to freely estimate the effects of each country in comparison to the reference group, which is what we get when we use dummies.


Square on graph of cubic

Question: Source of the problem: Mathematics Education Innovation
Let $k>0$ be some real constant and consider $f_k(x) = x^3 - k \, x$ for real $x$. Then one can show that for $k \geq \sqrt{8}$ there is a (tilted) square centered at $(0,0)$ with all its corners on the graph of $f_k$. (For $k=\sqrt{8}$ there is exactly one such square, for $k>\sqrt{8}$ there are two.) This minimal $k$ can be derived from a computation with resultants or Gröbner bases on the system of equations $$f_k(x)-y, \ f_k(y)+x, \ (3x^2 - k)(3y^2 - k)+1$$
and using $x,y \neq 0$ where required. (The third equation expresses that the curves given by the first two equations touch in a corner of the square.)
Now for the actual question: how could $k=\sqrt{8}$ be derived using only high school level mathematics? This is not a very precise question, but resultants and Gröbner bases are definitely out. Equations of "high" degree without apparent structure should be avoided as well.
Playing with the equations above leads to many derived equalities but getting rid of $x$ and $y$ by just playing around is not so simple it seems. (One such equation is $k^2=3x^2 y^2-1$ which suggests to somehow derive $x^2y^2=3$.)
Any method is acceptable by the way, it doesn't have to be purely algebraic as sketched above. Here's a nice picture for $k=\sqrt{8}$.
Answer: Here is how I would do it.
Consider a pair of perpendicular lines passing through the origin, rendered here as $y=mx$ and $y=-x/m$.  Combining each of these linear equations with $y=x^3-kx$ gives in turn the following non-origin intersections, where $L$= length if the "diagonal" between each pair of intersections:
$y=mx \rightarrow x_1=\pm\sqrt{k+m},L_1=2\sqrt{(1+m^2)(k+m)}$
$y=-x/m \rightarrow x_2=\pm\sqrt{k-(1/m)},L_2=\frac{2\sqrt{(1+m^2)(k-(1/m))}}{|m|}$
To make a square we then just render the diagonal congruent, thus $L_1=L_2$.  After removing common  factors, clearing fractions and squaring we ultimately arrive at a polynomial equation:
$m^4+km^3-km+1=0$
This looks ugly, but note that any line which solves this equation for a given $k$ must be accompanied by its perpendicular line.  Then the quartic polynomial in the slope $m$ must have pairs of roots with product $-1$ forcing this factorization:
$m^4+km^3-km+1=(m^2+am-1)(m^2+bm-1)=0$
Matching both cubic and linear terms then gives $a+b=k$, while matching quadratic terms yields $ab=2$.
Now to get a single pair of perpendicular lines, corresponding to a single "inscribed" square, we need $a=b$ making the factors identical.  Then from the matching equations given above either
$a=b=\sqrt{2},k=2\sqrt{2}$
or
$a=b=-\sqrt{2},k=-2\sqrt{2}$.
The second root gives no square in the real plane; instead the vertices of that square have imaginary coordinates.  The first root is the one giving a single square in the real plane.  The corresponding slopes of the lines for this case, obtained by solving $m^2+(\sqrt{2})m-1=0$, are $m=(-\sqrt{2}\pm\sqrt{6})/2$.
Comment: Nice method, thanks. Getting $k$ as the minimum value of $(m^4+1)/(m-m^3)$ on the interval $(0, 1)$ still seems quite a challenge though.
Comment: I do not minimize the k function directly. Rather I use the factorization of the quartic to identify the minimum positive k for real factors, which would give the single root. Incidentally, the slopes of the diagonals in the degenerate case are $(-\sqrt{2}±\sqrt{6})/2$.
Answer:
how could $k=\sqrt{8}$ be derived using only high school level mathematics?

The following is a somewhat speculative argument that "something happens" at $\,k=2 \sqrt{2}\,$.
To start with the speculation, the central symmetry of the cubic suggests that an inscribed square might be centered at the origin (though it doesn't prove that it has to). Let $\,(a,b)\,$ be one vertex of such a square, then the other three would be $\,(-b,a), (-a,-b), (b,-a)\,$. The last two follow by symmetry, and the relevant conditions for the first two vertices to lie on the cubic are;
$$
\begin{align}
\begin{cases}
b = a^3 - ka \\
a = -b^3 + kb
\end{cases}
\end{align}
$$
Eliminating (for example) $\,a\,$ between the equations:
$$
b = a\left(a^2 - k\right) = -b\left(b^2-k\right)\left(b^2\left(b^2-k\right)^2-k\right)
$$
Canceling out the $\,b\,$ factor, then expanding and collecting:
$$
b^8 - 3 k b^6 + 3 k^2 b^4 - k (k^2 +1) b^2 + k^2 + 1 = 0 \\[10px]
\iff\quad  P(c) = c^4 - 3 k c^3 + 3 k^2 c^2 - k (k^2 +1) c + k^2 + 1 = 0 \quad\quad \style{font-family:inherit}{\text{where}} \;\; c = b^2
$$
The latter quartic cannot have negative real roots by Descartes' rule of signs, and the nature of the roots can only change at points where there is a double root. Writing the condition as either the discriminant vanishing, or $\,\deg \gcd(P, P') \ge 1\,$ gives after routine (albeit tedious) calculations:
$$
0 = 4 k^6 - 60 k^4 + 192 k^2 + 256 = 4 (k^2 - 8)^2 (k^2 + 1)
$$
The negative root $\,k = -2 \sqrt{2}\,$ is uninteresting since $\,f(x)\,$ is an increasing function when $\,k \lt 0\,$. However, the positive root $\,k = 2 \sqrt{2}\,$ does in fact lead to explicit solutions for $\,c\,$, then $\,b\,$ and $\,a\,$.
Comment: Sure, that's how we do such things. But not exactly high school material.
Comment: @WimC I'd still call it high-school level, with the disclaimer that it's been a long time for me since ;-) The steps I glossed over can be elaborated without much difficulty, though the complete step-by-tiny-step proof would become long'ish to write down in detail. That said, I don't know that you'll find a satisfying short and simple high-school level answer to the question.
Comment: I cannot say that I learned about discriminants, other than the quadratic one, in high school.
Comment: @OscarLanzi Neither can I, which is why I wrote that the polynomial $\,\gcd\,$ can be used, instead, which requires nothing more than euclidean (long) division.

Square on graph of cubic


graphlab don't recommend items already owned by user

Question: what should one specify when creating a graphlab recommender model such that the item that a user already own is not recommended to him again? Can this be done directly by specifying certain parameters or do I need to write a recommender from scratch.? data would look something like this
| user_id    |  item_id    | othercolumns |
|:-----------|------------:|:------------:|
| 1          |     21      |     This     |
| 2          |     22      |     column   |
| 1          |     23      |     will     |
| 3          |     24      |     hold     |
| 2          |     25      |     other    |
| 1          |     26      |     values   |

Since item 21,23 and 26 are already owned by user 1 this item should not be recommended to him.
Answer: This behaviour is controlled by the exclude_known parameter of the recommender.recommend method (doc).

exclude_known : bool, optional
By default, all user-item interactions previously seen in the training
  data, or in any new data provided using new_observation_data.., are
  excluded from the recommendations. Passing in exclude_known = False
  overrides this behavior.

Example
>>> import graphlab as gl
>>> sf = gl.SFrame({'user_id':[1,2,1,3,2,1], 'item_id':[21,22,23,24,25,26]})
>>> print sf
+---------+---------+
| item_id | user_id |
+---------+---------+
|    21   |    1    |
|    22   |    2    |
|    23   |    1    |
|    24   |    3    |
|    25   |    2    |
|    26   |    1    |
+---------+---------+
[6 rows x 2 columns]
>>> rec_model = gl.recommender.create(sf)
>>> # we recommend items not owned by user
>>> rec_wo_own_item = rec_model.recommend(sf['user_id'].unique())
>>> rec_wo_own_item.sort('user_id').print_rows(100)
+---------+---------+----------------+------+
| user_id | item_id |     score      | rank |
+---------+---------+----------------+------+
|    1    |    22   |      0.0       |  1   |
|    1    |    24   |      0.0       |  2   |
|    1    |    25   |      0.0       |  3   |
|    2    |    21   |      0.0       |  1   |
|    2    |    23   |      0.0       |  2   |
|    2    |    24   |      0.0       |  3   |
|    2    |    26   |      0.0       |  4   |
|    3    |    21   | 0.333333333333 |  1   |
|    3    |    23   | 0.333333333333 |  2   |
|    3    |    26   | 0.333333333333 |  3   |
|    3    |    22   | 0.166666666667 |  4   |
|    3    |    25   | 0.166666666667 |  5   |
+---------+---------+----------------+------+
[12 rows x 4 columns]
>>> # we recommend items owned by user
>>> rec_w_own_item = rec_model.recommend(sf['user_id'].unique(), exclude_known=False)
>>> rec_w_own_item.sort('user_id').print_rows(100)
+---------+---------+----------------+------+
| user_id | item_id |     score      | rank |
+---------+---------+----------------+------+
|    1    |    21   | 0.666666666667 |  1   |
|    1    |    23   | 0.666666666667 |  2   |
|    1    |    26   | 0.666666666667 |  3   |
|    1    |    22   |      0.0       |  4   |
|    1    |    24   |      0.0       |  5   |
|    1    |    25   |      0.0       |  6   |
|    2    |    26   |      0.0       |  6   |
|    2    |    24   |      0.0       |  5   |
|    2    |    23   |      0.0       |  4   |
|    2    |    21   |      0.0       |  3   |
|    2    |    25   |      0.5       |  2   |
|    2    |    22   |      0.5       |  1   |
|    3    |    24   |      0.0       |  6   |
|    3    |    25   | 0.166666666667 |  5   |
|    3    |    22   | 0.166666666667 |  4   |
|    3    |    26   | 0.333333333333 |  3   |
|    3    |    23   | 0.333333333333 |  2   |
|    3    |    21   | 0.333333333333 |  1   |
+---------+---------+----------------+------+
[18 rows x 4 columns]
>>> # we add recommended items not owned by user to the original SFrame
>>> rec = rec_wo_own_item.groupby('user_id', {'reco':gl.aggregate.CONCAT('item_id')})
>>> sf = sf.join(rec, 'user_id', 'left')
>>> print sf
+---------+---------+----------------------+
| item_id | user_id |         reco         |
+---------+---------+----------------------+
|    21   |    1    |     [24, 25, 22]     |
|    22   |    2    |   [24, 26, 23, 21]   |
|    23   |    1    |     [24, 25, 22]     |
|    24   |    3    | [21, 23, 26, 25, 22] |
|    25   |    2    |   [24, 26, 23, 21]   |
|    26   |    1    |     [24, 25, 22]     |
+---------+---------+----------------------+
[6 rows x 3 columns]

Comment: Yes, it looks like `exclude` argument could do the job.
Comment: How to handle when we have additional boolean column is_purchased which is true if the user has purchased that item otherwise false. In the doc which you mentioned I see a exclude argument, should I add this arg with SFrame( user who has already purchased the item ) to handle the case.


Arzela-Ascoli over uniformly bounded differentiable functions in $C[a,b]$

Question: As an example of Arzela-Ascoli theorem in intro. to topology course, the following case was exhibited:
Let $A\subset C[a,b]$ be a set of differentiable functions such that: $\forall f\in A,\ \vert f \vert \leq M_1,\ \vert f' \vert \leq M_2$
thus A is bounded and equicontinuous, thus every sequence $\{f_n\}$ has a converging subsequence.
My question is: The limit function isn't necessarily in $A$, right?

A isn't necessarily a closed set, and the more detaild chain of consequences is: bounded & equicontinuous $\rightarrow$ absolutely bounded $\rightarrow\ \bar A$ is closed and absolutely bounded $\rightarrow\ \bar A$ is compact $\rightarrow$ every sequence $\{f_n\}\subset \bar A$ has a converging sub-sequence.

So a sequence in $A$ might converge to $C[a,b]\supset \bar A \ni f \notin A$, am I right?
Comment: Right, take $f_n(x) \equiv 1/n$ for example.
Comment: Another way to think about this is that Arzelà–Ascoli only tells you $A$ is precompact. So if it's not closed (and hence not compact), the sequence need not converge to a limit in $A$.
Comment: Great, thank you both
Answer: As pointed out in the comments by zhw and Fimpellizieri:
We only know that $A$ is precompact for the metric induced by the uniform norm, but it may not be closed. For example, if $A=\left\{ x\mapsto 1/n,n\in\mathbb N,  n\geqslant 1\right\}$, the limit of $\left(1/n\right)$ does not belong to $A$.


Elasticsearch fuzzy query and match with fuzziness

Question: So i saw these two queries.
First one is match with fuzziness option
{
    "query": {
       "match": {
         "user": {
           "query": "ki",
           "fuzziness": "AUTO"
         }
       }
    }
}

Second one is normal fuzzy search
{
"query": {
    "fuzzy": {
        "user": {
            "value": "ki"
         }
      }
   }
}

Result is pretty much the same. But my question is, does the query really does the same structure? and which one to use for fuzziness best practice?
Answer: In your example the results are the same. However, the fuzzy query behaves like a term query, so it does not perform analysis beforehand, whereas the match query does.
So if you searched for an address field containing pigeon street and indexed with a standard analyser, this query would work
GET my-index/_search
{
    "query": {
        "match": {
            "address": {
                "query": "wigeon street",
                "fuzziness": 1
            }
        }
    }
}

but this one would not:
GET my-index/_search
{
    "query": {
        "fuzzy": {
            "address": {
                "value": "wigeon street"
            }
        }
    }
}