Connecting Acoustic Piano to Laptop for Recording in Logic?

Question: I know about connecting digital pianos (MIDIs) to a laptop for use in logic.
My question is concerning a standard normal acoustic piano. My baby grand has a silent piano Yamaha system attached to it so I can practice with headphones. It has a headphone input - if I buy a 3.5mm aux jack to usb c cable, would I be able to record using my piano in logic?
Comment: If your piano has a headphone jack, then it is not an acoustic piano.
Comment: It sounds like you have a combination acoustic/digital piano. To clarify, it would be helpful if you edited your question to indicate the specific piano you have (brand and model).
Comment: Does this answer your question? [Recording digital piano sound](https://music.stackexchange.com/questions/72534/recording-digital-piano-sound)
Comment: @aaron Does combinations which actually *mute* the acoustic sound actually exist?
Comment: @Tom For example: https://usa.yamaha.com/products/musical_instruments/pianos/silent_piano/index.html
Comment: @Aaron Oh neat! I would not have imagined people actually making these! Thanks!
Comment: @Aaron Apologies for the confusion. To confirm, I have a Bosendorfer baby grand that has a Yamaha silent piano system attached to it so I can practice with headphones. There is a headphone jack, so I'm guessing this could be linked to my Mac logic with a suitable cable?
Comment: I didn't realize those existed either.  For all practical purposes, it is a digital piano when being used in silent mode, so the question I linked should still apply to you.
Answer: Based on your comment (Bosendorfer piano, Yamaha silent system), if you record your piano from the headphone jack you will not be recording your actual piano sound but a digital piano sample (although I'm sure a very good one) that Yamaha has built into its silent piano.
This question is borderline off topic (gear recommendation) but I will try and provide some useful information and options.
If you want to record the real acoustic sound of your piano in stereo then you will need two mics (or a stereo mic) and an audio interface with two XLR inputs, or a stereo mic with a USB output. Companies like Focusrite, Presonus, Mackie and many others make interfaces starting at a little over $100 and go way up from there.
If you are fine with just recording the Yamaha digital sample then there are some options. Some older Macs actually have a microphone/line input. Some not-so-old Macs have a two function jack that works either as a headphone or a mic/line in. An internet search of the year and model of your Mac should help you find out if yours has this feature. If yours is one of these then all you need is a stereo cable to send a signal to the computer. Keep in mind that this will not give you the best sound quality but may be fine for your purposes.
If it doesn't have the mic/line in feature then you will need some type of interface and adapter plugs or cables to record. Check to see if the headphone out is the only audio output on your Yamaha system. If there is another output make a note of it and call a company like Sweetwater. They can steer you in the right direction as far as exactly what is required for your specific computer and give you options covering different budgets. Good luck!
Comment: Thank you so much! Very detailed answer. I'll get to checking how my system works now
Comment: You're welcome. If you want to go the super simple route there are several mic/line to usb-c adapters on Amazon in the $10 range too. I can't speak for their quality/reliability though.


How can I backup and restore my Windows 2003 Firewall Settings?

Question: It seems that when I install TFS I just lost all my Windows Firewall settings.
How can I back this up and restore them on Windows 2003?
Answer: The firewall configuration is stored in the registry
<code>HKLM\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\StandardProfile\
</code>
It can be exported to backup or if you do a registry backup its included in it.
Answer: Since Windows Vista/Windows Server 2008 netsh.exe utility allows (netsh advfirewall export)  to export/import Windows Firewall with Advanced security configuration.
But it seems for Windows XP/Windows Server 2003 no other possible [standard] solutions for this task except export/import registry settings as jer.salamon stated above.


Keeping width ratio between two columns css3

Question: I want to use media queries to make a responsive website. I have some pages with 2 columns, others with 3 or 4.
For example I have two columns: #colA and #colB. #colA has width 600px, #colB has 360px with a wrapper of 960px width.
I want to use media queries so that if the wrapper has less than 960px, the columns will keep the width proportions between them (which should turn #colA's 600px to 62.5% and #colB's 360px to 37.5% widths..
Is there a way to do this with html/css? If not what are the other (easiest/lightest) options to use with media query?

content1

content2

to convert in

content1

content2

Using css/html?
Edit1: Yes it is a CMS. The user sets the width values in px by dragging some sliders in the control panel. I need to make the template responsive, so when the wrapper's width is less then 960px, the columns will still keep their width proportions between them.
Comment: http://css-tricks.com/when-using-important-is-the-right-choice/
Comment: Sure. Use percentages from the start. To make your life easier, grab one of the many existing responsive grid libraries, such as Boostrap.
Comment: I can't, they are hardcoded in px and can't acces them..
Comment: It's not clear what you mean. "Hardcoded"? Does that mean inline styles? They can usually be overridden. Show some code.
Comment: I know how to override inline values, the problem is elsewhere.. I need to transform pixels to percents dynamically AND also keep the width proportions between the columns inside a wrapper.
Comment: I'm still not entirely clear, but you may need scripting. Is jQuery available?
Answer: Your media query should look something like this, just make sure this code sits beneath the previously assigned styles for #colA and #colB
@media screen and (max-width: 959px) {
   #colA{ width:62.5%; }
   #colB{ width:37.5%; }
}

Comment: The cols can have any values in px, I must find a way to transform their width in percents dynamically..
Comment: If you're in a CMS or some other environment with code constraints you need to make that clear in your question.
Comment: This would be a case where !important could be used to overwrite the inline styles, although I'm unclear as to a situation where this would occur.
Answer: I think the easiest way to do it is right in your problem statement. Just use the percentage.
#colA {
    width: 62.5%;
}

and so on...


What are some beautiful examples of adjunctions?

Question: Lately I've been very interested in finding examples of adjunctions. In particular, examples that are elementary enough for an undergrad like me to grasp. So I was wondering if perhaps you could share some of your favourite examples of adjunctions and maybe little hints and suggestions on how to explore them and their implications.
Although I'd be very interested in examples in real analysis, number theory, and topology (something that motivates the study of locales would be very nice), I don't wish to be too restrictive, so feel free. And don't pay much attention to "for an undergrad to grasp", since being unable to understand something is a temporary thing, I hope...
Comment: http://math.stackexchange.com/questions/46708/a-bestiary-about-adjunctions
Comment: Hom and $\otimes$ is probably the simplest and most useful.
Answer: Here are some very basic examples, but which you don't find so often mentioned.
1. For real numbers $r$ and integers $z$ we have $$\iota(z) \leq r \Leftrightarrow z \leq \lfloor r \rfloor,$$
where $\iota$ is the inclusion map from integers to real numbers and $\lfloor - \rfloor$ is the floor function. That means that $\iota : (\mathbb{Z},\leq) \to (\mathbb{R},\leq)$ is left adjoint to $\lfloor - \rfloor : (\mathbb{R},\leq) \to (\mathbb{Z},\leq)$, where we regard preorders (and monotonic maps) as categories (and functors). Similarly, $\iota$ is right adjoint to the ceiling function $\lceil - \rceil: (\mathbb{R},\leq) \to (\mathbb{Z},\leq)$. (In the context of preorders, adjunctions are usually called Galois connections.)
2. Let $\mathsf{Ban}_1$ denote the category of Banach spaces with short linear maps. The forgetful functor $\mathsf{Ban}_1 \to \mathsf{Set}$ which maps a Banach space to its unit ball has a left adjoint $\ell^1 : \mathsf{Set} \to \mathsf{Ban}_1$ which maps a set $X$ to the Banach space $\ell^1(X)$ of summable functions on $X$.
3. Let's say a group $G$ is of exponent $n$ if $g^n=1$ for all $g \in G$. These groups constitute a full subcategory $\mathsf{Grp}_n \hookrightarrow \mathsf{Grp}$. The inclusion functor has a left adjoint: It maps a group $G$ to the quotient group $G/N$, where $N$ is the normal subgroup which is generated (as a normal subgroup) by all $g^n$, $g \in G$. This construction is connected to the famous Burnside problem.
4. For a map of sets $f : X \to Y$ we have
$$f_*(A) \subseteq B \Leftrightarrow A \subseteq f^{-1}(B)$$
for subsets $A \subseteq X$ and $B \subseteq Y$. This means  that $f_* : (\mathcal{P}(X),\subseteq) \to (\mathcal{P}(Y),\subseteq)$ is left adjoint to $f^{-1}: (\mathcal{P}(Y),\subseteq) \to (\mathcal{P}(X),\subseteq)$. Notice that this implies $f_*(\bigcup_i A_i) = \bigcup_i f_*(A_i)$, since left adjoints are cocontinuous (but not $f_*(\bigcap_i A_i) = \bigcap_i f_*(A_i)$, which only holds when $f$ is injective).
5. Let $\mathsf{Mor}(\mathsf{Grp})$ be the usual morphism category of the category of groups and let $\mathsf{Mono}(\mathsf{Grp})$ be the full subcategory consisting of monomorphisms of groups, i.e. injective homomorphisms. Then, the inclusion functor has a left adjoint, mapping a homomorphism $f : G \to H$ to the induced homomorphism $\overline{f}: G/\ker(f) \to H$.
6. The inclusion functor $\mathsf{Haus} \to \mathsf{Top}$ from Hausdorff spaces to topological spaces has a left adjoint, the "maximal Hausdorff quotient". Explicitly, this is $X \mapsto X/{\sim}$, where $\sim$ is the intersection of all equivalence relations $R$ such that $X/R$ is Hausdorff.
7. The inclusion functor from normed spaces to seminormed spaces has a left adjoint. It maps a seminormed space $(V,\lVert - \rVert)$ to $(V/K,\lVert - \rVert)$, where $K := \{v \in V : \lVert v \rVert = 0\}$ and $\lVert \overline{v} \rVert := \lVert v \rVert$. Exactly this construction is used in the definition of $L^p$-spaces in measure theory.
Comment: 1. "In the context of preorders, adjunctions are usually called Galois connections." --- only particular kinds of adjunctions: a Galois connection between $P$ and $Q$ is an adjunction from $P$ to $Q^{\mathrm{op}}$; in particular, the notion is symmetric (you get closure operators on both, as opposed to a closure operator on one and an interior operator on the other).
Comment: 4. What you denote $f_*$ is more typically denoted $f_!$ or $\exists_f$, since $f^{-1}$ also has a *right* adjoint, denoted $f_*$ or $\forall_f$; this explains why $f^{-1}$ preserves both unions *and* intersections. For example, in differential topology, if $f\colon M\to N$ is smooth, then the set of regular values of $f$ is $\forall_f$ of the set of its regular points
Comment: For $Haus$ and $Top$ you could also have mentioned $CompHaus$ and $Top$, with the Stone-Čech compactification
Answer: I'm no expert in category theory, but here are some easy examples I can think of:

Categories with closed monoidal structure are really great, because they give you a nicely behaved notion of a "mapping object". A closed monoidal category $\mathsf{C}$ is one where the functor $(-)\otimes X$ has a right adjoint $[X, (-)]$ called the internal hom. This essentially allows you to curry arrows out of $Y \otimes X$. For example, in the category of abelian groups, or more generally R-modules for a commutative ring R, the hom-sets have an obvious R-module structure, and this gives us an internal hom associated to the tensor product.
If the monoidal product is the usual categorical product (i.e. the limit) then you get what we call a Cartesian closed structure. The category of sets is Cartesian closed, for example, and so is the category of compactly generated spaces, and the category of diffeological spaces.
Using adjoints, we can make precise the notion of a free functor in algebra, which you have probably already encountered in the form of free groups, free R-modules, and so on. A free functor is just one that is left-adjoint to a forgetful functor.
The category of topological spaces has a forgetful functor to the category of sets, which has both a left adjoint (discrete functor) and a right adjoint (indiscrete functor). This means that the forgetful functor preserves both limits and colimits, which is why limits and colimits in topology are pretty easy to compute.
Answer: Here's a fun example. Suppose $ H $  a subgroup of $ G $ and let $ \iota $ denote the inclusion $ H \hookrightarrow G $. Let $ k $ be a field and let $ \operatorname{Vect}_{k} $ denote the category of $ k $-vector spaces. Regarding $ G $ as a category, objects of the functor category $ \operatorname{Vect}_{k}^{G} $ are $ G $-respresentations over $ k $ and morphisms are $ G $-equivariant maps.
Pre-composition with $ \iota $ defines a restriction functor $ \operatorname{res} \colon \operatorname{Vect}_{k}^{G} \to \operatorname{Vect}_{k}^{H} $. This functor has both left and right adjoints — the left adjoint is the left Kan extension along $ \iota $ (regarded as a functor from $ H $ to $ G $ regarded as categories) and the right adjoint is the right Kan extension along $ \iota $. These are the induction functor $ \operatorname{ind}_{H}^{G} $ which sends a $ H $-representation to the induced $ G $-representation, and the (perhaps less well-known) coinduction functor $ \operatorname{coind}_{H}^{G} $.
The same thing happens for $ G $-sets, $ G $-spaces, based versions of these, and $ G $-objects in any category when both adjoints exist.
Answer: Here is a logic example, as a special case of Galois connections, from Lambek's "The Influence of Heraclitus on Modern Mathematics" (Scientific Philosophy Today, pp. 111-121). Lambek reports that it was first studied by Lawvere:
Let $\mathcal{P}$ be the category with formulas of propositional calculus as objects and "entailments" $\vdash$ as arrows (so that $\mathcal{P}$ is a preorder). Define $\forall p\in\operatorname{Obj}(\mathcal{P})$ endofunctors $F_p,G_p:\mathcal{P}\to\mathcal{P}$ by $F_p:q\mapsto (p \wedge q)$ and $G_p:q\mapsto (p\Rightarrow q)$ (the arrow functions are the expected ones). Then $F_p$ is a left adjoint to $G_p$, and the counit of the adjunction is the good old "modus ponens" (naturality in $p$ can be established by the so-called "parameter theorem").


Find generating function of $ a_n=2a_{n-1}-3a_{n-2}+4n-1 $

Question: I have to find generating function of $ a_n=2a_{n-1}-3a_{n-2}+4n-1 $ where $a_0=1$ and $a_1=3$. I'm currently stuck at the form:
$f(x) = \sum_{n=0}^\infty a_nx^n = 1 + 3x +2x\sum_{n=2}^\infty(a_{n-1}x^{n-1})-3x^2\sum_{n=2}^\infty(a_{n-2}x^{n-2})+\sum_{n=2}^\infty((4n-1)x^{n})$
I have no idea how to go further.
Answer: Let's restart from beginning.
 We have
$$
\left\{ \matrix{
  a_{\,n}  = 0\quad \left| {\;n < 0} \right. \hfill \cr
  a_{\,0}  = 1 \hfill \cr
  a_{\,1}  = 3 \hfill \cr
  a_{\,n}  = 2a_{\,n - 1}  - 3a_{\,n - 2}  + 4n - 1 \hfill \cr}  \right.
$$
The best approach is to adjust the recurrence as to accomodate
the initial values. We shall do in this way
$$
\eqalign{
  & a_{\,0}  = 1 = 2a_{\,0 - 1}  - 3a_{\,0 - 2}  + 4 \cdot 0 - 1 =  - 1\quad  \Rightarrow   \cr
  &  \Rightarrow \quad a_{\,n}  = 2a_{\,n - 1}  - 3a_{\,n - 2}  + 4n - 1 + 2\left[ {0 = n} \right]  \cr
  & a_{\,1}  = 3 = 2a_{\,0}  - 3a_{\,1 - 2}  + 4 \cdot 1 - 1 + 2\left[ {0 = 1} \right] = 5\quad  \Rightarrow   \cr
  & a_{\,n}  = 2a_{\,n - 1}  - 3a_{\,n - 2}  + 4n - 1 + 2\left[ {0 = n} \right] - 2\left[ {1 = n} \right] \cr}
$$
where $[P]$ denotes the Iverson bracket
$$
\left[ P \right] = \left\{ {\begin{array}{*{20}c}
   1 & {P = TRUE}  \\
   0 & {P = FALSE}  \\
 \end{array} } \right.
$$
So we get a recurrence which is valid for all $0 \le n$.
$$
\left\{ \matrix{
  a_{\,n}  = 0\quad \left| {\;n < 0} \right. \hfill \cr
  a_{\,n}  = 2a_{\,n - 1}  - 3a_{\,n - 2}  + 4n - 1 + 2\left[ {0 = n} \right] - 2\left[ {1 = n} \right] \hfill \cr}  \right.
$$
or better
$$
a_{\,n}  = 2\left[ {1 \le n} \right]a_{\,n - 1}  - 3\left[ {2 \le n} \right]a_{\,n - 2}  + 4n - 1 + 2\left[ {0 = n} \right]
 - 2\left[ {1 = n} \right]\quad \left| {\;0 \le n} \right.
$$
Now we can multiply by $x^n$ and sum
$$
\eqalign{
  & f(x) = \sum\limits_{n = 0}^\infty  {a_{\,n} x^{\,n} }  =   \cr
  &  = 2\sum\limits_{n = 0}^\infty  {\left[ {1 \le n} \right]a_{\,n - 1} x^{\,n} }  - 3\sum\limits_{n = 0}^\infty  {\left[ {2 \le n} \right]a_{\,n - 2} x^{\,n} }  +   \cr
  &  + 4\sum\limits_{n = 0}^\infty  {nx^{\,n} }  - \sum\limits_{n = 0}^\infty  {1x^{\,n} }  + 2\sum\limits_{n = 0}^\infty  {\left[ {0 = n} \right]x^{\,n} }  - 2\sum\limits_{n = 0}^\infty  {\left[ {1 = n} \right]x^{\,n} }  =   \cr
  &  = 2\sum\limits_{n = 1}^\infty  {a_{\,n - 1} x^{\,n} }  - 3\sum\limits_{n = 2}^\infty  {a_{\,n - 2} x^{\,n} }  +   \cr
  &  + 4\sum\limits_{n = 0}^\infty  {nx^{\,n} }  - \sum\limits_{n = 0}^\infty  {1x^{\,n} }  + 2x^{\,0}  - 2x^{\,1}  =   \cr
  &  = 2\sum\limits_{n = 0}^\infty  {a_{\,n} x^{\,n + 1} }  - 3\sum\limits_{n = 0}^\infty  {a_{\,n} x^{\,n + 2} }
  + 4\sum\limits_{n = 0}^\infty  {nx^{\,n} }  - \sum\limits_{n = 0}^\infty  {x^{\,n} }  + 2 - 2x =   \cr
  &  = \left( {2x - 3x^{\,2} } \right)\sum\limits_{n = 0}^\infty  {a_{\,n} x^{\,n} }  + 4\sum\limits_{n = 0}^\infty  {nx^{\,n} }  - {1 \over {1 - x}} + 2 - 2x \cr}
$$
And the term with $nx^n$ becomes
$$
\eqalign{
  & \sum\limits_{n = 0}^\infty  {nx^{\,n} }  = \sum\limits_{n = 1}^\infty  {nx^{\,n} }  = x\sum\limits_{n = 1}^\infty  {nx^{\,n - 1} }  =   \cr
  &  = x{d \over {dx}}\sum\limits_{n = 0}^\infty  {x^{\,n} }  = {x \over {\left( {1 - x} \right)^{\,2} }} \cr}
$$
Finally
$$
\eqalign{
  & f(x) = \left( {2x - 3x^{\,2} } \right)f(x) + 4{x \over {\left( {1 - x} \right)^{\,2} }} - {1 \over {1 - x}} + 2 - 2x  \cr
  & f(x) = {{5x - 1} \over {\left( {1 - 2x + 3x^{\,2} } \right)\left( {1 - x} \right)^{\,2} }} + {{\left( {1 - x} \right)} \over {\left( {1 - 2x + 3x^{\,2} } \right)}} \cr}
$$
Comment: And what about the first part? How do i deal with sums starting from 1 or 2, instead of 0?
Answer: Hint.
Calling $A(x)=\sum_{k=0}^{\infty} a_k x^k$ we have
$$
(a_k-2a_{k-1}+3a_{k-2})x^k = (4n-1)x^k
$$
and
$$
\sum_{k=2}^{\infty}a_k x^k = A(x) - a_0-a_1 x\\
\sum_{k=2}^{\infty}a_{k-1} x^k = x(A(x)-a_0)\\
\sum_{k=2}^{\infty}a_{k-2} x^k = x^2A(x)
$$
and also
$$
\sum_{k=2}^{\infty}k x^k = \frac{1}{(1-x)^2}-1-x\\
\sum_{k=2}^{\infty}x^k = \frac{1}{1-x}-1-x
$$
and after some algebraic operations
$$
A(x) = \frac{1}{1-2x+3x^2}\left(\frac{1}{(1-x)^2}-\frac{1}{1-x}-a_0+a_1 x\right)
$$


Setting a script to run at boot on Ubuntu

Question: I need to kick off some processes on server boot, but I need them to run as a specific user.
At the moment I only have a load startup.sh's lying around.
Server is Ubuntu 8.04
Answer: As an alternative option, you can put it in the specific user's crontab, like this:
@reboot command-to-run

Edit: Before I forget, as root, you can edit a specific user's crontab with
crontab -u username -e

More documentation at Debian Administration.
Comment: You could also place a crontab fragment in /etc/cron.d.  Which I personally prefer over editing a users crontab.
Answer: The short answer is to put a
su username -c "/path/to/your/script.sh"

in the ubuntu equivalent of rc.local.
See this RcLocalHowto to prepare your system to have its local init script


Como desativar as Validations ao fazer um Submit no evento change de um DropDown

Question: Tenho uma modal com um dropdown, onde, sempre que for selecionada uma opção, é feito um submit e o modelo é enviado para a action para ser editado e depois é retornado. O problema é que as Validations atrapalham, é possível desativar as validations apenas para o evento change do meu dropdown? O botão Salvar deve funcionar normalmente, mas para o dropdown é necessário desativá-las.
$('#pessoaNatureza').on('change', function (e) {
  $(this).closest('form').submit();
});

Comment: Você pode passar um parâmetro executa validações e fazer dentro do método de submit uma validação para caso o executa validações for true executar, se não passar direto para a requisição http.

`$('#pessoaNatureza').on('change', function (e) {
  $(this).closest('form').submit(false);
}); `
Comment: Só que em todos os casos eu tenho que dar um submit, só que quando for pelo evento change, ele não valide os campos, isto é, ele deve enviar o form sem validar...
Answer: Pela documentação do plugin, você pode destruir a instância do validador com o método:
validator.destroy();

Onde validator é o nome da instância do plugin que você iniciou. Exemplo:
var validator = $("SELETOR DO FORMULÁRIO").validate();

Então seu evento change ficaria:
$('#pessoaNatureza').on('change', function (e) {
   validator.destroy();
   $(this).closest('form').submit();
});

O validador será desativado antes do submit e o formulário será submetido no evento change do dropdown.
Documentação do plugin
Exemplo:

var validator = $("#commentForm").validate();
$('#pessoaNatureza').on('change', function (e) {
   validator.destroy();
   $(this).closest('form').submit();
});

<form class="cmxform" id="commentForm" method="get" action="./">

   <select id="pessoaNatureza">
      <option value="">Selecione...</option>
      <option value="1">1</option>
      <option value="2">2</option>
   </select>

   <input id="cname" name="name" minlength="2" type="text" required>

   <button>Salvar</button>
</form>
Comment: Obrigado @sam!!!! Funcionou 100% Era isso mesmo que eu estava procurando e não encontrava. Você é fera!!!! :)
Comment: só agora que eu percebi um detalhe: Estou usando o Identity e meu sistema de login é aquele criado automaticamente quando se cria o projeto. A sua sugestão funciona perfeitamente, mas se eu estiver logado no sistema não. Você tem alguma ideia sobre o que isso poderia ser?
Comment: Mais tarde vou pro PC e a gente vê isso blz
Comment: Sem problemas companheiro!!! Quando vc puder!
Comment: A hora que quiser ver é só falar.
Comment: Vi agora sua msg companheiro... Estou on...
Comment: Blz... bora lá. Quando vc está logado o código não "destrói" o plugin? Como é isso?
Comment: Rapaz... é sinistro... Se eu estiver logado, o plugin não é destruído aparentemente. Eu não faço a mínima ideia do que poderia ser....
Comment: Vamos [continuar esta discussão no chat](https://chat.stackexchange.com/rooms/80846/discussion-between-jalber-romano-and-sam).


curl response says "HTTP version not supported", error 505

Question: I made request using curl, the response says that HTTP Version not supported, error 505. What are the steps to make HTTP Version supported.
After googling i get, the i should use curl --http2.0 to make it work, but my curl version is not supporting that option, as it is added in curl 7.33, whereas i am using curl with version: curl 7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/126.96.36.199 zlib/1.2.3 libidn/1.18 libssh2/1.4.2
Now, should i upgrade my curl or is there any other way to make it supported or am i missing something in my request(sorry, but i am not able to show the request).
If i need to upgrade it, then please specify me the way how to upgrade curl to version 7.33.0, i am not getting any proper way to do it.
Comment: As some answers have alluded to (and as was my case), you may first want to confirm there are no spaces in the url. If there are, replace them with `%20`
Comment: I think you need to upgrade your cURL. Curious what server you're talking to that is HTTP 2.0.
Comment: actually, i am assuming that it may be using HTTP 2.0, I dont know exactly what to do for getting out of that error
Comment: http://stackoverflow.com/questions/2757404/http-request-failed-http-1-1-505-http-version-not-supported-error this might help
Comment: @linux_fanatic : i have seen that question, but that is for php, whereas i am using curl commandline in linux, also that is not giving me proper idea, about what to do
Answer: for me the problem was mistake in the url (i had space there) after this issue it turn out that the curl complaining about bad http version was false alarm.
Comment: I had exactly the same problem - there was a space in the URL. I just need to remember that (unlike browser) curl passes the URL literally in the HTTP request. Replace spaces with `%20` and encode other special characters too.. js functions `encodeURI()` and `encodeURIComponent()` may be helpful here (as many implementations in other languages too)
Comment: @YouAreAwesome it might happend because the `postman` change the encoding of char like that while the `curl in bash` cannot make this kind of changes
Comment: but why this is just failing in curl if I used postman to call the same with spaces it worked pretty much well.
Answer: I got the same error today with Imperva Rest API curl commands.
Turned out that the URL that I was using had some path / (variables containing spaces in it's value) http://.../.../some path/or/some thing here/resource/sites and it didn't allow spaces.
To fix the issue, I used %20 to replace space characters (as per Imperva REST API v11.5 doc): http://.../.../some%20path/or/some%20thing%20here/resource/sites and then it worked.
Comment: Yes. In my case in a Shell script I was using quotes around the input that preserves spaces by default
Answer: this is a confusion created by curl error message. however this issue has nothing to be with HTTP version, most of the time is the space inside the curl URL. e.g. "adc.com/adc?a=hi there", so to fix this one just need to escape those chars according to rfc3986, like "adc.com/adc?a=hi%20there".
Answer: curl defaults to using HTTP 1.1 (which -v and --trace will show you), so if that is non-supported you probably need to switch to HTTP 1.0 using the --http1.0 option.
http 2 is hardly used in the wild yet by servers and is only supported by very recent curl versions .
Answer: For me it was while passing a half-coded "url" to Curl, particularly spaces were not encoded into "%20", while other staff was encoded properly. someone should either pass a "url" fully decoded or fully encoded.
Answer: I guess this is more or less just a message telling you that you http response is not well-formed in some way or may be in an unsupported http format.
I've had the same problem today: a server application I am woirking on would return an incomplete status message in its header, like
HTTP/1.1  500

instead of
HTTP/1.1 500 Internal Server Error

and curl would complain about an unsupported HTTP version. So it seems the message after the status code has to be filled in order to be valid http. Makes sense, but the message was a bit misleading. It is not necessarily about the HTTP version, it just says: malformed when validated against the http version spec.


Random variables inequality

Question: Let $X_1, X_2, ... , X_n$ be non-negative random variables on a probability space $(\Omega , P)$, each distributed as a random variable X, and let $S_n = \sum_{j=1}^{n} X_j$.
By considering appropriate events, deduce that
$$P (X_j \leq \frac{\lambda}{n}\;\text{for all j} ) \leq P (S_n \leq \lambda ) \leq P (X_j \leq \lambda \; \text{for all j} )$$
Hence show that if the $X_j$ are mutually independent, then
$$P^n (X \leq \frac{\lambda}{n}) \leq P (S_n \leq \lambda ) \leq P^n (X_j \leq \lambda )$$
By taking complements, show that
$$P^n (X \leq \frac{\lambda}{n}) \geq 1 - nP (X > \frac{\lambda}{n})$$
In a previous part of the question, I verified that $max\; X_j \leq S_n \leq n \;max X_j $ , however I could not see how to bring that forward to deduce the second pair of inequalities. Any help would be much appreciated.
Answer: The second pair of inequalities follows immediately from the first by the fact that $X_1,...,X_n$ are iid. You have, for example,
$$P(X_j \leq \lambda/n \text{ for all $j$}) = P(\cap_j\{X_j \leq \lambda/n \}) = \prod_j P(X_j \leq \lambda/n) = P^n(X \leq \lambda/n).$$
To get the first pair of inequalities, simply note that the first event in question implies the second, and the second event implies the third (by the non-negativity of $X_j$). Then use the fact that if $A$ implies $B$, then $P(A) \leq P(B)$.

Random variables inequality


Is it possible to append Series to rows of DataFrame without making a list first?

Question: I have some data I'm trying to organize into a DataFrame in Pandas.  I was trying to make each row a Series and append it to the DataFrame.  I found a way to do it by appending the Series to an empty list and then converting the list of Series to a DataFrame
e.g. DF = DataFrame([series1,series2],columns=series1.index)
This list to DataFrame step seems to be excessive.  I've checked out a few examples on here but none of the Series preserved the Index labels from the Series to use them as column labels.
My long way where columns are id_names and rows are type_names:

Is it possible to append Series to rows of DataFrame without making a list first?
#!/usr/bin/python

DF = DataFrame()
for sample,data in D_sample_data.items():
    SR_row = pd.Series(data.D_key_value)
    DF.append(SR_row)
DF.head()

TypeError: Can only append a Series if ignore_index=True or if the Series has a name

Then I tried
DF = DataFrame()
for sample,data in D_sample_data.items():
    SR_row = pd.Series(data.D_key_value,name=sample)
    DF.append(SR_row)
DF.head()

Empty DataFrame
Tried Insert a row to pandas dataframe
Still getting an empty dataframe :/
I am trying to get the Series to be the rows, where the index of the Series becomes the column labels of the DataFrame
Comment: I'm trying to add rows. The index of the Series should be the columns of the DataFrame.  So rows would be samples and columns would be features.
Comment: Did you try adding a name to the Series, as the error message suggests?
Comment: You need to read the error message.  It tells you to add a name to the Series, or use `ignore_index=True`.  If you do either of those, it works fine.
Comment: There is no error message, it just gives me an empty dataframe
Answer: Maybe an easier way would be to add the pandas.Series into the pandas.DataFrame with ignore_index=True argument to DataFrame.append(). Example -
DF = DataFrame()
for sample,data in D_sample_data.items():
    SR_row = pd.Series(data.D_key_value)
    DF = DF.append(SR_row,ignore_index=True)

Demo -
In [1]: import pandas as pd

In [2]: df = pd.DataFrame([[1,2],[3,4]],columns=['A','B'])

In [3]: df
Out[3]:
   A  B
0  1  2
1  3  4

In [5]: s = pd.Series([5,6],index=['A','B'])

In [6]: s
Out[6]:
A    5
B    6
dtype: int64

In [36]: df.append(s,ignore_index=True)
Out[36]:
   A  B
0  1  2
1  3  4
2  5  6

Another issue in your code is that DataFrame.append() is not in-place, it returns the appended dataframe, you would need to assign it back to your original dataframe for it to work. Example -
DF = DF.append(SR_row,ignore_index=True)

To preserve the labels, you can use your solution to include name for the series along with assigning the appended DataFrame back to DF. Example -
DF = DataFrame()
for sample,data in D_sample_data.items():
    SR_row = pd.Series(data.D_key_value,name=sample)
    DF = DF.append(SR_row)
DF.head()

Comment: Ah man, thanks! I didn't catch the DF = DF.append() That's way different than list appending.  Sorry I missed that.
Comment: **Warning**: df.append is now deprecated and you should try using pd.concat insted
Comment: you can use your `name` solution with `DF = DF.append(SR_row)` . Updated the answer with that example.
Comment: I saw that on "Insert a row to pandas dataframe" link above.  I'm trying to mess around with it. Maybe there is something that I'm not doing correctly.
Comment: I lost the Index labels. Is there any way to preserve this?
Comment: This is no longer valid due to append being deprecated. Please update to concat.
AttributeError: 'DataFrame' object has no attribute 'append'. Did you mean: '_append'?
Answer: DataFrame.append does not modify the DataFrame in place.  You need to do df = df.append(...) if you want to reassign it back to the original variable.
Comment: This is a deviation from python normal behavior and is worthwhile to always keep in mind.
Comment: Using `df.append` is deprecated since [pandas 1.4](https://pandas.pydata.org/docs/whatsnew/v1.4.0.html#deprecated-dataframe-append-and-series-append) and should be replaced by [`pd.concat`](https://pandas.pydata.org/docs/reference/api/pandas.concat.html)
Answer: append is deprecating so, the best choice would be to_frame().T
df1 = pd.DataFrame({'name':['john','mark'],'job':['manager','salesman'],'age':[43,23]})
ser1 = df1.iloc[-1]
pd.concat([df1,ser1.to_frame().T],ignore_index=True)

   name       job age
0  john   manager  43
1  mark  salesman  23
2  mark  salesman  23

Answer: Something like this could work...
mydf.loc['newindex'] = myseries

Here is an example where I used it...
stats = df[['bp_prob', 'ICD9_prob', 'meds_prob', 'regex_prob']].describe()

stats
Out[32]:
          bp_prob   ICD9_prob   meds_prob  regex_prob
count  171.000000  171.000000  171.000000  171.000000
mean     0.179946    0.059071    0.067020    0.126812
std      0.271546    0.142681    0.152560    0.207014
min      0.000000    0.000000    0.000000    0.000000
25%      0.000000    0.000000    0.000000    0.000000
50%      0.000000    0.000000    0.000000    0.013116
75%      0.309019    0.065248    0.066667    0.192954
max      1.000000    1.000000    1.000000    1.000000

medians = df[['bp_prob', 'ICD9_prob', 'meds_prob', 'regex_prob']].median()

stats.loc['median'] = medians

stats
Out[36]:
           bp_prob   ICD9_prob   meds_prob  regex_prob
count   171.000000  171.000000  171.000000  171.000000
mean      0.179946    0.059071    0.067020    0.126812
std       0.271546    0.142681    0.152560    0.207014
min       0.000000    0.000000    0.000000    0.000000
25%       0.000000    0.000000    0.000000    0.000000
50%       0.000000    0.000000    0.000000    0.013116
75%       0.309019    0.065248    0.066667    0.192954
max       1.000000    1.000000    1.000000    1.000000
median    0.000000    0.000000    0.000000    0.013116

Answer: Convert the series to a dataframe and transpose it, then append normally.
srs = srs.to_frame().T
df = df.append(srs)

Answer: Try using this command. See the example given below:

df.loc[len(df)] = ['Product 9',99,9.99,8.88,1.11]

df

Answer: This would work as well:
df = pd.DataFrame()
new_line = pd.Series({'A2M': 4.059, 'A2ML1': 4.28}, name='HCC1419')
df = df.append(new_line, ignore_index=False)

The name in the Series will be the index in the dataframe. ignore_index=False is the important flag in this case.


Unable to differentiate between words consisting of different Unicode letters in mysql and phpMyAdmin

Question: I am inserting a word using the following sql query from a php script.
$sql = "INSERT IGNORE into cb_words (word, user_id) VALUES('$word', $user_id)";

The problem arises in this particular scenario -
The cb_words table contains words in Bangla language.

word - আর which encoded to Unicode format is %u0986%u09B0
Another word - আঁর which encoded to Unicode format is %u0986%u0981%u09B0

As one may notice from the Unicode encoding for both the words they are almost similar with an additional letter in the second word.
Now, the table - cb_words already contains the second word, but when I am trying to insert the first word it fails.
It does not insert the word and simply says 0 rows inserted.
INSERT IGNORE into cb_words (word, user_id) VALUES('আর', 2)

When tried from PHPMyAdmin

Shockingly enough, when I search in the table for the word as -
SELECT * FROM `cb_words` where `cb_words`.`word` = 'আর'

The returned result is -

N.B: The table only has the word (2) as described above. and I am trying to insert (1)
So, despite the fact, these two words are not 100% identical, why does mysql fail to differentiate between the two?
I am adding the table structure in case it may be necessary:
Answer: Insert being ignored, is at my guess because your user_id is set to unique? can't tell from your screenshots and you're inserting with IGNORE supressing any errors. Remove the unique index from user_id.
You can change your collation to utf8_bin.
Created your table, locally:

similar question with some interesting reading: How can I enter data using non English (Bangla) language into this database table?
Comment: Thanks. The issue has been Fixed. I was doing the complete thing in a test environment locally. Thanks for the great help.
Comment: Thanks. Well if I want to change the collation for the table how may I do it without hurting the existing data?
Comment: export your db and try it in a test environment.
Answer: mysql> select 'আর'='আর' COLLATE utf8mb4_0900_ai_ci;
+-------------------------------------------------+
| 'আর'='আঁর' COLLATE utf8mb4_0900_ai_ci           |
+-------------------------------------------------+
|                                               1 |
+-------------------------------------------------+

That is, declare the column to have COLLATE utf8mb4_0900_ai_ci;
The two item you mention have these HEX values:
E0A686 E0A6B0 and E0A686 E0A681 E0A6B0
E0A681 is a non-spacing-modifier "BENGALI SIGN CANDRABINDU".  When collating with "Accent Insensitive" and (or?) "Case Insensitive", the two are considered equal.
If you want them to be treated as not-equal, use a different collation.


Alter comment links in blog teaser in drupal 7

Question: I would like to alter the comment links in the teaser view of the blog page. The code I have in node--blog.tpl.php at the moment is:
<?php if ($display_submitted): ?>

<?php $date = date("d F Y", $node->created); ?>
<?php print $date; ?>

 <?php $user = user_load($node->uid); ?>
        <?php $username=$user->name; ?>
<?php print t("By"); ?>
<a href="blogs/<?php print $username ?>"><?php print $username ?>

 <?php print ($comment_count); ?> <?php print render($content['links']['comment']); ?>

>

with css: .submitted ul li span {
        color: #fff;
        background: url("../images/blue-bubble.png") 0px 2px no-repeat;
        background-size: 100% 96%;
        padding: 0px 5px 5px 5px;
}
which produces:

but I want to make:

Any suggestions on this would be great!
Thanks
Answer: If I were you I'd hide the span content in CSS and add a tag for my background image like this:
Template:

    <?php print ($comment_count); ?>

    <?php print render($content['links']['comment']); ?>

CSS:
.submitted ul li span.comment-count {
  width: 16px; // or whatever
  height: 16px;
  background: url("../images/blue-bubble.png") 0px 2px no-repeat;
  background-size: 100% 96%;
  padding: 0px 5px 5px 5px;
}

.submitted ul li span.comment-hidden {
  display: none;
}

Comment: Thanks @Djouuuuh but the blue bubble is still sitting above the comment links. The html output wraps the comment links within a new ul.
Comment: Could you paste the generated code here ? I don't get it :/
Comment:
25

25 comments
Add new comment
  - the generated output
Comment: Just make the inside ul display inline or something. It's only css tricks at this point..
Comment: ul displaying inline has helped. Can live with the comment count being in light blue but initially wanted to make it appear as white inside the dark blue bubble. Thanks for your suggestions :)


How do I use a C# reserved keyword as a property name without the @ prefix?

Question: I need to design a class where one property name has to be return, but when I create a property name like return then I get an error.
After some research I found out that one can use a reserved keyword as a property or variable name by adding a @ prefix in C#, or by enclosing it in square brackets [] in VB.NET. For example:
var @class = new object();

So here is my class design code.
public class Person
{
    string _retVal;

    public string @return
    {
        get { return _retVal; }
        set { _retVal = value; }
    }
}

...
Person p = new Person();
p.@return = "hello";

Now I am not getting any error, but when I try to access property name like return then I need to write the name like @return, which I don't want. I want to access the property name like p.return = "hello"; instead of p.@return = "hello"; so I'd like to know if there is any way to do that?
Comment: Why bent on using reserved Keyword?
Comment: doesn't seem reasonable to me. You could use a "Return" name instead which is not a reserved keyword.
Comment: use `result` instead of `return`. Variable choice is your freedom.
Comment: There is a way to do this in C# using dynamic dispatch, however it would be over-complicating things to such a degree that I'd actually feel bad for suggesting it..
Comment: @phg I'm not certain but I think if you changed the property to `Return` you would also need to flag the assembly as *non* CLS compliant..
Comment: @MattDavey I agree, and I wouldn't call it `Return` myself if I worked on a library. But if it's just some small c# program which won't ever be called by anything else, and one insists on `Return`, who cares. Still, good point.
Answer: You can't. It is a reserved keyword. That means "you can't". Contrast to "contextual keywords" which usually means "we added this later, so we needed it to work in some pre-existing scenarios".
The moderate answer here is: use @return.
A better answer here is: rename your property. Perhaps ReturnValue.
There is also the option of, say, Return - but you might need to think about case-insensitive languages too.
Comment: +1 for considering case insensitive languages - lots of people forget about them when naming things
Answer: You can rename namespaces like this:
using Test = System.Diagnostics;

Answer: No way to achieve this because reserved Keywords are predefined, reserved identifiers that have special meanings to the compiler.
it's better you change name of property and use it in you code...something as given in @Marc answer...
Comment: ...then why repeat Marc's answer? :)


Kotlin's scopes - exposing single entry point

Question: Hello I have a simple question about kotln's scopes. I always design my modules to get an single entry point for module. It's just one (exact one) public class. I really care for this kind of hermetization. So imagine these 2 classes (please pay attention for packages):
package group.moduleA.service
internal class HiddenService() {

    fun someFunction {

    }
}

  package group.moduleA.service
    class Service(private val hiddenService: HiddenService) {

        fun someFunction {

        }
    }

So we have 2 classes in same package, one is public and the second one internal. You can imagine there is a lot of internal classes there. I would like to make visible just only Service class to another modules. Pretty common (for me) behavior in Java. In kotlin I get an error:
"public function exposes its internal parameter..."
Am I doing something wrong or it's just how Kotlin scopes works? How can I solve this problem?
Answer: You have to declare the constructor internal or private and provide another
function / constructor to create your service:
class Service internal constructor(private val hiddenService: HiddenService) {
    constructor() : this(HiddenService())

    fun someFunction() {

    }
}

Comment: Hmm can I use Spring's DI for this purpose?
Comment: class Service internal constructor(private val hiddenService: HiddenService) I think injection should work in this case. I will check it when get back to home, thanks :)
Comment: Oh great! Thanks a lot!
Answer: Dependency inversion principle is a good place to start:
internal class HiddenServiceImpl : HiddenService {
    override fun someFunction() {
    }
}

interface HiddenService {
    fun someFunction()
}

class Service(private val hiddenService: HiddenService) {
    fun someFunction() {
    }
}

Other option is to use factory method:
class Service private constructor(hiddenService: HiddenService) {

    companion object {
        fun create() = Service(HiddenService())
    }

    fun someFunction() {

    }
}

Comment: HiddenService interface is still visible outside module right?
Comment: If you want for someone to supply you the service, you'll have to make it public, as someone will be outside of your module. Spring DI is based on interfaces. Otherwise, use factory method pattern.
Comment: I want inject with Spring's DI internal class into public one. Requirement is to inject by constructor


Is it possible to add a wildcard CNAME into dnsmasq?

Question: I would like to let the DNS works in round robin way. So I have to put an entry into /etc/hosts. However, this does not allow wildcard domains.
Is there any way that I can do this in dnsmasq?
So I will get something like:
*.test.example.              0       IN      CNAME   mytest.example.
mytest.example.              0       IN      A       192.0.2.123

Answer: I've checked v2.77 and found that wildcard CNAME is working there. You should add to config cname=*.example.com,default.example.com, but your dnsmasq should be authoritative server for domain(in this case for example.com). It could be configured according man. In my case, I have such configuration:

/etc/hosts
127.0.0.1       default.example.com
127.0.0.2       default.example.com
127.0.0.3       default.example.com
127.0.0.4       default.example.com
127.0.0.5       default.example.com

/etc/dnsmasq.conf
cname=*.example.com,default.example.com
auth-server=example.com,eth0
interface-name=example.com,eth0
auth-zone=example.com,127.0.0.0/24,eth0

And result:
[root@centos-linux ~]# dig @127.0.0.1 *.example.com

; <<>> DiG 9.9.4-RedHat-9.9.4-29.el7_2.3 <<>> @127.0.0.1 *.example.com
; (1 server found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 6531
;; flags: qr rd ra ad; QUERY: 1, ANSWER: 6, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
;; QUESTION SECTION:
;*.example.com.         IN  A

;; ANSWER SECTION:
*.example.com.      600 IN  CNAME   default.example.com.
default.example.com.    600 IN  A   127.0.0.3
default.example.com.    600 IN  A   127.0.0.4
default.example.com.    600 IN  A   127.0.0.5
default.example.com.    600 IN  A   127.0.0.2
default.example.com.    600 IN  A   127.0.0.1

;; Query time: 0 msec
;; SERVER: 127.0.0.1#53(127.0.0.1)
;; WHEN: Mon Jun 05 16:28:13 MSK 2017
;; MSG SIZE  rcvd: 155

[root@centos-linux ~]# nslookup 2.example.com 127.0.0.1
Server:     127.0.0.1
Address:    127.0.0.1#53

Non-authoritative answer:
2.example.com   canonical name = default.example.com.
Name:   default.example.com
Address: 127.0.0.5
Name:   default.example.com
Address: 127.0.0.2
Name:   default.example.com
Address: 127.0.0.3
Name:   default.example.com
Address: 127.0.0.4
Name:   default.example.com
Address: 127.0.0.1

Comment: This is completely the wrong answer. A DNS record which resolves the literal query "*.domain.com" is not a wildcard record. This is a bad DNS record for a single domain called "*.domain.com" There seems to be some confusion in the DNSmasq documentation about this, as the author calls this out in his docs. The syntax "address=/domain.com/18.104.22.168" *does* create a wildcard domain, but only for a single IP. FWIW the wildcard form of the above question should resolve *any* sub-domain of example.com to the same address(es), but it does not.
Comment: just to clarify the above comment lost to formatting the asterisk as italics, this answer does not create a wildcard, it creates a record for a literal asterisk.example.com `*.example.com` CNAME to `example.com` which is not useful at all
Comment: I am aware of `address=` has wildcard. However, `address=` does not do round robin. It does not allow multiple IPs at all.
Comment: @Wang please check update, I found solution for `dnsmasq v2.77`
Comment: Thanks! WoW, just saw the change log, I am so lucky! Would you please remove the part in your answer before your update? It is apparently  irrelevant.
Comment: @JeffPuckett I'm read documentation wrong? `--cname as long as the record name is in the authoritative domain. If the target of the CNAME is unqualified, then it is qualified with the authoritative zone name. CNAME used in this way (only) may be wildcards, as in --cname=*.example.com,default.example.com`. According this part, this only one way to create wildcard domain in `dnsmasq`.
Comment: How would I create a wildcard CNAME that points to another domain, i.e. `cname=*.example,default.exmaple2`?


Django template: force choices on field and print display value with get_FOO_display()

Question: I want a model with 5 choices, but I cannot enforce them and display the display value in template. I am using CharField(choice=..) instead of ChoiceField or TypeChoiceField as in the docs. I tried the solutions here but they don't work for me (see below).
model.py:
class Language(models.Model):
    language = models.CharField(max_length=20,blank=False)
    ILR_scale = (
        (5, 'Native'),
        (4, 'Full professional proficiency'),
        (3, 'Professional working proficiency'),
        (2, 'Limited professional proficiency'),
        (1, 'Elementary professional proficiency')
        )
    level = models.CharField(help_text='Choice between 1 and 5', default=5, max_length=25, choices=ILR_scale)
    def level_verbose(self):
        return dict(Language.ILR_scale)[self.level]
    class Meta:
        ordering = ['level','id']
    def __unicode__(self):
        return ''.join([self.language, '-', self.level])

view.py
..
def index(request):
language = Language.objects.all()
..

mytemplate.html

      Languages

      {% regroup language|dictsortreversed:"level" by level as level_list %}

        {% for lan_list in level_list %}

          {% for lan in lan_list.list %}
          {{ lan.language }}: {{ lan.level_verbose }}{%if not forloop.last%},{%endif%}
          {% endfor %}

        {% endfor %}

From shell:
python3 manage.py shell
from resume.models import Language
l1=Language.objects.create(language='English',level=4)
l1.save()
l1.get_level_display()   #This is good
Out[20]: 'Full professional proficiency'

As soon as I create a Language instance from shell I cannot load the site. It fails at line 0 of the template with Exception Type: KeyError, Exception Value:   '4', Exception Location: /models.py in level_verbose, line 175 (which is the return line of the level_verbose method).
Also, I was expecting a validation error here from shell:
l1.level='asdasd'
l1.save()     #Why can I save this instance with this level?

And I can also save a shown above when using ChoiceField, meaning that I do not understand what that field is used for.
How to force instances to take field values within choices, and display the display value in templates?
Comment: it is looking for a string '4' not 4 in the dict. try - try . - `return dict(Language.ILR_scale)[int(self.leve)]`
Comment: You are mixing up strings and integers. If you wantto use integer keys you should probably use an `IntegerField` instead of a `CharField`. This will ensure that values are properly cast as integers before being saved.
Comment: yes, that fixes it. and I think ChoiceField is for forms, not for models
Answer: Well this is the common issue even when I started with django. So first let's look at django's feature that you can do it like below (Note: your choice case's value are going to be store as integer so you should use models.IntegerField instead of models.CharField):

get_FOO_display() : you are very near about this solution.

As you can see in documentation FOO is the field name of your model. in your case it is level so when you want to access corresponding choice value in shell or view you can call method with model instance as below as you have already mentioned:
`l1.get_level_display()`

but when you want to access it in template file you need to write it like below:
{{ l1.get_level_display }}

Now let's look at your method level_verbose() if you see quite again your model is a class and level_verbose() is the method you have created you can access self.ILR_scale directly just as you have used self.level

the main catch in you create dictionary of ILR_scale it's keys are Integer values (i.e. 1, 2, 3, 4, 5) but you have used CharField() to store the level values which returns you string values (i.e. '1', '2', '3', '4' or '5') and in python dictionary key 1 and '1' are both different one is integer and other is string. So you may change your model field to models.IntegerField() or you can access the keys like
dict(self.ILR_scal)[int(self.level)]

Comment: Of course! IntegerField works. I still find it strange that I can save l1.level=555, but then the site crashes. For this reason I think it would be safer to use validators. Now let me try get_FOO_display..
Comment: you are using choices to store values in model that means django is validating your result when you run your program in template; if you assign statically this way it won't properly handle any exception.
Comment: yes, {{ lan.get_level_display }} works too. It wasn't working for me because of the wrong CharField. Thank you
Answer: You can also use models.CharField  but you have to set field option choices to your tuples.
For exapmle:
FRESHMAN = 'FR'
SOPHOMORE = 'SO'
JUNIOR = 'JR'
SENIOR = 'SR'
LEVELS = (
    (FRESHMAN, 'Freshman'),
    (SOPHOMORE, 'Sophomore'),
    (JUNIOR, 'Junior'),
    (SENIOR, 'Senior'),
)
level = models.CharField(
    max_length=2,
    choices=LEVELS,
    default=FRESHMAN,
)

Then in your template you can use get_FOO_display() for example:
{{l1.get_level_display}}
See more in docs


Regex not start in zero if single digit

Question: I have a 5 textboxes that can input only numbers. I used /^[1-9][0-9]+$/, but what I need is if single digit is zero allow it.

Just like the picture above, I have 5 textboxes if 1 of the textbox is already equal the quantity the other textbox should allow a zero value. It can't be greater or lower than in quantity.
Comment: `/^([1-9][0-9]+|0)$/`?
Answer: Your best bet is:
/^\d+$/

Which will allow only a number of one or more digits.
Breakdown
/  start of regex
^  matches beginning of string
\d matches any digit
+  modifies the above to match one or more
$  matches the end of line
/  ends the regex
Answer: Try a or condition
/^([1-9][0-9]*|0)$/

Comment: I tried that, but why it not allowed single digit? Like 1-9?
Comment: @user3318208 try `/^([1-9][0-9]*|0)$/`

Regex not start in zero if single digit


What are good mathematical heuristics for choosing a good target function that always produce a stable linear regression solution?

Question: I am trying to approximate a target function $f$ in 1D with a polynomial linear regression (using software like python polyfit) in a specific interval $[lb,ub]$. I am specially interested in the underdetermined case (i.e. more unknowns than data points). However whenever I choose to approximate my target function with a high degree polynomial, I get that the vandermonde feature matrix $\Phi(x)$ is poorly condition or that it has a really low rank, usually smaller than the number of data points.
For me this seems rather counter intuitive because the that would mean that there are rows in my data set that are "repeated" in some sense. However, I usually choose functions that are not in the space of polynomials that are considered by the regression model. For example I've chosen:

really high degree (random polynomials)
cosine, sine curves
gabor like function $exp(-x^2)cos(2 \pi f x)$
or a linear combination of the above

If I choose say a target polynomial of degree $D_{target}$ then to exactly learn/approximate it I would have expected one needs at least $N=D_{target}+1$ points. With this intuition I thought that given a function that can be expressed as an infinite power series most sampling methods of point from the target function should lead to a $\Phi(x)$ that is full row rank (since we would need infinite polynomials to really figure out the coefficients). However, empirically I have noticed this is not the case. Most target functions lead to very ranks plots. If I plot the number of rows of $\Phi$ on the x-axis and the rank of $\Phi$ on the y-axis, I usually get that the rank increase and then stops increasing. The funny thing is that sometimes it stops before the # of data set points. For me this is really odd and I can't explain this. My guess is that:

Am might be just choosing really bad target functions (maybe not complex enough? or maybe in the case of a cosine there might be an issue its an even function? Though I've tried odd functions...)
or maybe my sampling method is not good (usually just equally spaced points)

Anyway, those are my thoughts. Does anyone have any suggestion on how to choose a target function such that the underdetermined system is always full rank?

Some example plots of the # parameters vs rank:
Comment: The name of the text is "An introduction to numerical linear algebra" by Cullen. You can get it on Amazon for \$30 or \$15 used
Comment: When you say underdetermined do you mean you are trying to find a polynomial with degree higher than the number of data points you have?
Comment: @DavidReed when I saw underdetermined, I mean that there are less rows than columns. So yes, I mean more degrees/monomials than data.
Answer: If I understand you correctly, given data points $(x_0,y_0),(x_1,y_1),\dots (x_m,y_m)$, you are trying to solve the matrix equation $(m \leq n)$:
$$\begin{bmatrix} x_0^n & x_1^{n-1} & \cdots & x_0 & 1 \\
 x_1^n & x_1^{n-1} & \cdots & x_1 & 1 \\ \vdots & \vdots & \vdots & \vdots & \vdots \\ x_m^n & x_m^{n-1} & \cdots & x_m & 1 \end{bmatrix} \begin{bmatrix}
 a_n \\ a_{n-1} \\ \vdots \\ a_1 \\ a_0\end{bmatrix} = \begin{bmatrix} y_0 \\ y_1 \\ \vdots \\  y_{m-1} \\ y_m \end{bmatrix}$$
Then your matrix will theoretically always have full row rank. However, when dealing with machines that are limited to finite precision,taking something to the 50th power can cause problems, especially if your $x_i$ are not whole numbers. It may also be a result of the algorithm you are using to determine the rank of the matrix. I took numerical linear algebra in college and as a general rule computers HATE matrices that are not orthonormal. I can't really speculate as to exactly what's going on without knowing what data you are using.

Edit- In response to your comment. When the columns of a matrix are orthornormal, the corresponding transformation preserves "lengths" and "angles". That is $\mathbf{Ax} \cdot \mathbf{Ay} = \mathbf{x} \cdot \mathbf{y}$ and $\Vert\mathbf{Ax}\Vert = \Vert \mathbf{x} \Vert$ As a result, the condition number of an orthogonal matrix turns out to be $1$. You used the term "Well-conditioned" above. This is what it refers to. It turns out you can bound certain errors that occur in terms of the matrix's condition number, I don't remember how, but you can have very drastic results occur even with 2 x 2 matrices because of the way the computer does arithmetic. Virtually every algorithm, even Gaussian elimination, has to be modified for use in a computer. Some people dedicate their entire adult life to finding ways to make computers and matrices get along I don't know much about the environment you are using. You might consider trying matlab as its really built for matrix manipulations. I will also look-up my textbook info and send it to you. Its pretty small, and will teach you how computers deal with floating point numbers and the errors that it can cause. Its a good balance of concrete examples of problems that arise, practical solutions and algorithms for them, and rigorous theorem proving.
Comment: the point of the question is that we are free to choose $f(x)$ such that the linear system is well behaved (or at least thats the intuition). Right now I am using the pseudo-inverse. Are we really always guaranteed to have full row rank? What if the function is $f(x) = k$ for some constant $k$...I think what you made me realize is that the main issue is that the rank of the data i.e. $\Phi(X)$ is independent of the target function since the only thing that has a rank is  $\Phi(X)$ the feature matrix...which is confusing me...why is $\Phi(X)$ not always full row rank?
Comment: $\Phi(X)$ is just the standard Vandermonde matrix (as you write I believe).  Is what you are saying that the computer is unable to find the rank of $\Phi(X)$ because of machine precision? Maybe the way I sample points on the given interval/hypercube matters...? I am sampling equidistant point usually over some interval. I think I've tried multiple intervals but mostly $[0,1]$. What do you think?
Comment: why do computers really prefer orthogonal stuff? can you provide an intuition (or link) if possible? :)
Comment: David, I did not perceive any irritation in your responses :). I'm grateful for ur engagement with me if anything. Anyway, back to maths. I guess it has to be a numerical issue since at around 30 it seems where the issue is arises...and machine precision seems to be $10^{-16}$ for 64 bit computers...I'm surprised its not at 16 though for values sampled btw [0,1]. I think what I am interested now is in computing $\Phi(X)$ such that its orthogonal only by sampling points. I wonder how easy that is to do...
Comment: yea it mostly mock data sampled equidistant inside of an interval, usually [0,1]. The target functions are the ones described in my original question (sine, cos, combinations of those, gabour, polynomials, etc)
Comment: @Pinocchio Also, the $10^{-16}$ refers to the mantissa. Computers store floating point nums in scientific notation. It can hold numbers way smaller than that, the $10^{-16}$ part refers to the maximum # of digits that can be in the X.XXXXX part of x.xxxxxx ee^{y}. After that the computer has to round, which is the source of most problems. for elements in that interval, high exponents of any numbers are going to be SUPER CLOSE
Comment: @Pinocchio my ti-89 counts $.5^{50} - .3^{50} $as being equal to $ .5^{50}. $So you can see how this can cause problems. You aren't going to be able to make the vandermonde matrix orthonormal at least for any choice of numbers because of the 1's btw. I'll look into a stable way to do this.


Synchronize with the correct time

Question: This may not be Drupal specific, but does Drupal have a module that can fetch the correct world time from any remote time server, which can help me in keeping the time shown in my Drupal site correct?
I don't want to use my system time which may be inaccurate.
Answer: If you are on shared hosting your hosting company should be responsible for keeping the time correct. If that's not happening contact them and ask why. If you are on VPS or your own private server you can set up a NTP client as tostinni recommended.
Answer: Time is a server job, so you should ensure your system time is correct rather than try to solve this with Drupal.
I'd recommend you to set up a NTP (Network Time Protocol) client on your server and have it synchronizes with a NTP server.
Here is the documentation for Ubuntu: Time Synchronisation with NTP.
PS: I think this question is off topic too ;)
Comment: Where are NTP servers? I mean which places are those located? Can't I use some php code to get latest time directly from those servers?
Comment: There's a lot of public NTP server, the tutorial for Ubuntu has one, here is a list of [public NTP servers](http://support.ntp.org/bin/view/Servers/WebHome). Doing this in php is [feasible](http://www.xenocafe.com/tutorials/php/ntp_time_synchronization/index.php) but cumbersome because after you retrieve the date, then what ? Drupal still relies on system time, so it's way easier to get your system time correct in the first place.
Comment: If I get the time from my shared hosting server which seems to have correct time sync with NTP, and convert it to any part in the world, will it correctly translate with respect to DST etc?
Comment: Drupal is the one who managed the Time Zones translation, so this should works flawlessly.

Synchronize with the correct time


Is $R=\{a+b\rho : a,b \in \Bbb{Z}\}$ a ring?

Question: Is $R=\{a+b\rho : a,b \in \Bbb{Z}\}$ a ring where $\rho=e^{2\pi i/5}$?
Since $R$ is a subset of the complex numbers we only have a few axioms to check. All but one of these are trivial (to me) but I can't seem to prove whether $xy \in R$ for all $x,y \in R$. Taking two arbitrary elements of the ring and multiplying gives $ac+bd\rho^2+(ad+bc)\rho$ which I'm not sure is in $R$ or not. I tried come up with a relation and got $\rho^5-1=0$ so I don't think I can get rid of the $\rho^2$ term.
So is it not a ring then?
Is this a valid counter example $\rho^2=e^{4\pi i/5} \notin R$.
Comment: Solve $a + b \rho = \rho^2$ for coefficients $a,b \in \Bbb R$, and find a *unique* solution.  Note that in this solution, $a$ and $b$ are not integers.
Comment: @DonAntonio "It is"?
Comment: Yes, it is...of you can prove that $\;\rho^2$ doesn't have the general form of an element in $\;R$ .
Comment: What do you mean to solve that equation?
Comment: That "of" there should have been an "if"...oh, well. And then yes: it *would* be a valid counter example.
Comment: How do you solve $a+b\rho=\rho^2$ for $a,b$?
Comment: @Sammy A geometric picture of the problem others are getting at with solving $a+b\rho$:  Look in the complex plane: $\rho^2$ does not lie on the lattice of points generated by $1$ and $\rho$, which is what you get if you are looking at $a+b\rho$ for integers $a,b$.
Answer: $$a+b\rho=\rho^2\implies \rho^2-b\rho-a=0$$
The above means $\;\rho\;$ is a root of the real (or integer, in fact) polynomial $\;x^2-bx-a\;$, and thus also $\;\overline\rho\;$ is a root, and then
$$\rho\overline\rho=-a\;,\;\;\rho+\overline\rho=b$$
Check the above implies
$$b=\rho+\overline\rho=2\,\text{Re}\,\rho=2\cos\frac{2\pi}5$$
and also
$$-a=\rho\overline\rho=|\rho|^2=1$$
but $\;=2\cos\frac{2\pi}5\notin\Bbb Z\;$ ...
Answer: $R$ is not a ring because it is not stable for multiplication. In fact
$$0+1\rho=\rho\in R$$ but $$(\rho)^2=(\cos\frac{2\pi}{5}+i\sin\frac{2\pi}{5})^2=\cos\frac{4\pi}{5}+i\sin\frac{4\pi}{5}\text{ (Moivre) }$$
In other words $$\rho=\cos 72^{\circ}+i\sin72^{\circ}\text { but } \rho^2=-\cos 36^{\circ}+i\sin36^{\circ}\notin R$$


If I repeatedly roll two fair six-sided dice, what is the probability that I will roll three 2s before I roll seven 6s?

Question: I would like to understand the math behind a basic racing game.
2d6 are rolled and the result advances the corresponding horse along the track (a roll of '7' would advance the #7 Horse).  To win the race, the #7 Horse needs to advance a total of 8 times - while the # 2 and #12 horses only need to advance three times.
How do I calculate the probability that the #2 horse will win the race?
[NOTE:  The 3/11 Horses must advance 4 times, the 4/10: 5 times, the 5/9: 6 times, 6/8 horses: 7 times.  These do not need to be included in the answer, but are included for completeness.]
I understand the basic probability of rolling two fair six-sided dice.
Comment: Just answering your title as a hint: You need to add the probability of your event happening given $n$ rolls, then you need to sum the result over all $n$, I believe. A very interesting question.
Answer: Start with the question in the title.
The probability that you throw 3 twos before 7 sixes is: that on the $3+7$ tries that matter, the first $3+7-1$ contain 3 twos and 6 sixes in some order, and try $3+7$ contains the seventh six.
$$\mathsf P(~\uparrow~) = \dbinom{3+7-1}{3}\dfrac{2^3\,5^7}{(2+5)^{3+7}}$$
... because the probability of obtaining a two given you obtain a two or a six is:$\frac{2/36}{2/36+5/36}$

Moving on, the probability that you throw 3 twos before 7 sixes or 3 twelves is: that on the tries that matter you do not throw all the twelves or all the sevens before the last two. Thus by the rule of complements, and the principle of inclusion and exclusion:
$$\mathsf P(~\uparrow~) = {1-\dbinom{3+7-1}{7}\dfrac{2^3\,5^7}{(2+5)^{3+7}}\\-\dbinom{3+3-1}{3}\dfrac{2^3\,2^3}{(2+2)^{3+3}}\\+\dbinom{3+7+3-1}{7+3}\dfrac{2^3(5+2)^{7+3}}{(2+5+2)^{3+7+3}}}$$

And, as you see, the probability that twos win the race will be rather complicated.


Getting the available template variables in a custom module

Question: I'm making a custom module that will hook into the default theme and override a template file. Like you can do in a custom theme. At this moment I can already use the template that was made in the custom module with the hook_theme() function, it shows in my page. But the available variables are not showing in here. (for example: content, attributes, ...).
Probably because the module does not recognise these variables? How do I pass these variables to the template in my custom module. I read about the function hook_preprocess_HOOK() but no luck so far.
This is the implementation of hook_theme().
/**
 * Implements hook_theme()
 */
function episode_data_theme($existing, $type, $theme, $path) {
        return [
        'paragraph__episode_content_question_slider' => ['variables' => [] ],
    ];
}

This is the content of the template.
{#
/**
 * @file
 * Default theme implementation to display a paragraph.
 *
 * Available variables:
 * - paragraph: Full paragraph entity.
 *   Only method names starting with "get", "has", or "is" and a few common
 *   methods such as "id", "label", and "bundle" are available. For example:
 *   - paragraph.getCreatedTime() will return the paragraph creation timestamp.
 *   - paragraph.id(): The paragraph ID.
 *   - paragraph.bundle(): The type of the paragraph, for example, "image" or "text".
 *   - paragraph.getOwnerId(): The user ID of the paragraph author.
 *   See Drupal\paragraphs\Entity\Paragraph for a full list of public properties
 *   and methods for the paragraph object.
 * - content: All paragraph items. Use {{ content }} to print them all,
 *   or print a subset such as {{ content.field_example }}. Use
 *   {{ content|without('field_example') }} to temporarily suppress the printing
 *   of a given child element.
 * - attributes: HTML attributes for the containing element.
 *   The attributes.class element may contain one or more of the following
 *   classes:
 *   - paragraphs: The current template type (also known as a "theming hook").
 *   - paragraphs--type-[type]: The current paragraphs type. For example, if the paragraph is an
 *     "Image" it would result in "paragraphs--type--image". Note that the machine
 *     name will often be in a short form of the human readable label.
 *   - paragraphs--view-mode--[view_mode]: The View Mode of the paragraph; for example, a
 *     preview would result in: "paragraphs--view-mode--preview", and
 *     default: "paragraphs--view-mode--default".
 * - view_mode: View mode; for example, "preview" or "full".
 * - logged_in: Flag for authenticated user status. Will be true when the
 *   current user is a logged-in member.
 * - is_admin: Flag for admin user status. Will be true when the current user
 *   is an administrator.
 *
 * @see template_preprocess_paragraph()
 *
 * @ingroup themeable
 */
#}
{% block paragraph %}

        {% block content %}
            {% set sliderDescription = content.field_slider_description|render|striptags %}
            {{ content.field_available_for }}

                {{ content.field_slider_question }}

{{ sliderDescription|length > 200 ? sliderDescription|slice(0, 200) ~ '...' : sliderDescription }}

                {{ 'Got it'|trans }}

                    {{ content.field_slider_question }}
                    {{ content.field_slider_description }}

        {% endblock %}

{% endblock paragraph %}

This is the debug output I get on the page.
Answer: According to your code, you are creating a custom template for a paragraph.
As you are trying to access variables, that will be added by the paragraph module, you'll have to tell the theming system that it is a paragraph.
You can do so by adding the 'paragraph' base hook. This way the template will get the variables provided by the paragraph (pre-)processing:
/**
 * Implements hook_theme()
 */
function episode_data_theme($existing, $type, $theme, $path) {
  return [
    'paragraph__episode_content_question_slider' => [
      'base hook' => 'paragraph',
    ],
  ];
}

Comment: Thank you so much, it works! I have been looking for this like everywhere but could not find an answer.


Show that $\lim_{n \to \infty}\frac{(3n^2−2n+1)\sqrt{5n−2}}{(\sqrt{n}−1)(1−n)(3n+2)} = -\sqrt{5}$

Question: I figured out that $\lim_{n \to \infty}\frac{(3n^2−2n+1)\sqrt{5n−2}}{(\sqrt{n}−1)(1−n)(3n+2)} $ is $-\sqrt{5}$ but I don't know how to prove it.
Comment: If you don't know how to prove it, you haven't figured out yet.
Comment: Hint:

Multiply the numerator and denominator by $\frac{1}{n^2\sqrt{n}}.$ Also, the answer should be $-\sqrt{5}$.
Comment: @LeonSot That's right. I will give it a try. Thanks!
Comment: A quick version: once verified that leading term have the same order, just look at the leading term coefficients.
Answer: Multiplying numerator and denominator with $\frac{1}{n^{5/2}}$, we get
$$\lim_{n\to\infty}\frac{(3-\frac{2}{n}+\frac{1}{n^2})(\sqrt{5-\frac{2}{n}})}{(1-\frac{1}{n^{1/2}})(\frac{1}{n}-1)(3+\frac{2}{n})}=\frac{3\times \sqrt 5}{-1 \times 3}=-\sqrt5$$
Since $\lim_{n\to\infty}\frac{1}{n}=0.$
Answer: The dominant terms in the numerator and denominator are both in $n^{5/2}$, hence the limit is finite. The corresponding coefficients are $3\sqrt5$ and $-3$. The ratio gives the answer.


Add SPF record for multiple systems in different servers

Question: I have a domain with a published SPF record (v=spf1 a mx ip4:xx.xxx.xxx.25 ~all) for it (e.g: xyz.com) also this domain has four subdomains:
sub1.xyz.com xx.xxx.xxx.29
sub2.xyz.com xx.xxx.xxx.30
sub3.xyz.com xx.xxx.xxx.31
sub4.xyz.com xx.xxx.xxx.32
and every one of those subs in a different server and different IP, when sending emails from subdomains (let's say for example firstname.lastname@example.com) the SPF check fails, in this situation should I publish individual SPF for every subdomain or include them in the main SPF record? and if I am supposed to include in the main, this must be done in a mechanism:

"v=spf1 a mx a:sub1.xyz.com a:sub2.xyz.com a:sub3.xyz.com a:sub4.xyz.com ip4:xx.xxx.xxx.25 ~all"

or include mechanism:

"v=spf1 mx a ip4:xx.xxx.xxx.25 include:sub1.xyz.com include:sub2.xyz.com include:sub3.xyz.com include:sub4.xyz.com ~all"

or mx mechanism:

"v=spf1 a mx mx:sub1.xyz.com mx:sub2.xyz.com mx:sub3.xyz.com mx:sub4.xyz.com ip4:xx.xxx.xxx.25 ~all
"
Answer: If the email is actually coming from the subdomain, that subdomain needs its own independent SPF record.
Comment: Yes! that true, it turned out that I did not do the right search so that I asked my question, Thanks for the help


How do I add a solo section (chord progression) to Real Book lead sheet?

Question: Is there an easy way (for beginners) to add a solo section to a piece of music, like a lead sheet from the Real Book?
I am thinking in terms of a chord progression. Would I repeat a progression from the main section or from a chorus, and improvise over that?
Answer: Listen to a recording of the piece and see what sections are used as a solo section. It differs from piece to piece, and my guess is that there is some flexibility with it, as long as the chord transitions from the end of the head of the piece back to the beginning of one of the sections is smooth. Say a piece has A, B, and C sections. Some will use all three as a solo. Some will use A as a bridge between solos and solo over B and C. Some will finish the head and return to just B or C for solos. It really depends on the piece and how close you want to stay to the original way it was done.
Answer: As Heather says, you can use any section you like to solo over. The verse is probably one of the best, as if it's a vocal piece, the singer can pick up straight after the verse you solo over, and into another chorus.
But, each piece will have its own geography, and will lend itself better to one particular part. For an inexperienced player, the part with fewest changes, or uncomplicated chords may be the best part.
Answer: Depends on what you are trying to accomplish. The question first seemed strange to me.  In Jazz it is typical to play the head, maybe twice, and the go - take off.  And yes, you typically just solo of the changes of the song playing through several times (the etiquette I learned was multiples of 2 cycles through the tune then hand it off).  So, if you are asking about soloing over changes you just lay your licks over the changes.
Now, the rhythm section can get creative in their interpretation of the changes with substitutions and cycle extensions but unless they're being mean they will stick to the structure and be "supportive".  Some artists set up different changes for a solo section.  A perfect example is West Coast Blues by Wes Montgomery.  The solo section has different chords (more intricate) but it still follows the 12 bar blues pattern, it does not go off into left field.
Lastly, if you are thinking of throwing in some avant garde middle section to Autumn Leaves or How High the Moon I don't have any advice.  That is beyond me.  If you are interested in understanding substitutes and cycle extensions you might try the following book:
How to Create Jazz Chord Progressions by Chuck Marohnic
My guitar teacher took me through that back in the 80s.
Comment: Great answer! +1 As a side note to viewers of this fine answer, playing the head twice usually only occurs over very short (12-bar) up-tempo tunes that only have 1 section. For example, we'd play the head twice on Blues for Alice, but not on Confirmation.
Comment: Thank you.  Good point about the 2 times through the head.  But to be fair Wes often played looong heads twice.  I've heard "How Insensitive" played twice through before solos.  Just saying.
Comment: It definitely could happen, but in general it'll be more rare. Are you thinking of this version? https://www.youtube.com/watch?v=guU_Dq-9VhY
Comment: I agree, it's rare.
Answer: General Form
When playing jazz standards from the Real Book, the improvisation always occurs over parts or all of the existing form/chord progression. The way these songs generally progress is:

play the melody
play solos
play the melody a final time

Improvising Over Faster Songs
If a song is faster ("up tempo"), solos typically occur over the entire form/over all of the chord changes. This is especially true for songs that are shorter in length (12 bars, 16 bars, etc.). If you're playing an up-tempo 12-bar blues, soloists will often improvise over many iterations of the form.
Improvising over Ballads
Ballads are played at slower tempos and typically have longer forms (e.g., AABA). For these songs, it's common for a single soloist to blow/improvise over just half of the song (AA). And after solos are finished, it's also common to start the final iteration of the melody at the bridge/B section, e.g., so that the final performance of the melody is simply BA instead of AABA.
Comment: Exceptions to these rules exist, but don't worry about those special cases until you've gained experience with the basics (soloing over the entire form and starting/ending the song with the melody).


What is the correct status code after testing if an e-mail address exists in the database or not?

Question: We are using a specific endpoint on our API to test if an e-mail address is already registered in our database. When it's not, what would be the right status code to return to the client ?
We cannot take a decision between 404, 204 and 200. There are a couple of articles over the net but all state pros and cons but it's not very clear.
Answer:
200 says that the request was successful
204 says that the request was successful AND that the message body included in the response is 0 bytes long.
404 says that there is no current implementation associated with the requested resource

Which of these is correct really depends on your resource design.
Consider a database query with a where clause -- if there are no matching rows, then you get SUCCESS, with an empty result set.  So the analogous thing in a HTTP response would be a 2xx status code, and a body that describes an empty set.
If you were using a JSON List as your representation of the set, then the representation would be two bytes long [], and a 200 status code would be appropriate.  If you were using a json lines representation, with each record on its own line, then with no records you would have no lines, therefore a 0 byte representation and 204 would be a good choice.
What about a case where we have a simple web page, that tells you if the email address is registered or not?  If it's registered, the server responds with a 200 message and a html document that tells you about the registration.  If it isn't registered, then you get an html message telling you that the email address isn't registered... and a 200, because we were able to find the current representation of the resource.
And 404?  404 indicates to the client that there appears to have been a spelling error in the target-uri of the http request -- that there isn't even nothing to find.
It may help to understand that status codes are metadata about the HTTP response, which is to say that they are part of the application domain of transferring documents over a network, not about the business domain.  They are there so that generic components, like caches, can do interesting things without needing to know any specifics about the domain in question.
Our web API is a facade to make our domain model look like a boring document store.


Prove that the integral of a sequence converges uniformly

Question: I've been stuck on this problem for a bit now:
Let $g$ and $f_0$ be continuous functions on $[0,1]$. Define the sequence on $[0,1]$ by
$$f_n(x) = \int_0^t g(t)f_{n-1}dt.$$
I have to prove that the sequence is converges uniformly.
Here are my thoughts: I know $f_n$'s are continuous and I also tried to solve this question using the $\epsilon-\delta$ definition for continuity and uniform convergence without any luck.
Any hint?
Answer: I suppose that the upper limit in the integral is $x$ and not $t$.
Let $G$ and $F$ be constants such that $|g(x)|\le G$ and $|f_0(x)|\le F$ for all $x\in[0,1]$. Then
$$\begin{align}
|f_1(x)|&\le\int_0^xG\,F\,dt=G\,F\,x\\
|f_2(x)|&\le\int_0^xG^2\,F\,t\,dt=\frac{G^2\,F}{2}\,x^2\\
|f_3(x)|&\le\int_0^x\frac{G^3\,F}{2}\,t^2\,dt=\frac{G^3\,F}{2\cdot3}\,x^3\\
\end{align}$$
Can you see a pattern?
Comment: The upper limit is t, but I thought was a mistake in the mock exam too..And yes, I can to also to what is converges now! thanks!


Is neck pain a common side-effect when diving?

Question: I've been getting a lot of tightness in my shoulders and neck after doing diving practice. I wonder if it's because of the impact when I hit the ground and my head shakes a bit.
Are there any ways to lessen the impact?
Answer: It's all about the way you fall (technique). Players who try to naturally brace themselves when diving will feel pain in the shoulder and neck.If your technique is good you shouldn't feel pain in your neck and shoulders. Soreness in your hips are normal even with good technique though!


HighCharts : Shared Tooltip with shared Data LABELS (in Series)

Question: I have a simple HighChart here ----> jsFiddle
By having a Serie like this:
series: [{
    name: 'Cities',
    data: [
        ["Paris", 29.9],
        ["London", 71.5],
        ["New York", 106.4]
    ]
},
{
    name: 'Universities',
    data: [
        ["Cambridge", 17.5],
        ["Oxford", 1.5],
        ["MIT", 16.4]
    ]
}
]

There a shared Tooltip (a hover tooltip to display both series information in a single box) can only display the TOP NAME of the Series. Instead,

I want the respective CITY name and UNIVERSITY name in the TOOLTIP box.

For example, it should show:
----------------------
| • Paris: 29.9     |
| • Cambridge: 17.5 |
----------------------

Or, at least it should show:
------------------------------------
| • Cities: 29.9 (Paris)           |
| • Universities: 17.5 (Cambridge) |
------------------------------------

Some thing like that.
(But now it is just showing the Serie Name)
How to do it please?
Answer: You can use the formatter function of tooltip for this.
http://api.highcharts.com/highcharts#tooltip.formatter
Demo: http://jsfiddle.net/robschmuecker/qSfJw/2/
$(function () {
    $('#container').highcharts({
        tooltip: {
            shared: true,
            formatter: function () {
                console.log(this.points);
                return this.points[0].key + ' : ' + this.points[0].y + '
' + this.points[1].key + ' : ' + this.points[1].y;
            }
        },
        series: [{
            name: 'Cities',
            data: [
                ["Paris", 29.9],
                ["London", 71.5],
                ["New York", 106.4]
            ]
        }, {
            name: 'Universities',
            data: [
                ["Cambridge", 17.5],
                ["Oxford", 1.5],
                ["MIT", 16.4]
            ]
        }]
    });
});


Python: Print a generator expression's values when those values are itertools.product objects

Question: I'm trying to dig into some code I found online here to better understand Python.
This is the code fragment I'm trying to get a feel for:
from itertools import chain, product

def generate_groupings(word_length, glyph_sizes=(1,2)):
    cartesian_products = (
        product(glyph_sizes, repeat=r)
        for r in range(1, word_length + 1)
    )

Here, word_length is 3.
I'm trying to evaluate the contents of the cartesian_products generator. From what I can gather after reading the answer at this SO question, generators do not iterate (and thus, do not yield a value) until they are called as part of a collection, so I've placed the generator in a list:
list(cartesian_products)
Out[6]:
[<itertools.product at 0x1025d1dc0>,
 <itertools.product at 0x1025d1e10>,
 <itertools.product at 0x1025d1f50>]

Obviously, I now see inside the generator, but I was hoping to get more specific information than the raw details of the itertools.product objects. Is there a way to accomplish this?
Comment: `itertools.product` objects don't expose anything useful for introspection. You could iterate over them to look at what they produce, but then they're exhausted and unuseable for the rest of the algorithm... not that it matters, because you already exhausted `cartesian_products`.
Answer: if you don't care about exhausting the generator, you can use:
list(map(list,cartesian_products))

You will get the following for word_length = 3
Out[1]:
[[(1,), (2,)],
 [(1, 1), (1, 2), (2, 1), (2, 2)],
 [(1, 1, 1),
  (1, 1, 2),
  (1, 2, 1),
  (1, 2, 2),
  (2, 1, 1),
  (2, 1, 2),
  (2, 2, 1),
  (2, 2, 2)]]


Simple ? JSON analyse with AutoIt

Question: I would like to use the following JSON which I read out from an API in AutoIt:
[
  {
    "id": 2336916545,
    "item_id": 85016,
    "price": 103,
    "quantity": 250,
    "created": "2020-06-07T18:13:46+00:00"
  },
  {
    "id": 2336916458,
    "item_id": 85016,
    "price": 103,
    "quantity": 250,
    "created": "2020-06-07T18:13:34+00:00"
  },
  {
    "id": 2336916352,
    "item_id": 85016,
    "price": 103,
    "quantity": 250,
    "created": "2020-06-07T18:13:22+00:00"
  }
]

What is the easiest way to multiply "price" and "quantity" and get a total sum for the array?
Thanks for your help!
Comment: Can you update your question to show what have you tried?
Answer: You can use the Ward's work and its library JSON.au3 to deal with JSON file.
Install AGS-wrapper-json
To add easyly this library in your AutoIt project, you can use the package AGS-wrapper-json : https://www.npmjs.com/package/@autoit-gui-skeleton/ags-wrapper-json. An AGS-wrapper is a simple wrapper for an another library created by another team/developer integrated in AGS framework. More information about dependency manager for AutoIt in AGS
To install it :
λ  yarn add @autoit-gui-skeleton/ags-wrapper-json --modules-folder vendor

Finally to use this library in your AutoIt program, you need to include this library in the main program. There is no need for additional configuration to use it.
#include './vendor/@autoit-gui-skeleton/ags-wrapper-json/JSON.au3'

Decode a JSON file from local
According to Ward's documentation.

The most JSON data type will be decoded into corresponding AutoIt variable, including 1D array, string, number, true, false, and null. JSON object will be decoded into "Windows Scripting Dictionary Object" retuned from ObjCreate("Scripting.Dictionary"). AutoIt build-in functions like IsArray, IsBool, etc. can be used to check the returned data type. But for Object and Null, Json_IsObject() and Json_IsNull() should be used.
If the input JSON string is invalid, @Error will be set to $JSMN_ERROR_INVAL. And if the input JSON string is not finish, @Error will be set to $JSMN_ERROR_PART.

;====================================================================================
; Decode JSON from a given local file
;
; @param $jsonfilePath (string)
; @return $object (object), instance return by json_decode
;====================================================================================
Func json_decode_from_file($filePath)
    Local $fileOpen, $fileContent, $object

    $fileOpen = FileOpen($filePath, $FO_READ)
    If $fileOpen = -1 Then
        Return SetError(1, 0, "An error occurred when reading the file " & $filePath)
    EndIf
    $fileContent = FileRead($fileOpen)
    FileClose($fileOpen)
    $object = Json_Decode($fileContent)

    Return $object
EndFunc

Get values from a json object
To work with $jsonObject, the return of json_decode_from_file, you can use Json_Get function. To select a JSON variable, both dot notation and square bracket notation can be supported.
For example :
Local $file = @ScriptDir & "\assets\DROIDS.json"
Local $jsonObject = json_decode_from_file($file)

; With dot notation
Local $project = Json_Get($jsonObject, '.project')     ; Listing droids
Local $name = Json_Get($jsonObject, '.author.name')    ; Luke
Local $mail = Json_Get($jsonObject, '.author.mail')    ; email@example.com
local $test = Json_Get($jsonObject, '.droids[1].name') ; BB8

; With array notation
Local $project2 = Json_Get($jsonObject, '["project"]')
Local $name2 = Json_Get($jsonObject, '["author"]["name"]')
Local $mail2 = Json_Get($jsonObject, '["author"]["mail"]')
local $test2 = Json_Get($jsonObject, '["droids"][1]["name"]')

Work with an object collection, and iterate its items
To iterate values from an array json
Local $file = @ScriptDir & "\assets\DROIDS.json"
Local $jsonObject = json_decode_from_file($file)

; Check if exists an item droid into the collection `droids`
Local $droids = Json_Get($jsonObject, '.droids')
If UBound($droids) = 0 Then
    Return SetError(3, 0, "Array attribute 'droids' is empty.")
EndIf

; Iterate items collection to store values into an array
Local $array[UBound($droids)][3]
For $i = 0 To UBound($droids) - 1 Step 1
    $array[$i][0] = Json_Get($jsonObject, '.droids' & '[' & $i & '].name')
    $array[$i][1] = Json_Get($jsonObject, '.droids' & '[' & $i & '].type')
    $array[$i][2] = Json_Get($jsonObject, '.droids' & '[' & $i & '].size')
Next

Comment: For multiplication ... I have no idea :p
Comment: Thank you very much. I will test this and give you more information when it's done :)

Simple ? JSON analyse with AutoIt


Six points on an ellipse: generalizing Conway's Circle Theorem

Question: Can you prove the claim given below?
Inspired by Conway circle theorem I have formulated the following claim:

Let $a,b,c$ be the side lengths and $\alpha,\beta,\gamma$ inside angles of the triangle $\Delta ABC$ . Let $P$ be a point on the extension of the segment $BA$ beyond $A$ such that $AP=\frac{a}{2}$ , let $Q$ be a point on the extension of the segment $CA$ beyond $A$ such that $AQ=\frac{a}{2}$ , let $R$ be a point on the extension of the segment $CB$ beyond $B$ such that $BR=\frac{b}{2}$ , let $S$ be a point on the extension of the segment $AB$ beyond $B$ such that $BS=\frac{b}{2}$ , let $T$ be a point on the extension of the segment $AC$ beyond $C$ such that $CT=\frac{c}{2}$ and let $U$ be a point on the extension of the segment $BC$ beyond $C$ such that $CU=\frac{c}{2}$ . Construct an ellipse $e$ through points $P,Q,R,S,T$ . If $\alpha \le \beta \le \gamma$ or $\beta \le \gamma \le \alpha$ or $ \gamma \le \alpha \le \beta$ then $U \in e$ .

GeoGebra applet that demonstrates this claim can be found here.
Comment: Did you find the surrounding Conway conic's eccentricity $e$ as a function of such extensions $ ( pa,pb,pc) $  with a const $\; p?$ So that if $p=\frac12, e=? $
Comment: And if $p\rightarrow \infty, e=0$ again?
Comment: If by "$U\in e$" you mean that $U$ is *on the curve*, not merely *in the bounded region*, then my calculations indicate that $U\in e$ if and only if $\triangle ABC$ is isosceles. There seems to be an interesting generalization when allowing the extensions to be arbitrary ratios; I'll post about it in a bit.
Comment: @Blue Isn't an ellipse a plane curve by the definition...
Comment: @PeđaTerzić: *"Isn't an ellipse a plane curve by the definition[?]"* ... Well, people can be a little loose with the usage, so it's helpful to double-check. Your applet, for instance, reports "$U\in e =  \text{true}$" for $\alpha\approx 10^\circ$ and $\beta\approx 165^\circ$, when $U$ is *visibly* in the ellipse's interior; this could be due to round-off error in your calculations or some graphical glitch in GeoGebra, or it could be that you intended the interior to count. So, I wanted to clarify.
Comment: @Blue I see....
Comment: @PeđaTerzić, Is that what [*Reference 3*](http://forumgeom.fau.edu/FG2013volume13/FG2013volume13.pdf#page=195) on the link of Conway circle theorem?
Comment: @NgChungTak Yes, this claim is inspired by Conway circle theorem....
Comment: @Narasimham I don't understand your question...
Answer: Given non-degenerate $\triangle ABC$, define points $A^+$, $B^+$, $C^+$, $A^-$, $B^-$, $C^-$ via
$$\begin{align}
A^+ = A + \alpha^+(B-A)\frac{a}{c} &\qquad A^-=A+\alpha^-(C-A)\frac{a}{b} \\[4pt]
B^+ = B +  \beta^+(C-B)\frac{b}{a} &\qquad B^-=B+ \beta^-(A-B)\frac{b}{c} \\[4pt]
C^+ = C + \gamma^+(A-C)\frac{c}{b} &\qquad C^-=C+\gamma^-(B-C)\frac{c}{a} \\[4pt]
\end{align} \tag{1}$$
for arbitrary values $\alpha^{\pm}$, $\beta^{\pm}$, $\gamma^{\pm}$. (That is, $A^+$ and $A^-$ are the translates of $A$ in directions $\overrightarrow{AB}$ and $\overrightarrow{AC}$ by signed distances $a\alpha^+$ and $a\alpha^-$, respectively.) Conway considers the case $\alpha^{\pm}=\beta^{\pm}=\gamma^{\pm}=-1$; OP considers $\alpha^{\pm}=\beta^{\pm}=\gamma^{\pm}=-1/2$. (In the cases where  $\alpha^{\pm}=0$, $\beta^{\pm}=0$, or $\gamma^{\pm}=0$, some pair of the six points coincide with the corresponding vertex of the triangle.)
Via coordinates, it's not difficult (using, say, this determinant) to show that the points $A^\pm$, $B^\pm$, $C^\pm$ lie on a common conic (which may-or-may-not be an ellipse) if and only if
$$\begin{align}
0 &=  (a - (b^+ + c^-)) \; (b - (c^+ + a^-))\;(c - (a^+ + b^-)) \\[4pt]
&\phantom{=}\cdot\left(
\alpha^+ \beta^+ \gamma^+ (a - c^-) (b - a^-) (c - b^-) - \alpha^- \beta^- \gamma^- (a - b^+) (b - c^+) (c - a^+)
\right)
\end{align} \tag{2}$$
where $a^\pm := a\alpha^\pm$, $b^\pm := b \beta^\pm$, $c^\pm:= c \gamma^\pm$.
Each of the first three factors of $(2)$ corresponds to a trivial case where two of our six points coincide (as the translated distances of two vertices add to the length of the side between them). The interesting condition, therefore, is
$$\alpha^+ \beta^+ \gamma^+ (a - c^-) (b - a^-) (c - b^-)
\;=\; \alpha^- \beta^- \gamma^- (a - b^+) (b - c^+) (c - a^+)
 \tag{$\star$}$$
For $\alpha^\pm=\beta^\pm=\gamma^\pm=:\lambda \neq 0$ (the zero case is trivial), this reduces to
$$(1+\lambda)(a - b) (a - c) (b - c) = 0 \tag{$\star\star$}$$
Thus, for $\lambda=-1$, the six points lie on the ellipse, regardless of the shape of the original triangle; this is part of Conway's Theorem. (Showing that the conic is actually a circle in this case take a little more work.)  For non-zero $\lambda\neq -1$ (in particular for OP's $\lambda=-1/2$), the six points lie on a common conic if and only if $\triangle ABC$ is isosceles. $\square$
Comment: Your result was also my first assumption, but the GeoGebra applet led me to the wrong conclusion.
Comment: @PeđaTerzić: Approximate computations? All calculators are subject to errors using "floating point" (ie, decimal) arithmetic; and I suspect GeoGebra's "element of" tester allows some wiggle room. ... It *is* a little surprising to me that the construction isn't *visibly* incorrect for less-dramatic triangles. A proper error analysis may be in order, but a definitive answer would seem to require knowing exactly how GeoGebra performs its internal calculations, both in generating its conic equations and in doing its "element" tests. I'll leave that investigation to others.
Answer: Assume the claim is true.
Let us say we are able to construct an ellipse $e$ with points $P, Q, R, S, T, U$ lying on it as described. We also have the Conway circle $k$ of the triangle $\triangle ABC$. By definition $P, Q, R, S, T, U$ lie on $k$. However, the maximum number of intersection points between a circle $k$ and ellipse $e$ is 4, if $e \ne k$ and hence impossible to have $P, Q, R, S, T$ lie on both $e$ and $k$. So, we have a contradiction.
Therefore, the original claim must be false.
Comment: The $P$, $Q$, $R$, $S$, $T$, $U$ that may-or-may-not all lie on OP's conic $e$ definitely **do not** lie on the Conway Circle. They are the *midpoints* of segments determined by the Conway points and the vertices of the triangle.