What is the derivative of $|x^3|$?

Question: Let $f(x)=|x^3|$.
I found two ways to differentiate this function. Apparently method 2 is wrong, but I cannot figure out why. So the question is, is method two wrong and why?
Method 1 (according to wolfram mathematica)
$$f(x)=|x^3|=|x|^3$$
$$f'(x)=3|x|^2 \text{Sgn}(x)=3|x^2|\frac{x}{|x|}=3|x|x$$
Method 2 (using chain-rule)
$$f'(x)= \text{Sgn}(x^3)\cdot3x^2$$
With method 2 it seems $f'(0)$ is not defined, since $\text{Sgn}(0)$ is not defined. However, this is not true according to WolframAlpha.
Comment: Using the limit definition of the derivative might help.
Comment: You must come to the same conclusion with Method 1 as well !
Comment: Added note: as a function of a complex variable, $|x^3|$ is not differentiable anywhere.
Answer: This is a nice question as it highlights an important subtlety in the chain rule, although it's a subtlety that comes up rarely. The chain rules tells us that
$$
\frac{d}{dx} (f \circ g)(a) = f'(g(a)) \cdot g'(a),
$$
provided that $g$ is differentiable at $a$ and $f$ is differentiable at $g(a)$.
It may happen that $f \circ g$ is differentiable at $a$ even if one of these hypotheses does not hold. This question is an example. Here, $g(x) = x^3$ and $f(x) = |x|$. Since $f$ is not differentiable at $g(0) = 0$, the hypotheses of the chain rule do not apply at $0$ and it is illegitimate to use it to conclude anything about the derivative there. Therefore, you must find another way. As you see, when we compute in the other direction, we see that in fact the derivative exists at the origin and is zero.
Comment: that's right, the first method is not a rigorous proof. To rigorously prove this, you should start from the definition of the derivative as a limit.
Comment: @ImreVégh it is not rigorous, but I would say it's not so bad. To make it rigorous would take a little work though! (What is being used is that if a function $f$ is differentiable away from a point $a$, and the function $f'$ has a limit at $a$, then you can conclude that $f$ is differentiable at $a$ and $f'(a)$ is equal to that limit.)
Comment: So strictly speaking the first method is also wrong, since that also involves dividing by zero in case of x=0?
Comment: Yeah, but still wolframalpha gives that solution (method 1) including a step-by-step explanation where they cancel out the |x| in the nominator and the denominator
Comment: @ImreVégh (in the little lemma I mention in the previous comment, you also need the hypothesis that $f$ is continuous at $a$.)
Answer: Undisputably,
$$\lim_{x\to0^+}\frac{|x^3|-|0^3|}{x-0}=\lim_{x\to0^+}\frac{x^3}x=\lim_{x\to0^+}x^2=0,$$
$$\lim_{x\to0^-}\frac{|x^3|-|0^3|}{x-0}=\lim_{x\to0^-}\frac{-x^3}x=\lim_{x\to0^-}-x^2=0.$$
Other $x$ cause no real difficulty.
Comment: You might want to add for completeness of the answer that $f'(x) = \pm 3x^2$ away from $0$ and that only issue might arise at $0$, thus needs to be resolved as you wrote.
Answer: I learned that, ...

... whenever you want to compute the derivative of a function involving an absolute value, first convert the absolute value into its definition
  $$
|x| = \sqrt{x^2} = (x^2)^{\frac{1}{2}}.
$$

So, $f$ can be re-written as
$$
f(x) = |x^3| = ((x^3)^2)^{\frac{1}{2}}.
$$
If we now apply the chain rule multiple times to compute its derivative, we obtain
$$
\begin{eqnarray}
\dfrac{df(x)}{dx}
&=& \left( \dfrac{df(x)}{d((x^3)^2)} \right) \cdot \left( \dfrac{d((x^3)^2)}{dx} \right) \\
&=& \left( \dfrac{df(x)}{d((x^3)^2)} \right) \cdot \left( \dfrac{d((x^3)^2)}{d(x^3)} \right) \cdot \left( \dfrac{d(x^3)}{dx} \right) \\
&=& \left( \dfrac{1}{2} \dfrac{1}{((x^3)^2)^{\frac{1}{2}}} \right) \cdot \left( 2x^3 \right) \cdot \left( 3x^2 \right) \\
&=& \dfrac{3x^5}{((x^3)^2)^{\frac{1}{2}}}.
\end{eqnarray}
$$
Now there are two options of how to proceed:

Combine $(x^3)^2 = x^6$ to yield $\dfrac{df(x)}{dx} = \dfrac{3x^5}{\sqrt{x^6}}$.
Or use again the definition of the absolute value to yield $\dfrac{df(x)}{dx} = \dfrac{3x^5}{|x^3|}$.

The computer algebra system Maple seems to prefer the first option; I would prefer the second one, because we started with an absolute value in the original function and end with an absolute value in its derivative. Nonetheless, both are equivalent.
Comment: Still in your answer f'(x) is not defined for x=0, while it should be f'(0)=0, how come?
Comment: No, as you said: *$\dfrac{df(0)}{dx}$ is not defined*. You can see that the expression $\dfrac{3 \cdot 0^5}{|0^3|}$ would lead to a division by zero. Consequently, $\dfrac{df(0)}{dx} = 0$ is a *wrong*. It should *not* be a true statement.
Comment: I think it is defined, since the left and right limit of f'(x) for x->0 are both 0
Comment: Well, the point is that the *undisputable* computation of the limit above is false.
$$
\lim_{x \to 0} \dfrac{|x^3| - |0^3|}{x - 0} = \lim_{x \to 0} \dfrac{|x^3|}{x} = \dfrac{ \lim_{x \to 0} |x^3| }{ \lim_{x \to 0} x } = \dfrac{0}{0}.
$$
So, we apply l'Hospitals rule and compute
$$
\lim_{x \to 0} \dfrac{\frac{1}{2}\frac{1}{|x^3|}}{1} = \lim_{x \to 0} \dfrac{1}{2}\dfrac{1}{|x^3|}.
$$
But this limit diverges!!!

What is the derivative of $|x^3|$?


Android exibir uma tela só na primeira vez que abrir o aplicativo

Question: Existe uma maneira de rodar uma tela de especifica (como por exemplo de identificação) na primeira vez que o aplicativo for aberto? E toda vez que eu lançar uma atualização no google play, as pessoas que já possuem o aplicativo instalado e abrirem novamente após a atualização, a tela de identificação será apresentada novamente? existe uma forma de diferenciar aqueles que fazem o download para aqueles que recebem uma atualização?
Answer: Use as SharedPreferences para guardar a versão da app.
Na actividade principal, no método oncreate(), obtenha essa informação e actue em conformidade.
String appVer = "versão actual da sua app";
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
String appVer = preferences.getString("lastAppVer","");

if(lastAppVer == ""){
    // A aplicação foi instalada pela primeira vez
    // Exibir tela
}
else if(lastAppVer != appVer){
    // A aplicação foi actualizada
    // Exibir tela
}

Na actividade da tela a ser exibida apenas uma vez guarde a versão da sua app nas SharedPreferences
String appVer = "versão actual da sua app";
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
preferences.edit.putString("lastAppVer",appVer).apply();

Comment: Muito obrigado ramaral!
Comment: o context meu fica em vermelho, pq?
Comment: @EvandroAguiar `context` é um objecto do tipo *Context*. Se estiver a usar o código numa *Activity* substitua por `this`.


Deploying to Heroku with submodule: Heroku didn't install the submodule

Question: It deploys the "parent" module just fine, but I'm getting 404s for the files inside the "child" module. When I use heroku run bash to manually git clone the child into the project I can see the files poopulate where they should be, but as soon as I exit the server's cli they disappear.
What am I doing wrong? I was under the impression that Heroku supported git submodules.
<code>// Here's what I'm trying to describe...
//
// PARENT LEVEL APP (after initial "git push heroku master")
// - app.js
// - server.js
// - child/submodule
//   - nothing inside!
//
</code>
Answer: Ok so I found out what went wrong. I had cloned in the child repo without using "git submodule add". Once I did that everything was great!


SVM optimization problem with constraint

Question: I am studying SVM from Andrew ng machine learning notes. I don't fully understand the optimization problem for svm that is stated in the notes.
So we have optimization problem
$$\max_{\gamma, w, b}\gamma$$
s.t. :
$$y^{(i)}(w^Tx^{(i)}+b)\geq\gamma, i=1,\dots m,\\||w||=1.$$
I get a little bit confused here, as i don't see why we should need this first constraint. Isn't it enough only to maximize $\gamma$ and in that case we already have the maximal margin hyperplane where observations are at least $\gamma$ away from the decision boundry (because $\gamma$ is already defined this way)?
I think I don't understand something simple here. If you have any explanation for this I would appreciate it very much.
Answer:
(because $\gamma$ is already defined this way)?

But how does the optimization problem know that $\gamma$ is defined in such way ? if you remove that constraint, your optimization problem becomes:
$$ \max_{\gamma, b, w} \gamma \\ s.t. : ||w|| = 1$$
The optimization problem will just indefinitely increase $\gamma$, as is not restricted in any way. You have to enforce the way gamma is defined so that the optimization problem has solutions that respect that definition.


Isolated Docker containers and resource limiting

Question: Say I want to build a hosting environment using Docker (so that I can scale up if needed).
I want:

Each user to be able to execute arbitrary code and
Each user to not see or affect other users

Is this something more concerning Docker, or some other tool like Apparmor?
I want users to be able to run, say, PHP code. If one users gets a lot of hits and is using a lot of cpu, I want it to not affect another user who I've promised a certain amount of cpu usage. Perhaps I'm missing what concept governs this type of thing altogether?
Answer: you can limit the memory an cpu usage of dockers using --memory and --cpus flags when you run the docker so users have a maximum amount of resources they are limited to, for all such constraints use the following documentation.
https://docs.docker.com/engine/admin/resource_constraints/


Pesquisa no SqlServer com Query

Question: Estou com o seguinte problema:
Gostaria que a pessoa digitasse o numero de ribbons em um edit e esses valor fosse comparado com os valores no banco de dados e quando forem iguais. apresentar eles no relatorio:
SQL.add('Select * from "controle" where "ribbons" = :ribbons');
FrMRelatorio.ADOQuery1.Parameters.ParamByName('ribbons').Value := edit1.Text;

Com o seguinte codigo o mesmo sempre retorna os ribbons referente a 4
aonde posso estar errando?
Answer: Você deve remover as aspas dupla ("") da tabela controle e do campo ribbons e também especificar o parâmetro para query que você esta usando.
Ficaria assim:
FrMRelatorio.ADOQuery1.SQL.add('Select * from controle where ribbons = :ribbons');
FrMRelatorio.ADOQuery1.Parameters.ParamByName('ribbons').Value := edit1.Text;

Veja mais sobre como trabalhar com parâmetros na query.
Answer: Você pode também ao invés de criar parâmetros adicionar o edit1.text dentro do SQL, dessa forma:
SQL.Add('Select * from controle where ribbons = '+QuotedStr(edit1.text.Text)+'');

Comment: Funcionou exatamente como eu queria.
Answer: Quando você utiliza parâmetros, você precisa definir os mesmos na propriedade "Parameters" mais quando você precisar fazer alguma mudança é precisar, por exemplo, carregar os campos da sua tabela você pode ter problemas é precisar redefinir tudo novamente da mesma forma que se você precisar definir mascara de campos você deve usar o evento Before Open. Geralmente eu utilizo  (ADOQuery + DataSetProvider + ClientDataSet). Não utilizo parâmetros, faço as consultas usando sql puro.
Você pode montar até uma procedure para que possa fazer todas as suas consultas, geralmente eu crio uma ADOQuery apenas para consultas da seguinte forma: (sqlGenerico + dspGenerico + cdsGenerico);
    //adicionar no type
    procedure ConsultaDadosGenerico(NomeDoClienteDataSet:TClientDataSet; sqlConsulta :String);

procedure TForm1.Button1Click(Sender: TObject);
begin
  ConsultaDadosGenerico(cdsCliente, 'Select * from controle where ribbons = ' +  QuotedStr(Trim(Edit1.Text)) );
end;

procedure TForm1.ConsultaDadosGenerico(NomeDoClienteDataSet: TClientDataSet; sqlConsulta :String);
begin
  NomeDoClienteDataSet.Close;
  NomeDoClienteDataSet.CommandText := '';
  NomeDoClienteDataSet.CommandText := sqlConsulta;
  NomeDoClienteDataSet.Open;
end;

Pesquisa no SqlServer com Query


Let G be a group of order 24 that is not isomorphic to S4. Then one of its Sylow subgroups is normal.

Question:
Let G be a group of order 24 that is not isomorphic to S4. Then
  one of its Sylow subgroups is normal.

This is the proof from my textbook.
Proof
Suppose that the 3-Sylow subgroups are not normal. The number of 3-Sylow
subgroups is 1 mod 3 and divides 8. Thus, if there is more than one 3-Sylow subgroup,
there must be four of them.
Let X be the set of 3-Sylow subgroups of G. Then G acts on X by conjugation, so we
get a homomorphism $f : G → S(X) \cong S_4$. As we've seen in the discussion on G-sets, the
kernel of f is the intersection of the isotropy subgroups of the elements of X. Moreover,
since the action is that given by conjugation, the isotropy subgroup of H ∈ X is $N_G(H)$ (the normalizer of H in G). Thus,
$$ker f = \cap_{H \in X} N_G(H).$$
For H ∈ X, the index of $N_G(H)$ is 4, the number of conjugates of H. Thus, the order
of $N_G(H)$ is 6. Suppose that K is a different element of X. We claim that the order of
$N_G(H) \cap N_G(K)$ divides 2.
To see this, note that the order of $N_G(H) \cap N_G(K)$ cannot be divisible by 3. This is
because any p-group contained in the normalizer of a p-Sylow subgroup must be contained in the p-Sylow subgroup itself (Corollary 5.3.5). Since the 3-Sylow subgroups have prime
order here, they cannot intersect unless they are equal. But if the order of $N_G(H) \cap N_G(K)$ divides 6 and is not divisible by 3, it must divide 2.
In consequence, we see that the order of the kernel of f divides 2. If the kernel has
order 1, then f is an isomorphism, since G and $S_4$ have the same number of elements.
Thus, we shall assume that ker f has order 2. In this case, the image of f has order
12. But by Problem 2 of Exercises 4.2.18, $A_4$ is the only subgroup of $S_4$ of order 12, so we must have im f = $A_4$.
By Problem 1 of Exercises 4.2.18, the 2-Sylow subgroup, $P_2$, of $A_4$ is normal. But
since ker f has order 2, $f^{−1}P_2$ has order 8, and must be a 2-Sylow subgroup of G. As
the pre-image of a normal subgroup, it must be normal, and we're done.
My Question
I'm just confused about the last part. I kind of got lost when it was explaining how/why $f^{-1}P_2$ has order 8. I'm not really sure how that's related to the kernel of f.
Thank you in advance
Answer: It has to do with the fact that every (non-empty) fiber of a homomorphism is a coset of the kernel. That is, if $\varphi:G\to H$ is a homomorphism, and $h\in\operatorname{im}\varphi,$ then the fiber of $h$ under $\varphi$ is the set $$\{g\in G:\varphi(g)=h\},$$ and is a coset of $\ker\varphi$ in $G$. I outline the proof of this fact (from a linear algebra standpoint) in my answer here, and not much changes in the more general case.
Since $\ker f$ has order two, then for any $\sigma\in S_4,$ we have $f^{-1}(\sigma)$ has cardinality either $2$ or $0$. Since we're assuming that $A_4=\operatorname{im}f,$ then for each $\sigma\in A_4$ (and in particular for each $\sigma\in P_2$) we have $f^{-1}(\sigma)$ has cardinality $2$. Since $P_2$ has $4$ elements by the referenced exercise, then $f^{-1}(P_2)$ is a union of $4$ pairwise disjoint sets of cardinality $2$, meaning that $f^{-1}(P_2)$ has order $8$.
Does that help?
Comment: @Artus, yes it is the 1st iso thm. What does "cosets of the kernel must have the same order as the corresponding elements in the image" mean? The elements in the image are not sets, and their order in the group-element sense is irrelevant. For the last part, it is not even that complicated: for any map $f:X\to Y$, the preimage $f^{-1}[A]$ has size $\sum_{a\in A} |f^{-1}(a)|$. In this case, $2+2+2+2=8$.
Comment: @Artus: Yes, and no. In the first case, that fact is fundamentally tied up in the proof of the first isomorphism theorem. In the second case, I was acting purely set-theoretically: given any function $f:X\to Y$ and any subset $A$ of the range of $f$, we know that $$f^{-1}(A)=\bigcup_{a\in A}\{x\in X:f(x)=a\},$$ and that this union is a pairwise disjoint union of non-empty fibers.
Comment: @anon: I suspect that Artus means there are as many cosets of the kernel as there are elements of the image.
Comment: @Artus: An application of that set theoretic bit from my previous comment is that, if $f:X\to Y$ is an $n$-to-$1$ function--that is, if all the non-empty fibers under $f$ are of cardinality $n$--then for any subset $B$ of $Y$, we have $$|f^{-1}(B)|=n\cdot|B\cap\operatorname{range}(f)|.$$ This is pretty much exactly what we used here. This homomorphism was assumed to be a $2$-to-$1$ function, with $P_2$ a subset of the image, and we knew that $|P_2|=4,$ so concluded that $$|f^{-1}(P_2)|=2\cdot|P_2|=2\cdot4=8.$$
Comment: when you say that "every (non-empty) *fiber* of a homomorphism is a coset of the kernel", you mean the first isomorphism theorem, right? Because we know that $G/kerf \cong im f$ So the cosets of the kernel must have the same order as the corresponding elements in the image. Also when you say that "$f^{-1}(P_2)$ is a union of 4 pairwise disjoint sets of cardinality 2, meaning $f^{-1}(P_2)$ has order 8", you are just using the formula $|HK| = \frac{|H||K|}{|H \cap K|}$, right?


Drupal web page logging

Question: I have a website built on drupal. I want to log (preferably db log) all the calls being made to a drupal page. The drupal page is called as shown here
http://www.example.com/page-name?url=example2.com&redirect=example3.com&uid2=randomNumber
I need to log all URL fields (url,redirect,uid2) alongwith timestamp and drupal user id.
Whats the best way to do it?
Comment: Only calls to `/page-name` or calls for all pages on the site, that include this parameters?
Comment: @user11153 only calls to `/page-name` including this parameters
Answer: Create a custom module, for example:
MODULENAME.install file with hook_schema() implementation:
<?php

/**
 * Implements hook_schema()
 */
function MODULENAME_schema() {
  $schema['MODULENAME'] = array(
    'description' => 'Description of the table.',
    'fields' => array(
      'timestamp' => array(
        'description' => 'Timestamp of the rquest.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      // definitions for the rest of fields here
    ),
    'indexes' => array(
      // define indexes
    ),
    'primary key' => array('NAME_OF_PRIMARY_KEY_FIELD'),
  );
  return $schema;
}

?>

MODULENAME.module file with hook_menu() implementation:

/**
 * Implements hook_menu()
 */
function MODULENAME_menu() {
  $items['page-name'] = array(
    'title' => 'Example title',
    'access callback' => TRUE, // imply no restrictions
    'type' => MENU_CALLBACK,
    'page callback' => 'MODULENAME_pagename_view',
  );
  return $items;
}

function MODULENAME_pagename_view() {
  global $user;
  // insert into Drupal database
  db_insert('MODULENAME')
    ->fields(array(
      'timestamp' => REQUEST_TIME,
      'user_id' => $user->uid,
      'url' => $_GET['url'],
      'redirect' => $_GET['redirect'],
      'uid2' => $_GET['uid2'],
    ))
    ->execute();
}

?>

Comment: Pay attention to `access callback` and `title` in your `hook_menu` implementation.
Comment: @Ayesh K Good point, corrected.
Comment: @user11153 how can i log it in external/internal database??
Comment: @lavesh I updated my answer.

Drupal web page logging


How to run django.setup() properly from within a stand-alone python file inside of a django app (on linux-ubuntu)?

Question: Im trying to run a stand-alone python file in a django project. The problematic code is below (standalone.py):
import os
import django

# os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings") tried as well
os.environ["DJANGO_SETTINGS_MODULE"] = "myproject.settings"

django.setup()

The error i receive is: 'No module named myproject.settings'. Somehow the project settings file is not being recognized.
The file runs just fine on my local machine however the problem occurs when running the file on a linux-ubuntu server.
This file is being run from within an app: myproject>myapp>standalone.py
When i move this file to the same directory that myproject resides in, the file runs just fine, so im assuming that the myproject.settings module is not being recognized from within the app directory.
As a temp fix:
sys.path.append('path_to_myproject/')

seems to resolve the issue, but definitely not something i want in production code. Any suggestions on how to resolve this issue? Thanks in advance
Comment: Why don't you make a Django management command?
Comment: Thanks for the post, I read this in the docs but didn't quite understand how to apply this to my script
Answer: If the settings module is myproject.settings, then the outer myproject directory must be on the python path. If the script is in the outer myproject directory (the one that contains manage.py) then you don't need to do anything because the current directory is on the path. Otherwise, you have to manually add the directory to the python path.
The way to add something to the python path is sys.path.append(), so you can't avoid having that in production code (unless you use the PYTHONPATH environment variable instead). Perhaps you would be happier with adding the parent directory instead of hardcoding the path.
sys.path.append('..')

Comment: This worked. Thank you for the post, i was looking for a way to do this. Do you think that there could be a better way? Without adding to sys.path
Comment: No, you can't avoid adding the directory to the python path. How do you expect Python to be able to import `myproject/settings.py`, if the directory containing `myproject` isn't on the Python path?
Comment: I agree, its much better than hardcoding the path although just want to make sure its the correct convention for running a stand-alone python script in django


What kind of ball is used in the FIFA World Cup?

Question: What are the specifications, the FIFA World Cup football needs to have?
I'm looking for weight, size, flight and possibly more info?
Answer: The FIFA regulations on the ball are found in FIFA 2014/2015 Laws of the Game (PDF), Law 2:

LAW 2 - THE BALL
Qualities and measurements
The ball is:

spherical
made of leather or other suitable material
of a circumference of not more than 70 cm (28 ins) and not less than
  68 cm (27 ins)
not more than 450 g (16 oz) and not less than 410 g (14 oz) in weight at
  the start of the match
of a pressure equal to 0.6 – 1.1 atmosphere (600 – 1,100 g/cm2
  ) at sea
  level (8.5 lbs/sq in – 15.6 lbs/sq in)

These are the general regulations for any ball, whether or not it is used in the World Cup.
However, as is the case with every World Cup, they have developed a new ball to be used in this year's 2014 FIFA World Cup in Brazil.  It is the Adidas Brazuca:

The specifications for the Adidas Brazuca are:

Six polyurethane panels
437 grams
69 cm circumference
0.2% water absorption
141 cm rebound
7% loss of pressure

Sources:

Gizmodo: Viva Brazuca
Daily Mail: The Science Behind the 'Brazuca'
Comment: Good answer, but you're missing "not more than 450 g (16 oz) and not less than 410 g (14 oz) in weight at
the start of the match". Strangely enough, this isn't on the FIFA web page you quoted, but is on page 15 of their Laws of the Game PDF: http://www.fifa.com/mm/document/footballdevelopment/refereeing/02/36/01/11/lawsofthegameweben_neutral.pdf
Comment: Side note to anyone who is interested: Last World Cup, many of the goalies were extremely unhappy with the design because of the grips that were present on them. I had a chance to use one as well and agree. I was not able to get as good a handle on it. This ball also appears to have those grips, and it may have an impact on how well a keeper can perform in certain conditions.


Is there any concept of 'declaring' an inning in Baseball?

Question: This is a question regarding a somewhat hypothetical situation, but one I have been thinking about quite a bit and can't get my head around.
In Cricket, a team can 'Declare' an innings at any time, ending the innings and allowing the other team to come to bat. This is generally done during test matches, as any game that reaches 5 days in length without both teams completing 2 innings would end in a draw - this means that it is not to a teams advantage to carry on after they have already achieved a heavy lead - it is more important to get the other team in so that they can be bowled out.
In Baseball, however unlikely, it seems to me that it would be possible for a team to just keep batting around the order, hitting a potentially infinite number of runs within an inning if the other teams pitchers were so inept that they just couldn't record any outs.
So my question is: Can a Baseball team choose to end an innings? Is there any law in place that would allow an umpire to step in and end it? In fact, is there anything at all that can end an innings other than three outs being recorded?
Comment: Since baseball doesn't have any limit to the length of the game, there's no strategic reason to do so - and while "possible" to score infinite runs, it's not likely to happen.  I've seen innings go well into double digits and the batting team still trying as hard as possible to score - remember, you're judged on your individual performance; see Wilson Ramos, for example, those two home runs he hit off of position players last week in a blowout certainly count when he goes for a new FA or arbitration deal.
Answer: In major league baseball, the only thing that could end an inning other than three outs would be a "walk-off" situation.
From wikipedia

As in the case of the ninth inning, a home team which scores to take a
  lead in any extra inning automatically wins, and the inning (and the
  game) is considered complete at that moment regardless of the number
  of outs

In other leagues (mostly kid's leagues) there is sometimes a rule that says an inning is finished if a team reachs a certain number of runs.
Answer: To my knowledge, there is no rule that allows for this at any level. However, teams can intentionally make outs. At the top ranks, this would probably be frowned upon.
On the other hand, in youth leagues it is not uncommon to intentionally "give away outs" in games where one team is many runs ahead, but some sort of rule might create a situation where a won game is nullified (for example a league might have a rule that the game must end after two hours or when it gets dark (on an unlighted field), but also a rule that some minimum number of innings must be played for the game to be official; otherwise the game must be replayed from the beginning). A few ways managers of youth baseball have "declared" an inning that I've seen: have batters strike out intentionally (rare); have batters swing at every pitch they see - regardless of whether the pitches are strikes or not - until their at bat is over, the batter doesn't have to strike out and can get a hit, but they must not take a pitch (or else they face the wrath of the manager); if a batter reaches base, have them lead off their base until they are tagged out, making no attempt to get back to their base or advance to the next one.


Store Image Using Rest Request using AngularJs

Question: how to store image in MySql using Angular as data is passed in json as Rest request to java backend server which i have used spring MVC.
Comment: loak at this link: http://stackoverflow.com/questions/21015891/spring-mvc-angularjs-file-upload-org-apache-commons-fileupload-fileuploade
Answer: Basically, you should give a try first and then come here to post questions, but here it is how you can get started:
1) Upload from your browser to the Web Server
2) Persist your image (binary file) into MySql
Try to integrate from these examples and come back if something fails.


How can I suspend a project in GAS?

Question: How can I suspend a project in GAS?
I have two projects on GAS, one is an outdated project so I want to stop it from working. But I don't know how to.
Some webpage says to delete the project, but I want to keep it anywhere.
Answer: Oh, I solved it by myself.
[Deployment] on the top, [Manage Deployment] and then archive all the deployment. Then it is suspended and I can resume it afterward.
Have a nice afternoon everyone.
Comment: You can delete the project and save the code using Apps Script API

How can I suspend a project in GAS?


Symfony 4 : Controller requires that you provide a value for the "$id" argument

Question: I have a page with a list of projects. When you click on one project, you should arrive on a "project_detail" page.
Here is my MainController with the route to project_detail :
 /**
 * @Route("/project_detail/{$id}", name="project_detail")
 */
public function project_detail($id)
{
    $current_project = $this->getDoctrine()
        ->getRepository(Project::class)
        ->find($id);

    return $this->render('main/project_detail.html.twig', [
        'current_project' => $current_project,
    ]);
}

And here is my template project_list, with the link to the "project_detail" page :

...

I obtain this link by clicking on it: website/project_detail/%7B%24id%7D?id=1
So I suppose that it understands that the page should show the project which have the id number 1. However, it keeps displaying this error : Controller "App\Controller\MainController::project_detail()" requires that you provide a value for the "$id" argument.
Do you have any idea of what I'm doing wrong ?
Thank you for your time,
Answer: The variable you pass is "current_project" and this means you need to change:

...

to

...

And remember also to fix this:
/**
 * @Route("/project_detail/{$id}", name="project_detail")
 */

with this
/**
 * @Route("/project_detail/{id}", name="project_detail")
 */

Comment: You make a good point about `current_project` passed from the controller vs `project` as used by the OP, but since we haven't seen the rest of the twig script this may or may not be a problem. For example, the `` tag with `project.id` could be in the middle of a loop through all projects, like `{% for project in projects %} ... ` for example. I'm just pointing out that these two are not necessarily linked for anyone reading this in the future.
Answer: Change your annotation to this:
/**
 * @Route("/project_detail/{id}", name="project_detail")
 */

The change is to drop the $ in front of the id variable.


insert query isn't working

Question:
INSERT INTO EmployeePrivileges (EmployeeID, PrivilegeID)
VALUES (
(SELECT ID
FROM Employees
WHERE Employees.JobTitle = 'Sales Manager'),
(SELECT PrivilegeID
FROM Privileges
WHERE Privileges.PrivilegeName = 'Day opening and closing'));

I'm trying to run the above query in Ms Access but following error occurs
" error query input must contain at least one table or query" what to do?
Comment: My guess is your first query returns multiple rows (assuming your company has more than one Sales Manager).
Answer: I haven't used ms-access in some time, but as long as those 2 queries are just returning 1 row each you could combine them:
INSERT INTO EmployeePrivileges (EmployeeID, PrivilegeID)
    SELECT e.ID, p.PrivilegeID
     FROM Employees e, Privileges p
    WHERE e.JobTitle = 'Sales Manager'
      AND p.PrivilegeName = 'Day opening and closing';

insert query isn't working


Composition formula for $ax^2 \pm by^2$

Question: It is well known that $(x^2+y^2)(u^2+v^2)=(xu+yv)^2 + (xv-uy)^2$, thus it suffices to characterize the primes $p$ with $x^2+y^2=p$. Are there any similar composition formulae for $ax^2+by^2$ and $ax^2-by^2$?
Comment: https://www.artofproblemsolving.com/community/c3046h1359115_representation_of_a_number_the_squares_in_different_ways_2
Comment: Martin, Gauss composition takes the product of two numbers of the form $\alpha x^2 + \beta y^2$ to a number of the form $u^2 + \alpha \beta v^2.$ In case this is in a non-principal genus, such as $2 x^2 + 3 y^2,$ the product can only be represented by $u^2 + 6 v^2$ by simple congruences, in this case $\pmod 3$
Answer: $$q(ac+nbd)^2+n(ad-qbc)^2=(a^2+nqb^2)(qc^2+nd^2)$$
We must remember that then can be reduced by a common factor.
Comment: but this is not a composition formula of the required type since the coefficients $a,b$ in $ax^2+by^2$ are not the same on the right-hand side
Comment: @Martin Don't understand. Not satisfied with this form? And what should be?
Comment: In your equation the coefficients $a$ and $b$ of $ax^2+by^2$ on the right-hand side vary ($1$ and $nq$ for the first factor and $q$ and $n$ for the second factor), while I want them to be fixed
Comment: @Martin  I want to have only the sum of the squares of the coefficients without? The coefficients should still appear.

Composition formula for $ax^2 \pm by^2$


How find this ODE solution $\frac{f(x)}{f(a)}=\left(\frac{x}{a}\right)^2e^{(x-a)\left(\frac{f'(x)}{f(x)}-\frac{2}{x}\right)}$

Question: let $a>0$ is constant number,and   the function $f(x)$ such follow ODE
$$\dfrac{f(x)}{f(a)}=\left(\dfrac{x}{a}\right)^2e^{(x-a)\left(\dfrac{f'(x)}{f(x)}-\dfrac{2}{x}\right)}$$
Find the $f(x)?$
Thank you
My try:
$$\dfrac{f(x)}{x^2}=\dfrac{f(a)}{a^2}e^{(x-a)\left(\dfrac{f'(x)}{f(x)}-\dfrac{2}{x}\right)}$$
then
$$\ln{\dfrac{f(x)}{x^2}}-\ln{\dfrac{f(a)}{a^2}}=(x-a)\left(\dfrac{f'(x)}{f(x)}-\dfrac{2}{x}\right)$$
then I can't,Thank you very much
Answer: Your equation can be written as follows:
$$\frac{\ln\frac{f(x)}{f(a)} - \ln\frac{x^2}{a^2}}{x-a} + \frac{2}{x} = \frac{f'(x)}{f(x)}, $$
now make the substitution: $\phi = \ln{f}$, so it yields:
$$\phi' = f'/f,$$
and substitute back in the original ode, which gives:
$$\phi' -  \frac{1}{x-a} \phi = \frac{2}{x}(x-a) - \ln\frac{x^2}{f(a) \, a^2}   := Q(x).$$
This is a linear first order ODE for $\phi(x)$, which can be solved, for example, in terms of an integrating factor, $u = e^{- \int (1/(x-a)) \,dx} = 1/(x-a) $, so:
$$\frac{d}{dx}\left( \frac{\phi}{x-a} \right) = \frac{Q}{x-a} \, dx,$$
and hence the solution:
$$\phi = A + (x-a)\int\frac{Q}{x-a}\,dx,$$
or, in terms of $f(x)$:
$$f = e^\phi = \overline{A} e^{(x-a) \int \frac{Q}{x-a} \, dx},$$
where I have defined $\overline{A} = e^A$, being $A$ a constant of integration.
Cheers!
Answer: You could turn it into a first order linear differential equation by substituting $\ln(f)=\phi$, since $\phi'=\ln(f)'=\frac{f'}{f}$ appears on the right side.
Comment: then ? I can't follow,Thank you


How to write with a single node in MPI

Question: I want to implement some file io with the routines provided by MPI (in particular Open MPI).
Due to possible limitations of the environment, I wondered, if it is possible to limit the nodes, which are responsible for IO, so that all other nodes are required to perform a hidden mpi_send to this group of processes, to actually write the data. This would be nice in cases, where e.g. the master node is placed on a node with high-performance filesystem and the other nodes have only access to a low-performance filesystem, where the binaries are stored.
Actually, I already found some information, which might be helpful, but I couldn't find further information, how to actually implement these things:
1: There is an info key MPI_IO belonging to the communicator, which tells which ranks provide standard-conforming IO-routines. As this is listed as an environmental inquiry, I don't see, where I could modify this.
2: There is an info key io_nodes_list which seems to belong to file-related info-objects. Unfortunately, the possible values for this key are not documented and Open MPI doesn't seem to implement them in any way. Actually, I can't even get the filename from the info-object which is returned by mpi_file_get_info...
As a workaround, I could imagine two things: On the one hand, I could perform the IO with standard Fortran routines, or on the other hand, create a new communicator, which is responsible for IO. But in both cases, the processes, which are responsible for IO have to check for possible IO from the other processes to perform manual communication and file interaction.
Is there a nice and automatic way to restrict the IO to certain nodes? If yes, how could I implement this?
Comment: Note that `MPI_IO` belongs to the predefined attributes of the execution environment and as such is read-only. It is mostly there for historical and portability reasons. On modern cluster systems its value is always `MPI_ANY_SOURCE` since all CPUs are in one way or another connected to the I/O subsystem.
Answer: You explicitly asked about OpenMPI, but there are two MPI-IO implementations in OpenMPI.  The old workhorse is ROMIO, the MPI-IO implementation shared among just about every MPI implementation.   OpenMPI also has OMPIO, but I don't know a whole lot about tuning that one.
Next, if you want things to happen automatically for you, you'll have to use collective i/o.  The independent I/O routines cannot send a message to anyone else -- they are independent and there's no way to know if the other side will be listening.
With those preliminaries out of the way...
You are asking about "i/o aggregaton".   There is a bit of information here in the context of another optimization called "deferred open" (and which OMPIO calls Lazy Open)
https://press3.mcs.anl.gov/romio/2003/08/05/deferred-open/
In short, you can definitely say "only these N processes should do I/O", and then the collective I/O library will exchange data and make sure that happens.  The optimization was developed some 15-odd years ago for just the situation you proposed: some nodes being better connected to storage than others (as was the case on the old ASCI Red machine, to give you a sense for how old this optimization is...)
I don't know where you got io_nodes_list.  You probably want to use the MPI-IO info keys cb_config_list and cb_nodes
So, you've got a cluster with master1, master2, master3, and compute1, compute2, compute3 (or whatever the hostnames actually are).  You can do something like this (in c, sorry.  I'm not proficient in Fortran):
MPI_Info info;
MPI_File fh;
MPI_Info_create(&info);
MPI_Info_set(info, "cb_config_list", "master1:1,master2:1,master3:1");
MPI_File_open(MPI_COMM_WORLD, filename, MPI_MODE_CREATE|MPI_MODE_WRONLY, info, &fh)

With these hints, MPI_File_write_all will aggregate all the I/O through the MPI processes on master1, master2, and master3.  ROMIO won't blow up your memory because it will chunk up the I/O into a smaller working set (specified with the "cb_buffer_size" hint: cranking this up, if you have the memory, is a good way to get better performance).
There is a ton of information about the hints you can set in the ROMIO users guide:
http://www.mcs.anl.gov/research/projects/romio/doc/users-guide/node6.html
Comment: Thanks for this very informative answer. I got the `io_nodes_list` from the `MPI-3` standard and I have no problem with the `C` language.  Though, I hoped for a non-collective possibility, to keep things unsynchronized.
Comment: Hah! I've been hacking on our MPI-IO implementation for nearly 13 years and I never knew about io_nodes_list.. .but there it is, in Section 13.2 under "Reserved File Hints".  ROMIO doesn't support the "filename" hint either...though that would be easy to implement.
Comment: You'll have to implement something on top of MPI-IO for a non-collective approach.  Some kind of distributed cache, say (Northwestern University did a bunch of work in this area in the 2008 time frame).  You could imagine RMA windows on the well-connected nodes, and hijacking MPI_Write to actually be MPI_Put... "the details are left to the reader"... and they are hairy details...
Comment: OMPIO in Open MPI 1.8 doesn't seem to be controllable in any way through the info argument. The info is simply stored so that it could be later retrieved using `MPI_FILE_GET_INFO`.

How to write with a single node in MPI


Is it correct to state that 2 bars 4/4 drumloops is 8/4?

Question: I've lots of drumloops recorded, that are (given the BPM at which they were recorded) long 4 beats per bar (i.e. 4/4), for 2 bars.
Here's opened in my DAW:

Is it correct to state that they are in fact 8/4 drumloops? The accent is every 8 quarters.
Comment: Which bit do you think represents the accent every 8 quarters?
Answer: No, carry on stating that you have two bars of 4/4
If you tell someone you have one 8/4 bar, they'll be puzzled and you'll have to explain yourself anyway.
Comment: So which tempo is that?
Comment: I know I don't have "two bars of 4/4", else the "accent" will repeat after 1 bar. But in fact, it repeats after 8 beats...
Answer: Late response here. 8/4 doesn't work like that. It's about the rhythm accent of the song. 8/4 could be expressed in 3 + 3 + 2 for example. There is a really good example of the difference between 4/4 and 8/4 in the song "into the light" by the band "2002". Most of the song is in 4/4 but the piano instrumental part feels like 8/4 if you count 4/4 it feels kind of weird and it's because the rhythm accent is like 3 + 3 + 2.

But the end of the day is somehow subjective because a musician could write the entire song in 4/4, it's just a matter of perception.
Answer: In this case the wave form of bar 2 looks identical to the wave form of bar 1. The wave form is 2 bars long in 4/4 time and the second bar is the same as the first. The 4 quarter note subdivisions can be seen below the wave form.
This pattern looks like bass drum on 1 and 3& and snare drum on 2 and 4 with high hat (or cymbal) varying between 8th and 16th notes.
Phrases can be more than one bar long with no repetitions and accents can occur anywhere in a phrase. Neither of those determine the time signature.
Comment: @markzzz the rhythmic pattern is identical. If a drummer plays a 1 bar pattern there will be subtle differences from bar to bar. I stand by my answer, 4/4. You seem to resist the idea that this is 4/4. Your question even states "2 bars 4/4 drum loop". Is there a reason you want this to be 8/4? Would you count this song off as 12345678?
Comment: They are not identical, they are similar. You hear the "repeat" after 8 beats...
Comment: @Belzaguy Yes I do. For almost every drumloops I think: 12345678. Song apart, because It can fit within a 4/4 Song...
Answer: The way it sounds will be 8/4, so it's better written that way. The accent on the first beat of each bar makes it so. If it was 4/4, you'd need to signify that one bar is accented, and the next isn't.
Anyone reading 8/4 might think it a little odd, but the time sig. needs to reflect what actually happens. All music should be written in the easiest way to read and make sense.
Fact - two bars of 4/4 are two bars of 4/4. If that 'compartment' of music translates to one bar, it can be called 8/4. It's not an improper fraction. Some music has way more than 8 crotchets per bar.
Comment: One of these days, a dver is going to explain! Don't mind dv, but on its own, it's meaningless to all except the dver. Come on, get realistic.
Comment: @markzzz - a dver is a shortened version for one who downvotes (dv). We can more often than not understand an upvote, looking at the quality of what's been upvoted. Sadly, not so with a dv.
Comment: @markzzz - when you want to address a particular person with a comment, use '@xxxx'. I guess the comment wasn't to me.
Comment: not sure if you are ironic or are you talking seriously?
Comment: @markzzz - about what in particular? Answer or comment? No irony here. All serious.
Comment: what is a dver?
Comment: I did not downvote, but I can speculate about the dver's reasoning: Drum patterns can be longer than 1 bar, and they need not accent every downbeat.  If the OP says there's an accent every 8 beats, that sounds to me like it's a 2 bar pattern in 4/4.
Comment: "that sounds to me like it's a 2 bar pattern in 4/4", thus, 8/4? :P That's the question... you "feel" the repeat after 8 beats, not 4. That's why they are not for me 2 bars of 4/4: it will repeat after 4 beats in that case, isn't?
Comment: @markzzz - where did you get the quote from? I don't understand. I'm agreeing with you.
Comment: @Tim from ibonyun above, he written that comment
Comment: @Tim it wasn't. I was talking with ibonyun
Answer: If you and everyone working on this piece of music agrees that they hear 8/4, then the music is in 8/4. You can write it down in 8/4 and count it in 8/4.
If someone were to transcribe the drum loop(by itself) by ear, they would likely notate it in 4/4. It is normal for a drum loop to last more than 1 bar.


I need an alternative similar to System.Runtime.Remoting that is supported in .NET 5.0

Question: I have a current software product written in C# WinForms that I'm migrating to WPF .NET 5.0. I've almost got it all migrated, but one of the last projects to migrate is the remoting support for the app. This is intended for remote control from a client in an intranet, NOT Internet.
The current version of the product uses .NET Remoting, however, I sadly have found that this is not supported in .NET 5.0.
I've seen something about gRPC, but can't find anything to show me how to implement or whether there might be something more similar to .NET Remoting to use so that there are minimal changes required.
Thanks in advance for your help!
Comment: The only difference should be how it's hosted, though. The point being, that the internet is full of gRPC tutorials...
Comment: This could also be interesting for you: https://github.com/cactuaroid/GrpcWpfSample
Comment: _"I've seen something about gRPC, but can't find anything to show me how to implement"_ - _Really_? How about ... https://learn.microsoft.com/en-us/aspnet/core/grpc/basics?view=aspnetcore-5.0, https://learn.microsoft.com/en-us/aspnet/core/grpc/?view=aspnetcore-5.0, https://learn.microsoft.com/en-us/aspnet/core/tutorials/grpc/grpc-start?view=aspnetcore-5.0&tabs=visual-studio, https://learn.microsoft.com/en-us/aspnet/core/grpc/client?view=aspnetcore-5.0, https://duckduckgo.com/?t=ffab&q=C%23+gRPC+how+to&iax=videos&ia=videos&iai=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DQyxCX2GYHxk, ...
Comment: This is for ASP.NET, not WPF with .NET 5.
Comment: I understand that. I just can't find an example for any other hosting like TCP/IP. I've done a lot of searches, but we all know it comes down to entering the magical query to get what you want. Everything I see is about ASP.NET Core.
Comment: I just recently learnt, Kestrel can be a TCP/IP Server, too (if that is what you want). I'll have look if I find that article again.
Comment: Here it is. It's also based on ASP.NET, though: https://github.com/davidfowl/MultiProtocolAspNetCore but should be adaptable to be running from a WPF App.
Comment: Another thing that just comes to my mind: Maybe have a look into [Zero-MQ](https://zeromq.org/languages/csharp/) (I am not affiliated with the project). It's a "Serverless" MessageQueue. Serverless in "" because, it not really is, it just doesn't need to "install" a MQ somewhere. You can just have it running in-process/in-app.
Comment: Fildor, thank you SO much for all of this help! I'll be looking into it.
Comment: The GRPC sample looks like the way for me to go.
Comment: Ah, alas, the Grpc WPF example isn't compatible with .NET 5.0
Answer: @Fildor, this isn't really an answer, perse, just posting what I ended up doing for a simplistic approach, rather than leveraging a remoting framework. My remoting implementation always runs on a private network or over a corporate VPN, so security isn't an issue. Thus, I can take a simplistic approach.
What I finally ended up implementing is a simple TCP/IP Socket implementation using TcpClient class and TcpListener that passes Json strings to represent a command and the response objects defined as classes. This class includes server API methods, each of which map to the defined API.
I created a class that inherits from TcpClient (RemoteClientSocket) for the client and another that inherits from TcpListener (RemoteListener) on the server.This class includes client API methods, each of which map to defined API.
I defined an enum, CommandType , that includes types for each remote command.
The RemoteClientSocket class includes method, SendCommand() that is invoked by each of the client API methods after instantiating a RemoteClientCommand object, this method takes a RemoteClientCommand argument.
The RemoteListener class includes methods for each of the remote commands defined in the CommandType enum.
I then created RemoteClientCommand class that is serialized into a Json string and sent from the client and deserialized by the RemoteListener object, which maps to the server command. I then created a RemoteClientResponse class that is serialized to a Json string, which is returned to the client. Each class includes a Serialize() and DeSerialize() method to serialize/deserialze to/from a Json string that is actually sent over the TCP/IP connection.
Lastly, add methods to the RemoteClientSocket class for each of the commands that populates the CommandArgs object array to send to the server and add methods to the RemoteListener class that that executes the server method corresponding to the CommandType contained in the RemoteClientCommand object.
After the RemoteListener executes the command, it instantiates a new RemoteCommandResponse object and populates the CommandReturn object and the CommandOutParams object array, calls Serialize() on the RemoteCommandResponse object and sends that Json string in response over the TCP/IP connection.
When the RemoteClientSocket receives the response, it calls DeSerialize() on the Json response string and unpackages the CommandReturn object, if any, and the CommandOutParams, if any, before returning to from the client method.
Here is the code for the RemoteListener:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using RemoteClient;

namespace RemoteServer
{
    public class RemoteListener : TcpListener, IWinCalRemotingService
    {
        private static readonly IPAddress _ipAddress = IPAddress.Parse("127.0.0.1"); // Local host

        // Keep track of the threads and create CancellationTokenSource for each
        private Dictionary<Thread, CancellationTokenSource> m_ThreadDictionary = new Dictionary<Thread, CancellationTokenSource>();

        public RemoteListener()
            : base(_ipAddress, Constants.DEFAULT_REMOTING_PORT)
        {
            RegisterCommands();
        }

        ///
        /// Start the server
        ///
        public void StartServer()
        {
            Start();

            // Create a thread for the server to listen on
            Thread t = new Thread(new ThreadStart(StartListener));
            t.Start();
        }

        ///
        /// Stop the server
        ///
        public void StopServer()
        {
            foreach (KeyValuePair<Thread, CancellationTokenSource> pair in m_ThreadDictionary)
            {
                // Cancel all of the client threads
                pair.Value.Cancel();
            }

            Stop();
        }

        public void StartListener()
        {
            try
            {
                while (true)
                {
                    Debug.WriteLine("Waiting for a Remoting Connection...");
                    TcpClient client = AcceptTcpClient();
                    Debug.WriteLine($"Remoting Client Connected from IP Address:{client.Client.RemoteEndPoint}");
                    Thread t = new Thread(new ParameterizedThreadStart(HandleClient));

                    // Add a mapping
                    m_ThreadDictionary.Add(t, new CancellationTokenSource());
                    t.Start(client);
                }
            }
            catch (SocketException e)
            {
                Debug.WriteLine("SocketException: {0}", e);
            }
        }

        public void HandleClient(Object obj)
        {
            TcpClient client = (TcpClient)obj;

            CancellationTokenSource cancelToken = m_ThreadDictionary[Thread.CurrentThread];
            var stream = client.GetStream();
            string imei = String.Empty;
            string remoteCommand = null;
            Byte[] bytes = new Byte[512];
            int i;
            try
            {
                while (!cancelToken.IsCancellationRequested && (i = stream.Read(bytes, 0, bytes.Length)) != 0)
                {
                    string hex = BitConverter.ToString(bytes);
                    remoteCommand = Encoding.ASCII.GetString(bytes, 0, i);
                    Debug.WriteLine("{1}: Received: {0}", remoteCommand, Thread.CurrentThread.ManagedThreadId);

                    string response = ProcessCommand(remoteCommand);
                    Byte[] reply = System.Text.Encoding.ASCII.GetBytes(response);
                    stream.Write(reply, 0, reply.Length);
                    Debug.WriteLine("{1}: Sent: {0}", response, Thread.CurrentThread.ManagedThreadId);
                }

                m_ThreadDictionary[Thread.CurrentThread].Dispose();
            }
            catch (Exception e)
            {
                SystemEventsMgr.AddException("Remoting Server Client Thread Exception", e);
            }
            finally
            {
                // Remove this thread from the map
                m_ThreadDictionary.Remove(Thread.CurrentThread);
                client.Close();
            }
        }

        private string ProcessCommand(string jsonCommand)
        {
            RemoteClientCommand cmd = RemoteClientCommand.DeSerialize(jsonCommand);
            RemoteCommandResponse response = null;

            switch (cmd.CommandType)
            {
                case ClientCommand.GetAutoInfo:
                    GetAutoInfo(cmd);
                    break;
            }

            return response.Serialize();
        }

    }

    private RemoteCommandResponse GetAutoInfo(RemoteClientCommand cmd)
    {
        int autoID = cmd.CommandArgs[0];
        string manufacturer = "";
        string model = "";
        int year = 0;
        string retString = GetAutoInfo(autoID, out string manufacturer, out string model, out int year);
        object[] outParams = new object[]{manufacturer, model, year};

        RemoteCommandResponse resp = new RemoteCommandResponse(CommandType.GetAutoInfo, retString, outParams);
    return resp;
    }

    private string GetAutoInfo(int autoID, out string autoManufacturer, out string autoModel, out int autoYear)
    {
        autoManufacturer = _autos[autoID].Manufacturer;
        autoModel = _autos[autoID].Model;
        autoYear = _autos[autoID].Year;

        return "Success";
    }
}

Here is the code for the RemoteClientSocket:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace RemoteClient
{
    ///
    /// IMPORTANT: When adding new commands, do the following:
    /// 1. Add to the command types
    /// 2. Add to the RemoteListener ProcessCommands switch statement
    ///
    public enum ClientCommand
    {
        GetAutoInfo,
    }

    class RemoteClientSocket : TcpClient, IAutoInfoInterface
    {
        ///
        /// Instantiate and connect the client
        ///
        /// <param name="ipAddress"></param>
        /// <param name="port"></param>
        public RemoteClientSocket(string server, int port)
            : base(server, port)
        {
        }

        ///
        /// Send a command of input type and receive a response as output type
        ///
        /// <param name="cmdObject">The Command Object</param>
        /// <param name="inputType">The Type for the Command Object</param>
        /// <param name="outputType">the Type for the return object</param>
        /// <returns></returns>
        public RemoteCommandResponse SendCommand(RemoteClientCommand cmd)
        {
            RemoteCommandResponse cmdResp = null;
            NetworkStream stream = GetStream();

            Byte[] data = Encoding.ASCII.GetBytes(cmd.Serialize());
            stream.Write(data, 0, data.Length);

            data = new Byte[256];
            string response = string.Empty;
            Int32 bytes = stream.Read(data, 0, data.Length);
            response = System.Text.Encoding.ASCII.GetString(data, 0, bytes);

            // Deserialize the response
            cmdResp = RemoteCommandResponse.DeSerialize(response);

            stream.Close();

            return cmdResp;
        }

        virtual public string GetAutoInfo(int autoID, out string autoManufacturer, out string autoModel, out int autoYear)
        {
            string err = "None";
            RemoteClientCommand cmd = new RemoteClientCommand(CommandType.GetAutoInfo, new object[] { autoID });

            RemoteCommandResponse resp = SendCommand(cmd);

            // Unpackage the return type and output arguments
            err = resp.CommandReturn as string;
            autoManufacturer = resp.CommandOutParams[0] as string;
            autoModel = resp.CommandOutParams[1] as string;
            autoYear = (int)resp.CommandOutParams[2];

            return err;
        }
    }

    ///
    /// The WinCal Remoting Client Command Package Containing Json Strings for Objects
    ///
    public class RemoteClientCommand
    {
        ///
        /// Command Type - one for each remote command
        ///
        public WinCalClientCommand CommandType { get; private set; }

        ///
        /// Command argument object(s)
        ///
        public object[] CommandArgs { get; private set; }

        public RemoteClientCommand(WinCalClientCommand cmdType, object[] cmdArgs)
        {
            CommandType = cmdType;
            CommandArgs = cmdArgs;
        }

        ///
        /// Serialize the class to Json string for the command
        ///
        /// <returns></returns>
        public string Serialize()
        {
            return JsonSerializer.Serialize(this);
        }

        ///
        /// Deserialize the command object
        ///
        /// <param name="jsonString"></param>
        /// <returns></returns>
        public static RemoteClientCommand DeSerialize(string jsonString)
        {
            return JsonSerializer.Deserialize(jsonString, typeof(RemoteCommandResponse)) as RemoteClientCommand;
        }
    }

    ///
    /// The object serialized and returned by the RemoteListener
    ///
    public class RemoteCommandResponse
    {
        ///
        /// The Command Type - one for each remote command
        ///
        public WinCalClientCommand CommandType { get; private set; }

        ///
        /// The single command return object
        ///
        public object CommandReturn { get; private set; }

        ///
        /// The Json strings for all out params - may be empty
        ///
        public object[] CommandOutParams { get; private set; }

        public RemoteCommandResponse(WinCalClientCommand cmdType, object retObj, object[] outParamObjs)
        {
            CommandType = cmdType;
            CommandReturn = retObj;
            CommandOutParams = outParamObjs;
        }

        ///
        /// Serialize the class to a Json string
        ///
        /// <returns></returns>
        public string Serialize()
        {
            return JsonSerializer.Serialize(this);
        }

        ///
        /// Deserialize the response object
        ///
        /// <param name="jsonString"></param>
        /// <returns></returns>
        public static RemoteCommandResponse DeSerialize(string jsonString)
        {
            return JsonSerializer.Deserialize(jsonString,typeof(RemoteCommandResponse)) as RemoteCommandResponse;
        }
    }
}

Comment: @LeiYang, yes, that is precisely what I did. It didn't take long to implement it.
Comment: so you mean you used socket to implemented some class similiar to .net remoting(at least interface is similiar?)


How do I remove the tab provided by a third-party module?

Question: I'm using the Guestbook module version 6x-2.0. How do I remove the "My Guestbook" tab on user profile pages?
Answer: I solved this with the Tab Tamer module.

Tab Tamer is an administration utility that provides easy re-ordering, hiding, and deactivation of tabs and subtabs.
Tab Tamer makes use of Drupal's drag ordering, but degrades gracefully when javascript is disabled.
Comment: if you solved the problem, you can mark this as accepted


Elasticsearch: Accessing IndexedScript in aggregation

Question: ES offers the possibility to store your script within an internal index ( see IndexedScript ), but unfortunately I cannot access it from aggreagtions.
Creating the index:
POST /_scripts/groovy/termFrequency
{
  "script": "_index['textBody'][term].tf()"
}

Using the script within aggreagtions:
GET /my_index/_search
{
   "query":{
      "match_all": {}
   },
   "aggs":{
      "tf_sum":{
        "sum":{
          "script": {
            "script": "termFrequency",
            "lang": "groovy",
            "params": {"term":"keyword"}
          }
        }
      }
   }
}

results in the syntax-error: Parse Failure [Unexpected token START_OBJECT in [tf_sum].
The purpose of the script is, to extract the term frequencies. I don't want to use script_files, because uploading such files is expensive in cloud services (e.g. found).
Comment: What version of ES you are using?
Answer: This is the correct syntax for ES 1.7, you were looking at ES 2.1
GET /my_index/_search
{
  "query": {
    "match_all": {}
  },
  "aggs": {
    "tf_sum": {
      "sum": {
        "script_id": "termFrequency", <--- you access it with script_id
        "lang": "groovy",
        "params": {
          "term": "keyword"
        }
      }
    }
  },
  "size": 0
}

Hope this helps!
Comment: thank you, i got confused with different versions of ES.


Apache 2.2.17 + Tomcat 7 on Windows Server?

Question: What's the most painless way for a newbie to get Tomcat 7 and Apache 2.2.17 running together on Windows Server 2008 R2?  I want Apache to handle all the static content and for Tomcat to handle the grunt work.  So far both work separately, just working on connecting the two.
Is mod_jk still the way to go here?  That's what my reading points me to, but I'm not sure if there's a newer/easier alternative.  If so, what do I need to add to my Apache config file if I've already got the DLL installed?
Comment: Found mod_proxy_ajp and it looks like it's easier to setup.  Is this the "wave of the future"?  Not looking for spectacular performance, just something that's reliable and easy to set up.  Thanks in advance for thoughts.
Comment: mod_proxy_ajp is a little easier to set up than mod_jk. However be very aware about the "secure your proxy" warning in the documentation
Answer: mod_jk is the way to go.  mod_proxy works as well, but JK is more configurable, plus it's very straight-forward to implement.  The quickest intro is here: http://tomcat.apache.org/connectors-doc/generic_howto/quick.html
Edit:
Add the following to httpd.conf (if you're using VirtualHosts you can put portions in individual hosts.
# Load mod_jk module
# Update this path to match your modules location
LoadModule    jk_module  modules/mod_jk.so

# Where to find workers.properties
# Update this path to match your conf directory location (put workers.properties next to     httpd.conf)
JkWorkersFile conf/workers.properties

# Where to put jk logs
# Update this path to match your logs directory location (put mod_jk.log next to access_log)
# This can be commented out, to disable logging
JkLogFile     logs/mod_jk.log

# Set the jk log level [debug/error/info]
# Only matters if JkLogFile is being used.
JkLogLevel    info

# Select the timestamp log format
JkLogStampFormat "[%a %b %d %H:%M:%S %Y] "

# Send everything for context /examples to worker named worker1 (ajp13)
# /examples would most likely be the name of your WebApp (c:/tomcat/webapps/example)
JkMount  /examples/* worker1

Comment: Thanks for your input.  I've been looking at that page, and I get down to the Apache config example, but it seems to favor UNIX.  Would you mind posting an example of a minimum config for a Windows server?  Thanks again.
Comment: Added an example above


Disallowed URI chars used in my token

Question: Take a look at this url:
http://firstname.lastname@example.com/74ffb86822ca0a75e378e1eaa3a4a000fbf5eb1f6bc98d2ec789c59b2cc9cfc7e27e7489bfe59cfff04220c3e29f3869b8abc6f0a65ef170b9b9148d3619b2f9

This is the config:
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-';

The url gives me this error -> The URI you submitted has disallowed characters.
The longest ugly string in the url is timestamp + salt sha512 encoded, but I don't see any disallowed chars in there, any idea what's wrong? Thanks!
Answer: firstname.lastname@example.com, specifically the @, in the URL is the reason for the error.
Answer: There's nothing wrong with your sha hash... the problem is with the at "@" symbol. You cannot have an "@" symbol within the path portion of your URL.
You can escape it to %40
http://localhost/foo/reset_password/bar%40foobar.com/74ffb86822ca0a75e378e1eaa3a4a000fbf5eb1f6bc98d2ec789c59b2cc9cfc7e27e7489bfe59cfff04220c3e29f3869b8abc6f0a65ef170b9b9148d3619b2f9

should work... just unescape the email address on your end

Disallowed URI chars used in my token


not a statement error in if statement within switch case

Question: My problem arises in the if statement - in the event that the variable "hours" is greater than 10, i wish to multiply the additional hours by 2.00 and add 9.95 to the result but i receive an error at compilation and I don't understand why. Any help is much appreciated.
    String choice;

    double hours;

    Scanner input = new  Scanner(System.in);

    System.out.print("Enter which package you are using A, B or C? ");
    choice = input.nextLine();
    choice = choice.toUpperCase();

    System.out.print("Enter the amount of  hours used: ");
    hours = input.nextDouble();

    switch ( choice )
    {
        case "A":
            if ( hours > 10 ){
                (( hours - 10) * 2 ) + 9.95;    << ERROR: Not a statement!
                }
            else
                System.out.println("Total: $9.95");
            break;

For references sake this has been answered and edited to:
            case "A":
            if ( hours > 10 ){
                total = (( hours - 10) * 2 ) + 9.95;    // Initialised to total
                System.out.println("Total: $" + total);
            }
            else
                System.out.println("Total: $9.95");
            break;

Answer: You need to assign the result value that generated form that line like:
double value = (( hours - 10) * 2 ) + 9.95;

Read about valid statement in Java
Comment: Thanks, can't beleive i didn't see that; hours - 10 must've tricked my brain into  thinking it was an assignment. Time to log off and rest my eyes.
Comment: Welcome, and don't worry its happened with all developers.
Answer: You are not setting this expression value (( hours - 10) * 2 ) + 9.95; to any variable.
Set the value to any variable like below :
double total = (( hours - 10) * 2 ) + 9.95;

Answer: That line is not a Java statement, As per Oracle doc, statement should be a complete unit of execution

Statements
Statements are roughly equivalent to sentences in natural languages. A
  statement forms a complete unit of execution. The following types of
  expressions can be made into a statement by terminating the expression
  with a semicolon (;).

Assignment expressions
Any use of ++ or --
Method invocations
Object creation expressions
Answer: You have to assign your result to the hours variable like this:
hours = (your expression here);


Difference between browser session and Drupal session

Question: After reading this question over here from 2014, I'm left wondering:
Is there any benefit, security concern, or real reason to use Drupal's session manager class over the browser session <code>$_SESSION[key]</code>?
Specifically wondering about the Symfony session API that was mentioned in the above linked question and whether or not that provides any benefits over the way i'm storing and accessing session data.
'The Drupal Way':
<code>$tempstore = \Drupal::service('user.private_tempstore')->get('mymodule_name');
$tempstore->set('my_variable_name', $some_data);
</code>
How I'm currently doing it:
<code>$_SESSION['three_minute'] = array();
$_SESSION['three_minute']['utility'] = $form_state->getValue('utility');
</code>
Answer: What you are describing is not Drupal session vs. Browser session. There's just one session, always managed by Drupal (partially by using Symfony code. But it's still Drupal).
The (private) tempstore is just a custom storage that used to be provided by ctools in 7.x. For anonymous users, it actually requires a session to be present, as it uses the session ID to identify the entries.
The main difference is that session data is always loaded, on every request. While for the tempstore, you control when and what is loaded. If you have data that is small and you need on many/all pages, use the session directly. If you have big objects, consider using a temp store.
Drupal itself uses the tempstore for example to store node objects for the preview feature and views while editing them.


Suppose A and B represent two vectors (insame order), the angle between them being 60 degrees, then why is the resultant wrong?

Question: Let's say there are three points A,B and C:
A represents the displacement between points A and B (4 cm to the east) and B represents the displacement between the points B and C (3cm to the northwest).And the angle formed ( anglevCBA) is 60 degrees.
The (magnitude of) resultant vector C would be:

So, according to the triangle law of addition , the answer should be:$\sqrt{37}$ or 6.08
I made a diagram (with some precision), which looked something like:

On actual construction, I found the magnitude of the resultant to be 3.62  (maybe it was 3.65 cm. Somewhere between 3.60 and 3.70. The point is, it wasn't 6.08 cm.- {Quite far from it}).
The question is/are:

What did I do wrong?
Is there something wrong with my interpretation of vector addition?
And the important question: How do we show this triangle addition law
visually? (since, this doesn't seem correct )

// Didn't see any 'beginner' tag in the search result while posting this question
Comment: I don't know where you found it but the cosine rule you're using is just wrong... it should be $a^2 = b^2 +c^2 -2bc \times cos(\theta)$
Answer: I would say you misplaced a $+$ where it should be a $-$:
$$ c^2=a^2+b^2-2\,a\,b\,\cos\gamma $$
With this, we get a length of $c=3.61\text{ cm.}$
Answer: You're adding $\vec{A}$ and $\vec{B}$, and your formula is correct as long as you take $\theta$ to be the angle between them, which is 120 degrees, not 60. Pay attention to the direction of the vectors.
Comment: A vector is a quantity with a magnitude and a direction. Its base point (where its tail end is) is irrelevant. So slide $\vec{A}$ so that its tail is at B, where $\vec {B}$'s tail is. Now look at the angle between them.
Comment: 120 degrees was in the exercise question. I was trying to find out whether it holds true for acute angles. How's the angle 120 degrees in this case(given the diagram)?
Comment: Here's another way to think about it. If I am moving east in the direction to $\vec{A}$, by what angle do I have to turn counterclockwise to face in the northwest direction of $\vec{B}$?
Comment: Thanks! Got that now.
Comment: Your vector addition formula does hold for all angles, but in this case the angle is obtuse.
Comment: Kind of funny. I was thinking it was acute in this case and obtuse in all others.
Comment: Other folks didn't notice that the vectors were being added. If you reverse the arrow on $\vec{A}$, then $\vec{C}=\vec{B}-\vec{A}$, their formulas with the minus sign apply, and the angle between the vectors is 60 degrees. Plus they have the same base so it is easier to understand what the angle is! So this way of thinking about a triangle of vectors is much more intuitive.


Centralizar um elemento com position absolute

Question: Estou tentando centralizar um botão no meu card.
Eu gostaria de obter esse resultado:

precisa ser com position absolute pois os outros cards as vezes possuem descrição maior e o botão "Ver detalhes" fica com distancias diferentes.
Atualmente eu tentei:
.btn-comprar{
    position: absolute;
    bottom: 0;
    left: 0;
}

Atualmente o botão com essas propriedades tem o seguinte resultado:

Meu html:

          {{ produto.desconto }} %

{{ produto.nome }}

          <app-media-avaliacao-produto [numero_avaliacoes]="produto.numero_avaliacoes" [avaliacao]="produto.aval"></app-media-avaliacao-produto>

{{ produto.preco_anterior | currency:'BRL' }}
            {{ produto.preco | currency:'BRL' }}

          ver
            detalhes

CSS:
.thumb-wrapper{
    padding: 35px;
    background: #fff;
    border-radius: 6px;
    text-align: center;
    position: relative;
    box-shadow: 0 2px 3px rgba(0,0,0,0.2);
    border: 1px solid #caccca;
    height: 100%;
}

Eu utilizo a biblioteca material design bootstrap
Comment: Já tentou apenas colocar o botão dentro de tags  sem ser absoluto? testei aqui e funcionou.
Answer: Cara tentei simular aqui e aparentemente ele ficou alinhado, então tem algo a mais no seu código que está atrapalhando... Mas veja no exemplo abaixo que para centralizar um elemento absoluto vc tem que colocar margin:auto e left:0 e right:0 assim ele fica no meio. E o bottom vc ajusta com quantos px quiser não tem segredo...

.box {
    position: relative;
    width: 100px;
    height: 100px;
    border: 1px solid #000;
}
.box .btn {
    position: absolute;
    width: 30px;
    margin: auto;
    bottom: 10px;
    left: 0;
    right: 0;
    border: 1px solid #000;
}

btn

Comment: vou tentar esse
Answer: Você pode usar porcentagem combinado com calc no seu css para calcular a proporção.
ex:

.box {
    position: relative;
    width: 100px;
    height: 100px;
    border: 1px solid #000;
}
.box .btn {
    position: absolute;
    width: 30px;
    bottom: 10px;
    left: calc(50% - 15px);
    border: 1px solid #000;
}

btn


Multithreading with Selenium using Python and Telpot

Question: I'm coding my first telegram bot, but now I have to serve multiple user at the same time.
This code it's just a little part, but it should help me to use multithread with selenium
class MessageCounter(telepot.helper.ChatHandler):
    def __init__(self, *args, **kwargs):
        super(MessageCounter, self).__init__(*args, **kwargs)

    def on_chat_message(self, msg):
        content_type, chat_type, chat_id = telepot.glance(msg)
        chat_id = str(chat_id)

        browser = browserSelenium.start_browser(chat_id)
        userIsLogged = igLogin.checkAlreadyLoggedIn(browser, chat_id)
        print(userIsLogged)

TOKEN = "***"

bot = telepot.DelegatorBot(TOKEN, [
    pave_event_space()(
        per_chat_id(), create_open, MessageCounter, timeout=10),
])
MessageLoop(bot).run_as_thread()

while 1:
    time.sleep(10)

when the bot recive any message it starts a selenium session calling this function:
def start_browser(chat_id):
    global browser

    try:
        browser.get('https://www.google.com')
        #igLogin.checkAlreadyLoggedIn(browser)
        #links = telegram.getLinks(24)
        #instagramLikes(browser, links)

    except Exception as e:
        print("type error: " + str(e))
        print('No such session! starting webDivers!')
        sleep(3)

        # CLIENT CONNECTION !!
        chrome_options = Options()
        chrome_options.add_argument('user-data-dir=/home/ale/botTelegram/users/'+ chat_id +'/cookies')
        chrome_options.add_argument('--no-sandbox')
        chrome_options.add_argument('--lang=en')
        print("Starting WebDrivers")
        browser = webdriver.Chrome(options=chrome_options)

        start_browser(chat_id)

    return browser

and then this one check if the user is logged:
def checkAlreadyLoggedIn(browser, chat_id):
    browser.get('https://www.instagram.com/instagram/')
    try:
        WebDriverWait(browser, 5).until(EC.element_to_be_clickable(
            (By.XPATH, instagramClicks.buttonGoToProfile))).click()
        print('User already Logged')
        return True
    except:
        print('User not Logged')
        userLogged = login(browser, chat_id)
        return userLogged

and if the user is not logged it try to log the user in whit username and password
so, basically, when I write at the bot with one account everithing works fine, but if I write to the bot from two different account it opens two browser, but it controll just one.
What I mean it's that for example, one window remain over the google page, and then the other one recive two times the comand, so, even when it has to write the username, it writes the username two times
How can I interract with multiple sessions?
Comment: This seems like something you would want to run in the browser (which is asynchronous already) but I can't tell what you're trying to do here.
Answer:
WebDriver is not thread-safe. Having said that, if you can serialise access to the underlying driver instance, you can share a reference in more than one thread. This is not advisable. But you can always instantiate one WebDriver instance for each thread.

Ideally the issue of thread-safety isn't in your code but in the actual browser bindings. They all assume there will only be one command at a time (e.g. like a real user). But on the other hand you can always instantiate one WebDriver instance for each thread which will launch multiple browsing tabs/windows. Till this point it seems your program is perfect.
Now, different threads can be run on same Webdriver, but then the results of the tests would not be what you expect. The reason behind is, when you use multi-threading to run different tests on different tabs/windows a little bit of thread safety coding is required or else the actions you will perform like click() or send_keys() will go to the opened tab/window that is currently having the focus regardless of the thread you expect to be running. Which essentially means all the test will run simultaneously on the same tab/window that has focus but not on the intended tab/window.

Reference
You can find a relevant detailed discussion in:

Chrome crashes after several hours while multiprocessing using Selenium through Python


Three different diminished scales?

Question: I'm reading about some jazz stuff, and get told there are ony two whole tone scales, and three diminished scales. The whole tones are pretty obvious - once you get past the second semitone, you're into a mode of the original one. But - I thought there were the whole/half and the half/whole diminished scales, so what's the third one?  Unless the writer conflated scales and arpeggios, whereby the notes of say, Co, C♯o and Do are all different, but when we arrive at E♭o, that's a mode of the first, Co?
Comment: whole + half = 3 half steps.  If a pattern repeats every 3 half steps, it can only have 3 versions.
 Proof: the one starting on C goes C, D, Eb F Gb.  Now look at the one starting on Eb, and you'll see it's the same collection of notes.  The other way to look at it is C has 2 of them, but one of them doesn't have a C at all.
Comment: They mean the somewhat abstract observation regarding counting scales as a *set* of pitch classes.  So, up to starting note, there are only two distinct whole tone scales: 0, 2, 4, 6, 8, 10; and 1, 3, 5, 7, 9, 11.  Similarly, there are only three distinct diminished scales up to starting note: 0, 1, 3, 4, 6, 7, 9, 10; 0, 2, 3, 5, 6, 8, 9, 11; and 1, 2, 4, 5, 7, 8, 10, 11.
Answer: There are three unique whole-half (or half-whole) diminished scales starting a half-step apart from each other. Each one has an equivalent half-whole (or whole-half) diminished scale starting a whole step (or half step) above it.

Equivalences between whole-half and half-whole diminished scales

Whole-Half scale | Half-Whole scale
starting pitch   | starting pitch
-------------------------------------
C, Eb, Gb, or A  | D, F, Ab, or B
C#, E, G, or Bb  | C, Eb, Gb, or A
D, F, Ab, or B   | C#, E, G, or Bb
Comment: Calling H/W and W/H the "same" is like say phrygian and lydian are the same, because they are rotations of the diatonic scale.
Comment: So doesn't that make **six** different diminished scales..?
Comment: Simple, really, innit?
Comment: @Tim Another way to look at it is that W-H and H-W are two different scales, and there are three unique versions of each. In that way it's like saying there are 12 major scales and 12 (natural) minor scales, even though they only differ according to their starting pitches.
Comment: Thanks. I was considering that the writer (a certain Jamie) was considering a diminished seventh arp. as a scale - when there wuld in fact be three different ones - and their modes.
Comment: @MichaelCurtis My language was sloppy. Just for my clarification, are you commenting on my answer, or my comment?
Comment: The comment. But, the way I would put it is there is one major scale (structure) and one natural minor, both can be transposed to 12 tonics. Both can be found in rotations of the other. They aren't the same for being rotations of one set, but different for the different intervals above a tonic.
Comment: @MichaelCurtis Thanks for pointing it out. I deleted the comment.
Answer:
only two whole tone scales, and three diminished scales.

They just mean that when you account from transposing the scales there are only 2 unique sets of tones for the whole tone scale, and 3 for a diminished scale.
But they are overlooking there are two diminished (or octatonic) scales.
In terms of interval structure there is one whole tones scale - all whole steps, and two octatonic scales - one alternating whole and half steps, the other alternating half and whole steps.
When you transpose a whole tone scale by a whole tone, you get the same set of tones.
When you transpose a diminished/octatonic scale by a minor third, you get the same set of tones.
If you take the rotations, or modes, of the scales instead of transpose them, something funny happens. All rotations of a whole tone scale produce the same set of tones just like transposing by a whole step. But, with the diminished scale, every other rotation produced the same set of tones or the "opposite" diminished scale, for example take second rotation of a W/H diminished scale and you get a H/W diminished scale.
If, for some reason, you treat the first and second rotation of a diminished scale to be the same thing, then there are only 3 diminished scales.
If you treat octatonic scales as just embellishments of a diminished seventh chord, then I guess it sort of makes sense to treat W/H and H/W as the same.
If you realize that W/H octatonic has a perfect fourth above the tonic, and H/W has diminished sixth - enharmonically equivalent to a perfect fifth -  that's a significant structural difference, and W/H and H/W are different scales. With H/W you can construct major, minor, and diminished triads above the tonic.
Coincidentally, I recently was looking at my scale syllabus from a certain Jamey, for a dominant seventh flat nine chord. He gives the diminished scale, but only the H/W version. That makes sense, because it provides the flat nine. But, that also underscores the two diminished scales are not necessary to be treated as the same.
Comment: I think it's the way he phrased the whole thing. There were a couple of other iffily phrased bits too. Producing 'educational' documents, I feel it's of paramount importance to eliminate all statements which may, even in the least, be construed as ambiguous.
Comment: I find a lot of jazz pedagogy unclear and, at least for me, prompts lots of follow up questions. It's almost always confusion about _the wording and terminology_.
Answer: As far as I'm concerned there are 12 whole tone scales, 12 W/H diminished scales and 12 H/W diminished scales. The two diminished scales I mentioned are separate entities. I've never agreed with the "there are only 2 whole tone scales" etc. explanation. Of course several of the scales share notes but I approach them as individual entities. Just as I don't think of E Phrygian as a C scale from E to E I don't think of a E whole tone scale as a C whole tone scale from E to E. The tonal center of a scale should have some importance, even if it shares notes with 4 or 6 other scales.
Based on his logic of "only 2 whole tone scales", the writer is definitely thinking of a single diminished scale in 3 chromatic positions, C, C#, D and saying everything else just comes from there.
Comment: We may be getting into the realm of 'when is a mode a scale, when is a scale a mode' territory...
Comment: @Tim I'd say pretty much always in both cases…
Comment: I can't make up my mind - a scale is a set of notes put into an order - ascending/descending. But Dorian, Phrygian, Lydian, etc., are almost always referred to as *modes*.  To me, a mode is an inversion of a known (accepted) scale. A question may be coming on...
Comment: @Tim Everyone brace yourselves!

Three different diminished scales?


How do you sing and strum guitar chords simultaneously?

Question: In my experience with the guitar, I think I do best with strumming.
But it's always difficult for me when I have try to keep singing while strumming.  How can I learn to do both?
Answer: @Mark is right on. You've gotta practice enough so you can do it without thinking, even without the instrument.
My trick for getting there… play and read the news at the same time. It takes practice; at first you'll only be able to read a headline and then you'll mess up a chord, but eventually you can digest entire news stories while you're playing through a song. That way you don't have to actively think about DOING something while your muscles are going through the strumming and chords to a song.
I've heard of people who play in pit orchestras for broadway, etc., being able to read books while they play. Could be a rumor… but if you play eight shows a week for a year, I bet you get close to that!
Answer: If you have to do 2 or 3 things at a time, make sure you have to think about only one of them. So, in this case, really practice the guitar part until it goes automatically. Then, start to rehearse it together with the singing. Good luck!
Answer: Try to keep the strumming simple with one strum per four beats then as you get comfortable strum once every 2 beats. Progress to one strum per beat, eighth notes to sixteenth notes while singing the lyrics.
Answer: I have tried singing while playing guitar before and the only answer I have got to this question is: start at a slower tempo to the song that you are practicing, then slowly get faster and faster until you can sing and play at the right speed. It might take a while but it's worth it. Good luck.


Decoupling voice from the beat

Question: When playing and instrument and singing, I find it quite hard to separate the rhythm in the vocal line from that in whatever instrument I'm playing (guitar, drums). Is there a good way to approach remedying this?
Comment: Actually I think the wording of this current question is more general and therefore possibly better, but I suppose the duplicate indication mostly serves as a reference pointer why it doesn't matter if this is the one to be marked as duplicate.
Comment: Like the old question of how to get to Carnegie Hall:  practice, practice, practice. :-) .  So I guess I'm saying the posted answers are good answers.
Comment: @CarlWitthoft: yeah, I guess I assumed practice was implied. I probably should have asked for specific exercises or something...
Answer: The same challenge can be found with musicians learning keyboards as they have to learn how to coordinate both left and right hands playing together.
To accomplish this, students are given pieces that progress from easy to hard and they advance as they are ready. The key here is to break down each part to beats whether you are singing one part and playing guitar or drums or keys on the other.
Learn both parts then when you feel comfortable with each part, you can begin to combine them. Start with a very slow tempo until you have it and then pick it up until you are ready for the desired tempo. This all boils down to practice. If you get stuck, remember if you can learn one part, you can learn both, if you learn both parts, you can learn to play them together. Like rubbing your tummy counter clockwise with your right hand while circling your head clockwise with your left hand at the same time.
Another strategy to get really good at this is to swap parts, try playing the drum part with making sounds with your mouth, and play the melodic beats with your drums. Of course this will be way easier to swap parts when both instruments can play melodic content.
Yet another strategy is to practice poly rhythms with two hands. One hand plays three beat pattern say accent plus two more beats while the other plays a five note pattern say accent plus one beat then accent again followed by two more beats (3 against 5). You can make up as many combinations as you like to make it more challenging. This will help teach your hands to move more independently.
Here is an example of a poly rhythm exercise from a pianist eager to get better:
http://crosseyedpianist.com/tag/poly-rhythm/
One last thing, since you mentioned voice, make sure you take a breath before each phrase and this may help to keep time as well.
Answer: One technique I was taught to facilitate limb independence on the drumkit may help you here as well: play only the instrumental part and try conversing with someone. Have them ask you simple questions infrequently at first and try to answer without disturbing the rhythm in your playing, and progress once you're comfortable with that to more complicated questions, even up to solving math problems etc. Once you can do all that you will probably find you can play the instrumental part in your sleep so singing along with it should be no problem and you could even improvise without affecting your accompaniment.
Comment: Sounds like an interesting exercise. I'll give it a go :)
Answer: Practice using a metronome. Play and sing very slowly like a robot on each count until you get it down, then you can loosen off or put more emotion into the singing. Some songs will come easier than others. As you get better you will learn to control your motor controls for hand timing and vocal cord timing independently. Get the basic 12-bar blues and some rock and roll rhythm ingrained into your fingers.
Early on, and still for some songs or learning new songs, I start very slowly to teach my hands and vocal cords how the timing is going to work, and they kind of "learn" after a few repeats when to come in / when to synchronize, etc.
Sometimes it helps to first figure out the strumming, and then listen very closely to the song and where the singer puts the words in relation to the beats.
For difficult songs or odd vocal stylings that don't follow the rhythm try first learning the song using a very slow simple 1-2-3-4 beat or a sort of "country-fied arrangement." Then once you have the basic structure of the song down, it's usually easier to make small adjustments to the vocal timings.

Decoupling voice from the beat


Taylor series in Maple for root of $x=e^{a\frac{\ln(1+b/x)}{\ln(1+b/x)+c}}$

Question:
I want to find the Taylor series for the following function in Maple:
Root of
  $$x=\large e^{a\cdot \dfrac{\ln\left(1+\frac{b}{x}\right)}{\ln\left(1+\frac{b}{x}\right)+c}}$$ when $a,b,c>0$

I use: series(RootOf(m = exp(a*ln(1+b/x)/(ln(1+b/x)+c)), m), a)
Maple returns:
\begin{align}
\label{eq:1} 1+\dfrac{\ln\left(\dfrac{b+x}{x}\right) }{\ln\left(\dfrac{b+x}{x}\right)+c}a+\dfrac{\ln\left(\dfrac{b+x}{x}\right)^2 }{2\left(\ln\left(\dfrac{b+x}{x}\right)+c\right)^2}a^2+\cdots+O(a^6)
\end{align}
[fourth to sixth terms are dropped for brevity]
As you see, the parameter $x$ appears again which is not what we want. Do you know how I can solve this?
If MAPLE does not work, let me know if you can do this in MATLAB or MATHEMATICA
Second question, do you know how I can convert the output style of MAPLE to Latex? The output I got from MAPLE was originally different (see below) and it took me some time to convert it to a beautiful form written above.
1+a*ln((b+x)/x)/(ln((b+x)/x)+c)+(1/2)*ln((b+x)/x)^2*a^2/(ln((b+x)/x)+c)^2+(1/6)*ln((b+x)/x)^3*a^3/(ln((b+x)/x)+c)^3+(1/24)*ln((b+x)/x)^4*a^4/(ln((b+x)/x)+c)^4+(1/120)*ln((b+x)/x)^5*a^5/(ln((b+x)/x)+c)^5+O(a^6)
Comment: Fixed point is simple.  As an example, consider trying to solve $x=\sqrt 3$.  We know that $x^2=3$, or $2x^2=3+x^2$, or $x=\frac{3+x^2}{2x}$.  This nifty formula can be tied with fixed point method.  We know that $\sqrt3\approx\sqrt4=2$, so we start with $2$.$$x_0=2\\x_1=\frac{3+2^2}{2\cdot2}=\frac74\\x_2=\frac{3+(x_1)^2}{2x_1}=\frac{97}{56}\approx1.73214\\\vdots\\\sqrt3=1.73205$$So just repeatedly apply the formula until you are satisfied.  For this problem, $x_{n+1}=e^{f(x_n)}$ where $f$ is your exponent.
Comment: Or maybe it should be like this: `series(RootOf(x = exp(a*ln(1+b/x)/(ln(1+b/x)+c)), x), a)`
Comment: Yeah, doubt its solvable like that.  One a brighter note, one can attempt fixed-point iteration, though I'm unsure if it converges.
Comment: @SimplyBeautifulArt Can you talk about it more?
Comment: Is the ultimate goal to compute a value of $x$ solving this equation in terms of $a, b, c$? Or is the Taylor expansion of $x$ in terms of $a$ really what you are looking for?
Comment: @TobErnack Well, what I really wanted was to find a formula for $x$ with respect to parameters $a,b,c$.  Since I couldn't solve it for $x$, I wanted to find the series for $x$ in terms of $a,b,c$.
Answer: I am not sure why you changed the x to and m, it should be:
series(RootOf(x = exp(a*ln(1+b/x)/(ln(1+b/x)+c)), x), a);

You can use the latex() command to produce latex markup of a Maple expression.  I got the following from:
latex(series(RootOf(x = exp(a*ln(1+b/x)/(ln(1+b/x)+c)), x), a, 2));

$$1+{\frac {\ln  \left( b+1 \right) }{\ln  \left( b+1 \right) +c}}a+{
\frac {\ln  \left( b+1 \right)  \left(  \left( \ln  \left( b+1
 \right)  \right) ^{2}b+\ln  \left( b+1 \right) bc+ \left( \ln
 \left( b+1 \right)  \right) ^{2}+\ln  \left( b+1 \right) c-2\,bc
 \right) }{2\, \left( \ln  \left( b+1 \right) +c \right) ^{3} \left( b
+1 \right) }}{a}^{2}+O \left( {a}^{3} \right)$$


Open-sourced pairwise learning models

Question: I am solving a classification problem using pairwise-learning training set.
We have 2 classes: bad and good.
We also have pairs of objects $(a_i,b_i)_{i=1}^n$, meaning that object $a_i$ is better than $b_i$.
Each object is described through its real coordinates: $a_i = x_i^1, x_i^2, \dots x_i^k$.
My aim is to build such an algorithm, that says for test object which is bad and which is good.
The question is what open-sourced algorithms/programs/packages can you suggest for solving that kind of pairwise-learning problem.
I have found only svm-rank algorithm from svm-light project that handles such pairwise training data.
I wonder, didn't find anything similar in matlab/R/rapidminer.
Answer: The R implementation of sofia-ml, RSofia provides a couple of options, rank and query-norm-rank, that allow for pairwise learning. It's a fast SVM implementation out of Google. It's more barebones than some other R packages, but once you get it up and running I've found that it is a nice SVM option.

Open-sourced pairwise learning models


Adding background-colors to divs through javaScript

Question: Trying to add different background colors to divs using a for loop.
I stored all the colors in 20 variables and I want each of the 20 divs to have their own color. I'm trying to set it like this "background-color":(bar+i), but that does that work.
It works if I just pass one variable like bar1. What am I doing wrong? Any help is greatly appreciated.
var bar1 = "#afb626";
var bar2 = "#5b590a";
var bar3 = "#b44708";
var bar4 = "#950000";
var bar5 = "#eb9f9f";
var bar6 = "#246d13";
var bar7 = "#afb626";
var bar8 = "#a60046";
var bar9 = "#733702";
var bar10 = "#d1570d";
var bar11 = "#afb626";
var bar12 = "#5b590a";
var bar13 = "#b44708";
var bar14 = "#950000";
var bar15 = "#eb9f9f";
var bar16 = "#246d13";
var bar17 = "#afb626";
var bar18 = "#a60046";
var bar19 = "#733702";
var bar20 = "#afb626";

for (var i = 0; i < 20; i++) {
    $('
', { id: 'foo'+i,}).appendTo('body');
      $("#foo"+i).css({"background-color":(bar+i),"height": "100%", "width": screenWidth, "float": "right"});
}

Comment: you should really use an array for that
Comment: Yes you are probably right, but not really sure to do it with an array.
Answer: Use an array instead:
var bars = ["#afb626", "#5b590a", ...];

for (var i = 0, z = bars.length; i < z; i++) {
    $('
', {
        id: 'foo' + i
    }).css({
         backgroundColor: bars[i],
         height: "100%",
         width: screenWidth,
         float: "right"
    }).appendTo('body');
}

Comment: Just to let you know a comma after the last item in a object will break in IE
Comment: You said but that is in < IE8. well. yes it could be but the point is if it takes `2 Seconds` to prevent that happening then do it.
Answer: (bar+i)

should be
(window["bar"+i])

Answer:
There are a few problems in your code. i made a quick example for you

JSFiddle Demo Link
var bar = ["#afb626", "#5b590a", "#b44708", "#950000", "#eb9f9f", "#246d13",
              "#afb626", "#a60046", "#733702", "#d1570d", "#afb626", "#5b590a",
              "#b44708", "#950000", "#eb9f9f", "#246d13", "#afb626", "#a60046",
              "#733702", "#afb626"];

for (var i = 0; i < bar.length; i++) {
    $('
', {id: 'foo' + i})
       .css({
        "background-color": bar[i],
        "height": "100px",
        "width": $(window).width(),
        "float": "left"
    }).appendTo('body');
}

The Problems

You should use a array for your items. makes loads more sense

for (var i = 0; i < 20; i++) {
    $('
', { id: 'foo'+i, /* < you shouldn't have a comma here */ }).appendTo('body');
      $("#foo"+i).css({"background-color":(bar+i),"height": "100%", "width": screenWidth, "float": "right"});
}

// What is screenWidth?
// You shouldn't create your element - append it to body then reselect it??

Comment: Sorry, I didn't add all the code. screenWidth is a variable I use to decide the width of the div.