Search for an element in a n-ary tree recursively

Question: I have a Tree class that has a nested private Node class.
I wrote a method (Search(T elem)) that searches if the element given as parameter exists in the tree and sends a boolean.
However my problem is that this method only sends true if the element exists in the first branch of my tree and if not, it sends false. I must have mistaken somewhere in recursive calls.
for example, here in main i call search('C') and I get false although I should get true because C is in the second branch of my tree.
P.S. : Also I should mention that in this class, copy operator and constructor must be disabled and i can not use anything but raw pointer (no vector or smart pointers).
Thank you in advanced.
Comment: It's time to learn how to debug your code.
Comment: @ThomasSablik I debuged it and I understood that the problem is with my recursive call but I don't know how to fix it .......... :)))
Comment: _"somewhere in recursive calls"_ doesn't sound like you debugged the code and found the reason for the problem. If you debugged your code and know the problem please add this information to your question.
Comment: Your problem is pretty similar to https://stackoverflow.com/questions/58808623/how-to-compare-new-string-name-with-existing-from-txt-file. If you understand the other problem you will understand your problem.
Answer: You shouldn't return children[i]->search(elem); directly. So it will return false if elem is not found in the first branch, it will never get past the first child. Only return there directly if it is found. Otherwise try the other children.
Comment: @Mohammadreza change `if (children[i])
          return children[i]->search(elem);` to `if (children[i] && children[i]->search(elem)) return true;` in your original code.
Comment: sorry but I din't quite get what you are saying. could you pleas be more specific. Thank you
Comment: Consider the case where your tree only has the root with two children. Try to work through your code and think about what happens, when `elem` is in the second child.
Comment: @Mohammadreza `if (children[i]) return children[i]->search(elem);` checks the first child and exits the loop. It doesn't check the other children.
Comment: @ThomasSablik but doesn't the recursive call to method do the trick to search in all children ???? Are you saying that there is something wrong with `return` in this method
Comment: @Mohammadreza Do what n314159 said. Create a tree with root and two children. The character should be in the second child node. Run the program in your debugger and you will see exactly where the problem is. n314159 also described a solution. You should only return the value if it is true. Otherwise stay in the loop. `return` exits the loop and the function even if not all children where checked
Comment: @ThomasSablik ok i will try what happens in debugger. Thank you. Also, regarding the `return false`, is it in good place. Because if I don't write it there, I get a warning
Comment: @Mohammadreza Yes, it's in a good place. It's the only place where you can return false. Anywhere else in the function you can only return true.
Comment: @ThomasSablik so I do this `bool search(T elem) {
    if (_info){
      // if (_info->getData() == elem) return true;
      Tree** children = _info->getChildren();
      for (char i = 0; i < N; i++){
        if (children[i]){
          if (children[i]->_info->getData() == elem) return true;
          children[i]->search(elem);
        }
      }
    }
    return false;
  }` and I am able to search for second children of the root but i can not search for children of the children of the root. I am stuck in the first level of my tree
Comment: @ThomasSablik I am very struggling here to see where comes the problem, i tried to debug with gdb to see where from comes the problem but i was not successful to find it
Comment: You are stuck in the first level since you do nothing with the output of your recursive function call. You have to utilise the value of `children[i]->search(elem);`
Comment: @ThomasSablik n314159 Thanks for help ... i see now what is happening and where I was not stupidly looking.


Node.js - Pass context through to nested objects in function properties

Question: I need to make a cleanly name-spaced module in Node.js, break it up into sub-modules via require() and pass the root context/scope all the way to the methods in the name-spaces.
// index.js

  var SDK = function(data){
      this.data = data;
  };

  SDK.prototype.Utilities = require('./utilities');

  module.exports = function(data) {
      return new SDK(data);
  };

// utilities.js

  module.exports = {
       callAPI: function() {
            console.log(this.data);
       }
  };

// Use-case (somewhere in the node.js app...)

  var SDK = require('./index')("this is some data");
  SDK.Utilities.callAPI();
  // Should return "this is some data"

For example:
this in SDK needs to be accessible in SDK.Utilities.callAPI();, like below.  Utilities is the name-space I'm referring to.
I'm aware of javascript bind() and call() techniques, but I'm not sure how to use them in this particular case.
Comment: OK - one last thing, could you add an example of how you want to be able to use it? Pseudocode is fine
Comment: Yes.  I've just added the use-case to the bottom of the code.
Answer: You should use apply or call
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call
these run the function with the given this scope.
Comment: I'm aware of this.  But I don't know how to do this while dividing up the module into submodules via `require()`.  Could you please provide a written example of how this would work in my specific case?


R getting share of users with multiple of an element

Question: I have a data frame like this
User     OS
A        Windows
A        Linux
B        MacOS
C        Linux
C        FreeBSD
C        Windows
D        Windows

What I want to do is plot two types of statistics.

The share of users with different number of OSs. So, it would be the fraction of the users with 1 OS, with OS etc.
The share of users with only one OS and more than one OS.

For this I tried using tapply(OS, User, unique). But don't know how to go about plotting the results.
I was wondering if this is the right way and what more would I need to do to to get the plots I wanted.
Comment: if it's really about programming in R, there are quite some plot people on http://stackoverflow.com that can help you out as well.
Answer: You could try something like
> df <- data.frame(User=sample(LETTERS[1:10], 100, rep=T),
                   OS=sample(c("Win","Lin","Mac"), 100, rep=T))
> (res <- with(df, tapply(OS, User, function(x) length(unique(x)))))
A B C D E F G H I J
2 3 3 3 3 3 3 3 3 3
> barplot(table(res)) # for counts
> barplot(table(ifelse(res==1, "1", "2+")))

Replace table() by prop.table() if you want proportions instead of counts, as suggested by @Chase in a comment to your preceding question.


Routes - CodeIgniter

Question: Queria saber o que significa este $ na definição das rotas, por exemplo :
route["(.*)-sid-(:num)-(:num)"]  = "services/service/$2/$3";
O que representa $2e $3?
Comment: Segundo o [manual](https://ellislab.com/codeigniter/user-guide/general/routing.html): `$route['products/([a-z]+)/(\d+)'] = "$1/id_$2"`; **URL**: `products/shirts/123` -> `$1 = shirts e $2 = id_123`. Representam os parâmetros da rota que você definiu.
Comment: são apenas variáveis que representam o ID e a function que sera passado para a url
Answer: São agrupamentos de caracteres capturados de uma Expressão Regular ou RegEx.
Em seu caso, o CodeIgniter pode definir as rotas com os agrupamentos das Expressões Regulares dentro dos parênteses, onde em: $route["(.*)-sid-(:num)-(:num)"] = "services/service/$2/$3";, $2 e $3 representam respectivamente os grupos de caracteres numéricos (:num) e (:num) e $1 captura um grupo de caracteres caso exista (.*)
Comment: Explicação perfeita, obrigado!

Routes - CodeIgniter


Pegar string dentro de um arquivo de texto usando regex em Python

Question: Gostaria de saber como pegar uma string nesse formato ' XXXX ' dentro de um arquivo de texto, usando regex. Já tentei vários métodos mas sem sucesso:
import re
f = open('infos', 'r')
padrao = re.findall(r'\sSSBR\s', f)
if padrao in f:
    print(padrao)
else:
    print("Padrão não encontrado!")

Quando executo retorna esse erro:
Traceback (most recent call last):
  File "analiseInfos.py", line 3, in <module>
    padrao = re.findall(r'\sSSBR\s', f)
  File "C:\Users\Matheus\AppData\Local\Programs\Python\Python37\lib\re.py", line
 223, in findall
    return _compile(pattern, flags).findall(string)
TypeError: expected string or bytes-like object

Trecho do arquivo 'infos':
20190401 00:01:25.371 00000084 SSBR 186701000125370c 0000 0000 D P C S N 0 3 RV 1e->000010413400000000000SSSSBR1010000091107200KP006287927455DF0

20190401 00:01:25.729 000000ff SSBR 175601000125370c 0000 0001 D R S S N 0 3 RV 1e<-000010413400000000000SSBRSS1022300091000107200KP006287927455

20190401 00:01:26.984 00000076 SSBR 176401000125984c 0000 0000 D P C S N 0 3 RV 1e->000011413400000000000SSSSBR1010000091107200CJ003363907455DF0

20190401 00:01:27.700 000000ff SSBR 190401000126984c 0000 0001 D R S S N 0 3 RV 1e<-000011413400000000000SSBRSS1236500091000107200CJ003363907455

Comment: Poste um trecho do que tem dentro do arquivo infos
Comment: Pronto, amigo!!
Answer: A função open retorna um file object, enquanto a função findall deve receber uma string. É isso que a mensagem de erro está dizendo:

TypeError: expected string or bytes-like object

Você passou o retorno de open (ou seja, um file object), em vez de uma string.
Para verificar o conteúdo do arquivo, você deve primeiro usar o file object para ler o conteúdo do arquivo e obtê-lo como uma string. Em seguida, você passa essa string para findall. Também recomendo usar with, pois ele já fecha o arquivo automaticamente:
with open('infos', 'r') as f:
    for line in f: # para cada linha do arquivo
        print(re.findall(r'\sSSBR\s', line))

Lembrando que findall retorna uma lista com as ocorrências da regex na string em questão, então basta você imprimi-la para obter os resultados (se não tiver nada, retorna uma lista vazia).
O código acima faz um loop por todas as linhas do arquivo, e para cada uma, verifica a regex em questão. Mas se quiser, também pode colocar todo o conteúdo do arquivo de uma vez em uma única string, e em seguida usar a regex:
with open('infos', 'r') as f:
    tudo = f.read()

print(re.findall(r'\sSSBR\s', tudo))

Mas para arquivos muito grandes, carregar tudo de uma vez pode consumir muita memória, então é melhor usar a primeira abordagem, de ler uma linha de cada vez.

Só lembrando que findall retorna uma lista dos trechos encontrados na string. Mas a sua regex contém um texto "fixo" (as letras "SSBR", exatamente nesta ordem, e com um espaço antes e outro depois), então o retorno de findall será uma lista com uma ou mais strings " SSBR " (ou uma lista vazia, se não for encontrado).
Se você só quer saber se a linha contém "SSBR" ou não, pode usar search:
with open('infos', 'r') as f:
    for line in f:
        if re.search(r'\sSSBR\s', line):
            print('linha contém SSBR')
        else:
            print('linha não contém SSBR')

Quando for usar a mesma regex várias vezes, é interessante compilá-la antes, usando o método compile:
r = re.compile(r'\sSSBR\s')
with open('infos', 'r') as f:
    for line in f:
        if r.search(line):
            print('linha contém SSBR')
        else:
            print('linha não contém SSBR')

Assim você reaproveita a regex, pois ela não precisa ser recompilada várias vezes dentro do loop (se bem que a documentação cita que existe um cache das regex usadas mais recentemente, então para programas pequenos e/ou com poucas regex que não são usadas muitas vezes não fará tanta diferença).

Outro detalhe é que você usou \s (que corresponde a espaços, TAB e quebras de linha, veja a documentação para a lista completa), e os espaços fazem parte do retorno de findall (ou seja, retornará " SSBR ", com os espaços antes e depois). Se quiser que somente a string "SSBR" esteja nos resultados, você pode trocar a regex para r'\s(SSBR)\s': os parênteses formam um grupo de captura e quando estes estão presentes, findall retorna somente os grupos.
Ou você pode usar r'\bSSBR\b'. O \b significa "word boundary" (algo como "fronteira entre palavras"), e corresponde à posições em que há um caractere alfanumérico antes e outro não-alfanumérico depois (ou vice-versa). Ou seja, ela pega a string "SSBR" inclusive se tiver outras coisas além de \s antes ou depois (como sinais de pontuação, o início ou fim da string, etc).
Comment: Muito obrigado! Era isso mesmo!


Como encontrar o segundo menor valor de um array em python sem usar funções built-in?

Question: Sou novato em programação e estou com dificuldades em criar um código que retorne o segundo menor valor de um array, ex:
array = [2, 3, 6, 6, 5]

retornar 3
Estou naquela fase de praticar a lógica de programação, pois já compreendo todo o conjunto básico da lógica, porém, como tenho pouca prática em aplicar, ainda me esbarro com problemas que acredito que sejam simples, enfim, espero que entendam.
Comment: Por quê retorna 5 se o segundo menor seria o 3?
Comment: foi mal Anderson Carlos, é isso mesmo, tem que retornar o 3, falta de atenção minha, valeu!, kkkkkkkkk
Answer: def segMenor(numeros):
     m1, m2 = float('inf'), float('inf')
     for x in numeros:
         if x <= m1:
             m1, m2 = x, m1
         elif x < m2:
             m2 = x
     return m2

 print segMenor([2, 3, 6, 6, 5])

Comment: m1 e m2 vai receber 5 e 6, x = 2, ai ele checa se 2 <= 5, sim, então, m1 = 2 e m2 = 6, ai ele começa de novo com x = 3 agora, até qd x = 6 e m2 = 5, ai cai no segundo if  (6 > 5) e o m2 recebe 5. Dificil de explica pq é bem complexo, mas se vc fizer no papel vai entender melhor.
Comment: boa tarde, m1 e m2 não recebe um número da lista, mas usei o da lista para vc entender mais fácil. Esse inf ( é infinito - um valor maior do que qualquer outro valor , ñ uma string). No começo sempre vai cair no primeiro if, dai x vai receber um valor da lista, ai começa a verdade. Pq inf sempre vai ser maior q qualquer outro numero. Dai m1 vai receber o x, dai ele compara de novo, e assim vai. Ele só usa o inf na 1ª vez, depois x recebe valor da lista.
Comment: Opa, ñ vi certo, corrigi.
Comment: Agora só falta explicar seu código :D
Comment: oi allan, cara eu não to conseguindo entender como funciona essa atribuição de valores para m1 e m2, como que as variáveis recebe uma função float com strings dentro (não sabia que isso era possível), e como o codigo sabe que m1 vale 5?, pq olhando o código, para mim tanto m1 como m2 somente tem uma função float com strings dentro, como uma função float pode armazenar strings? e como ela pode ter um valor dentro na primeira passada do if se não tem nenhum valor atribuido a variável m1, somente uma função float, pode explicar mais detalhadamente? ficou confuso pra mim.
Answer: Primeiramente você pode usar o SET para organizar os dados, garantindo a ordenação e a ausência de cópias duplicadas.
    array = [2, 3, 6, 6, 5]
    copia = set(array)

O conteúdo da variável cópia é "[2,3,5,6]", ou seja, garantimos que o segundo valor é sempre o segundo menor.
Após isso você pode imprimir o valor desejado da seguinte forma:
   print (list(copia)[1])


I need help setting up httpd.conf file to perform redirects to same site if accessed via http and https

Question: I am pretty much a newb at http configuration, so please bear with me (I inherited support of this system).
My web server is running behind an F5 which handles all of the https handshaking.  If the incoming request is for http, the F5 passes the request to the web server on port 80.  If the incoming request is for https, the F5 handles all of the handshaking and then passes the request to the web server on port 81.
My httpd.conf file is set up to listen on ports 80 and 81.  There is one Virtual Host defined for port 81:
<code><VirtualHost 126.96.36.199:81>
  ServerName example.com
  DocumentRoot /usr/local/mwi/www/winxp/81
  RewriteEngine on
  RewriteCond %{REQUEST_METHOD} !^(GET|POST|HEAD)$
  RewriteRule .* - [F]
</VirtualHost>
</code>
The directives "RewriteEngine on", "DocumentRoot /usr/local/mwi/www/winxs/80", and all RewriteCond and RewriteRule are outside of a Virtual Host block (and are not in any other block) which I take to mean that they are global directives.
My problem is that the rewrite rules process correctly when http://example.com/whatever is used but no rewriting is being done if the request is https://example.com/whatever.  The website is returning a 404 (page not found).  I found something yesterday (on the apache site) that said that the global directives are ignored if there is a Virtual host block that matches the incoming request.
I searched and found that I may be able to accomplish this using an htaccess file but is not recommended due to the performance hit (I do have access to the main httpd.conf file).
Do I need to create an additional Virtual Host block for port 80 and move all of the Rewrite directives into it?
Do I also need to copy all of the Rewrite directives to the Virtual Host for port 81?
I would prefer to maintain only one set of Rewrite directives for both ports.  How can I best accomplish this?
Thanks in advance.
Harley
Answer: If you don't want to double your rewrite configuration, then you could include it from an external file:
Include files in Apache HTTP Server Version 2.2 httpd.conf
Two separate blocks each including one rewrite would probably be neatest indeed.
Answer: JayMcTee - thank you.  I used your answer and figured out my issue.  I had to create a Virtual Host for the port 80 requests and remove the global rewrite directives.
From the way I understood the apache doc, I thought that the global rewrite directives would always be used no matter what port the request came in on.  A deeper reading of the doc had a statement saying that if a request was handled by a Virtual Host, then only the rewrite directives specified in that Virtual Host would be used.  Initially, I tried to simply copy the rewrite directives in the port 81 Virtual Host but still had the issue.  I then created a Virtual Host for port 80 and used the Include directive in both Virtual hosts.
Problem solved!


Question on a Proof regarding exponential matrix

Question: I need to prove following statement

Let $A$,$B$ $\in \mathbb{R}^{nxn}$ such that
  $$e^{t(R+S)}= e^{tR}e^{tS}$$
  Prove that RS = SR

My proof is the following and I'm unsure about one step: I don't know if I'm allowed to do it or not.
Proof:
$$e^{tR}e^{tS}=e^{t(R+S)}=e^{t(S+R)}=e^{tS}e^{tR}$$
$$\iff tRtS = tStR \iff RS = SR$$
Am I allowed to say that $e^{tR}e^{tS}= e^{tS}e^{tR} \implies tRtS = tStR$? my question comes from the fact that I'm working with matrices and not with numbers thus I can't take the logarithms to both part.
Thank you for any help.
Comment: Try taking a derivative of $f(t) = e^{tR}e^{tS}$ instead.
Comment: 1st problem: the logarithm is only definied in a open ball around the identity in the space of invertible matrices, your proof only works for small $t$.
Comment: 2nd problem: in your proof you already assume that $R$ and $S$ commute!
Comment: @Blah I assume the the sum of two matrices commute $\implies R+S = S+R$. however thank you for the answer, I'll prove it in another way :D
Comment: You have to know that $(tR)(tS)=(tS)(tR)$ for your first step $$e^{tR}e^{tS}=e^{(tR)+(tS)}$$
Answer: I don't think your proof is valid. You claim that $e^{tR}e^{tS}=e^{t(R+S)}=\color{red}{e^{t(S+R)}=e^{tS}e^{tR}}$, but the third equality sign (i.e. the equality I colored in red) is not justisfied. And I also don't see understand why the implication $e^{tR}e^{tS}= e^{tS}e^{tR} \implies tRtS = tStR$ holds.
To prove the proposition, you may differentiate the given condition on both sides twice w.r.t. $t$, and then put $t=0$.


Intersection of a 45 degree angle and an ellipse

Question: If you are looking at the upper right quadrant of an ellipse centered at $(0,0)$, with $a=1$ and $b = 0.6$, and there is a $45$ degree line drawn from $(1, 0.6)$, how would I find the $(x,y)$ coordinate where the line crosses the ellipse? (I have been out of school for a long time, this is not homework).
Answer: Your ellipse has the following equation:
$$
\frac{x^2}{1} + \frac{y^2}{0.6^2} = 1.
$$
Your line, which passes through $(1, 0.6)$ with $45$ angle has the following equation:
$$
y = x - 0.4.
$$
Now you need to solve the system of these two equations.
Substituting $y = x-0.4$ to the first equation, we get
$$
x^2 + \frac{x^2 - 0.8 x + 0.4^2}{0.6^2} = 1.
$$
Therefore, we obtain the following quadratic equation:
$$
(1+0.6^2) \, x^2 - 0.8 \,x - (0.6^2-0.4^2) = 0.
$$
Hence,
$$
1.36 x^2 - 0.8 x - 0.2 = 0.
$$
The roots of this quadratic equation will be (if I didn't make a mistake)
$$
x_1 = \frac{0.1 - \sqrt{0.027}}{0.34}, \quad
x_2 = \frac{0.1 + \sqrt{0.027}}{0.34}.
$$
Thus, the points of intersection of line and ellipse will be
$$
\left(\frac{0.1 - \sqrt{0.027}}{0.34}, \frac{0.1 - \sqrt{0.027}}{0.34} - 0.4 \right) \\
\left(\frac{0.1 + \sqrt{0.027}}{0.34}, \frac{0.1 + \sqrt{0.027}}{0.34} - 0.4 \right)
$$
The second point lies in the upper right quadrant.
Comment: Hi Voliar, thank you so much for answering.  Does the 0.8x come from 2ab?  I can solve down to 1.36x^2-.8x-.2=0, where do I go from there?  My math is very rusty.
Comment: The step I am missing is how do I turn 1.36x^2 - .8x -.2 = 0 into (x,y) coordinates that I can graph?  Thanks.
Comment: @beltran I edited my post, look at it.
Comment: Thanks so much Voliar.  You are very good at explaining things in a way I can understand.  If you don't mind, how do you do the roots, going from 1.36x^2 - .8x -.2 = 0 to the next step?
Comment: @beltran No problem. You just need to use the so-called Discriminant, see [here](http://en.wikipedia.org/wiki/Quadratic_equation#Discriminant)


How can I apply a plugin only to the lower frequencies?

Question: Part of the MasterRig plugin in WaveLab is the ability to apply saturation to the lower frequencies. I love this plugin, it sounds amazing, but I don't love WaveLab and would like to do this in Logic. As far as I can tell, the MasterRig plugin is simply not available outside of WaveLab.
I have tried splitting the signal into low and high using busses (and the single band eq plugin). It works, but I'm not 100% sure what the correct settings would be to make sure this doesn't attenuate or amplify any of the frequencies in the crossover region. It's also a little awkward.
For the tape saturation, I'm using Apple's tape delay plugin with 0 delay. Also sounds great.
What's a better way to achieve this (ideally with stock Logic plugins)?
Comment: Does the crossover region matter that much? Is this for mastering?
Comment: I guess it doesn't matter that much.
Answer: Instead of sending it to two different busses, just duplicate the track. Put a high pass filter on one copy, and a low pass filter on the other copy and make sure the cutoff frequencies are the same.
Then just put whatever plugins you want on one track or the other.
This was done quite often in the analog world, where one tape track was multed to two or more channels on the mixing console. Then the same track could have two different mixes that could be switched between (using mutes) or layered on top of each other. The way to do the same thing in the DAW is with track duplication. Note that duplicating a track does not create a separate copy of the media files used by the track, so you're not taking up more hard drive space with this trick.
The reason why making the cutoff frequencies the same ensures no total attenuation or boost at the crossover point is because by definition, the cutoff frequencies are the 3 dB down points. At the exact crossover frequencies, each of the high and low tracks are 3 dB down. When they are combined, they add up to the original power level, because 3 dB down is half the power. The other aspects of the filters you want to match for smoothest crossover is the slopes. Once you pick 6 or 12 or 18 or 24 or whatever dB per octave, make both the highpass and lowpass filters have that slope.
All that said, once you put different plugins on the different high and low tracks, you're going to make them different from each other to the point that having a smooth crossover region is pretty much meaningless. If you tape saturate the lows and not the highs, then you've just changed the the levels and loudness of one while leaving the other the same, which means your crossover region is now a mixture of something different with something the same. There's no preventing that - that's part of what you are deliberately doing to the audio.
Another way to approach the whole thing is to leave the original track as is and then just low pass the duplicate track. Saturate the crap out of the "low" track - way more saturated than you want it to sound - and then turn it all the way down. Now slowly bring it up while playing back until you are adding in the amount of the low saturation that you want. If the whole thing seems like it has too much low end at this point, you can add a low shelf to the original track to drop it down slightly.
No matter what, your whole goal as a mixer is to make it sound good, not to make it sound... anything else. Don't worry about weird things happening in the crossover region. Worry about it sounding bad. If it sounds bad, isolate why and then change it. Maybe it turns out to be the EQ settings, you just have to change them to make them sound better, but there's no one set of EQ settings that someone else can tell you will sound good. You have to figure it out based on the actual musical material you are working with. It's like asking what paint colors to use to paint a flower in a picture. There's no one answer. Your answer is the answer that for you gives you the best representation of the material that you have.
Comment: @piiperi - I know this. But the equing method suggested is the same approach as arallel compression. Split it, treat it, and add a bit back in.
Comment: The OP is worried about what happens with the crossover region: phasing, attenuation, amplification etc. If you do it manually, you have to solve it yourself, when in an integrated multiband processor it can be assumed that if it's properly made, the processor will keep things nice and tidy, particularly if it's meant for mastering. So how to set the band splitting EQs?
Comment: @piiperi I'm not sure I understand your question. Are you asking how to set the EQs for the two duplicated tracks or are you asking how to configure the crossover frequencies for integrated multiband processors? In the latter case, of course it depends on the processor. In the former case, you can set them however you want. You don't even have to choose the same corner frequencies, even though I suggested that in my answer. Technical knowledge, experience, and artistic goals will inform the decisions about how to set the EQs.
Comment: I meant this part of the OP's question: "It works, but I'm not 100% sure what the correct settings would be to make sure this doesn't attenuate or amplify any of the frequencies in the crossover region." Your answer does not address that part, and I don't think it helps to say you can set them however you want. Or that you just have to have technical knowledge, experience and artistic goals. ;)
Comment: @piiperi I expanded my answer to address that more, but it really **is** that you can set them however you want. There are no objective answers to artistic decisions, and mixing is at least as much art as it is a science, and even moreso when applying tape saturation plugins to only the low frequencies of a track!
Comment: Rather like parallel compression it seems to me.
Comment: @PeterJ This is not the same as parallel compression at all. Parallel compression is for bringing up the quieter parts of the dynamic range without spoiling the punchiness of loud things. This question is about processing the low and high ranges of the _frequency spectrum_ separately, which you might want to do for many different reasons like creating harmonic overtones for the bass only, stereo-widening only the highs without messing with the low end, or just auto-balancing everything. You could even parallel-compress the split lows and highs separately. :) Different techniques.
Comment: @PeterJ **Two** methods are suggested, one is like parallel compression and one is not.


What are some SAS-70 Type II data centers in the Boston area?

Question: I work at a small company that is going for ISO certification, and as a part of that we need to have our servers in a SAS-70 data center.  Could anyone make some recommendations besides Hosted Solutions in Charlestown (we're familiar with those guys and they are... sub-optimal for a variety of reasons)?
Comment: What ISO certification are you shooting for?  It's unrelated to the question, but we are also looking at what auditing standards and certifications our company should be targeting.
Answer: Vericenter has a SAS 70 Type II-compliant facility in Boston.
Answer: Navisite has a SAS 70 Type II-compliant datacenter in Andover.
I'd stay away from them. They were expensive and not at all responsive.
Answer: Savvis BO2/BO3 is compliant.
Answer: You may also want to take a look at 2nPlus1, it's a pretty new facility on the sommerville/cambridge line (on mcgrath highway).
Answer: Sungard is great. We use them for all but one of our Datacenters and that's only because they don't have a presence in Australia.
Answer: ColoSpace has six (6) SAS 70 Type II Data Centers throughout New England.  Competitive pricing, responsive customer service and exceptional engineering/technical support.
Somerville, Waltham, Rockland, Marlborough, Bedford,NH and Manchester, NH.


Bash script to kill specific process running longer than 5m

Question: Hi I'm looking for a BASH script for CentOS 6.5 that kills a processes by name that's been running longer than 5 minutes. I asked this question before and received a response that doesn't work under CentOS because killall doesn't have --older-than. I'm looking for an equivalent to that that will work under CentOS.
That post is here: Kill any GS process that's been running for over 5m on CentOS 6.5
Thanks!
Comment: Can you just start the original process with [timeout](http://linux.die.net/man/1/timeout).
Comment: @Zoredache I've never even *seen* that before!
Answer: I really suggest finding the root cause of this issue (or this issue or this issue).
A killall is a heavy-handed approach to process management, and your real issue is probably an application or resource problem.
Can you outline what you've tried so far? The types of things I would check are:

System vitals at the time these runaway Ghostscript processes occur: RAM? CPU?
Make sure the system this is running on has enough memory and doesn't have major contention for other resources.
Is this a physical or virtual server?
Talk to the vendor. There's a community and some level of support around PrinceXML.
A possible strace of the affected PIDs and Parent PIDs.
Are all of the requisite fonts installed?
Try logging the times that this happens to see if there's a correlation between the hang and other system events.
If you don't have historical and granular monitoring, you should. You could even try something like NewRelic to try to get a picture of what is happening or happened at a given time.
Check apache settings. It looks as though Ghostscript is being spawned by the apache user. Are there any limits or server settings that should be examined here?

Based on your output from an earlier question, it looks like you've only allocated 1 Gigabyte of RAM to this system and possibly only have a single CPU - no swap either...

If all else fails, you can write a script that can clean up old or stalled processes... or just compile a version of killall that supports the --older-than flag.
Comment: I'm a programmer not a sysadmin so I'll be honest I'm completely clueless on how to fix this the right way. Are you interested in taking a contract job to diagnose this for us? PM me your email if you're interested.
Comment: @Jonathan Well, how often does this happen? Can you increase RAM on your Rackspace instance? Is it just one CPU?
Answer: Will something like this be ok?
#!/bin/bash

PROC_NAME=my_proc_name

# Get all PIDs for process name
procs=(`ps aux | grep  $PROC_NAME | awk '{print $2}'`)

# for each PID in PIDs array
for pid in $procs; do
    # get elapsed time in form mm:ss and remove ":" character
    # to make it easier to parse time
    time=(`ps -o etime $pid | sed -e 's/[:-]/ /g'`)
    # get minutes from time
    min=${time[1]}
    # if proces runs 5 minutes then kill it
    if [ "$min" -gt "5" ]; then
        kill -9 $pid
    fi
done;

Of course it should be executed by cron or something like that to check processes periodically.


Technologies to create a hybrid application in Cordova

Question: This is not a programming question. If it is not appropriate to post it here, just advise me some place worth to share this.
What would be best to know in order to startup a project in Cordova. What i need to know is that in order to create a working web and android app what should i use?
So far

I use Cordova.
Ionic for GUI.
PHP and MySQL for back end
Angular JS for client side and controller for the app.
JSON

Do I have to use AJAX as well? if so, where would it fit?
Comment: It's really unclear what you are asking here.  You *seem* to be asking which libraries you should use to build an app, but the way this is presented breaks multiple rules for making a question on-topic for this site.  Specifically, questions should have a **singular**, concrete answer possible;  suggestions, recommendations, etc. are all off-topic.  You seem to acknowledge this immediately in the question, but proceed to essentially ask us to recommend where else you can ask your question, which isn't really appropriate either.
Answer: "Do I have to use AJAX as well? if so, where would it fit?"
Yes, you should build a Single Page Application inside Cordova using any framework that you desire.  Ionic/Angular is a valid choice here, other options include JQuery/Bootstrap, React JS, Framework7, OnsenUI and pretty much any combination of JS single page application framework and mobile focussed web front end framework that you like and can make work together.
For going beyond what the web view can do you'll use off the shelf plugins, or write your own which will need Java / Objective-C / C# or Swift skills depending on which platforms you're using.
As you want to be building a single page application you will need to make AJAX calls to get resources from servers, call APIs and the like.  Do this using the mechanism built into your chosen framework, e.g. $http service with Angular, $.ajax for JQuery etc.
Comment: Thanks and got it. But when it comes to $http I'm facing CORS and I'm working on it. If you don't mind can you check [this question](http://stackoverflow.com/q/36887891/5850835) out and see what you can do to help me.
Answer: With angular you can use AngularJS <code>$http</code>
Link to Angular documentation: https://docs.angularjs.org/api/ng/service/$http
Comment: With $http I'm facing CORS and I'm working on it. If you don't mind can you check [this question](http://stackoverflow.com/q/36887891/5850835) and see what you can do to help me.


How to rebuild object with keys and values javascript/jquery?

Question: Im looking for your advise how to re-build object in javascript/jquery? Im receiving JSON from server
Source json (var array):
{
  "key1":{
         "subkey1":"a",
         "subkey2":"b",
      },
  "key2":{
         "subkey1":"a",
         "subkey2":"a",
      }
}

Expected object:
{
  "a":{
         "subkey1":[
                      "key1",
                      "key2",
                   ],
         "subkey2":[
                      "key2"
                   ]
      },
  "b":{
         "subkey2":[
                      "key1"
                   ]
      }
}

Here is where I got stuck:
    var newarray = {};
    for (var key in array) {
        var items = [];
        for (var item_id in array[key]) {
            items.push(item_id);
            newarray[array[key][item_id]] = [];
        }
        console.log(items);
    }
    console.log(newarray);

Comment: You do not have a multi-dimensional array.  You have an object with nested sub-objects. `[]` denotes an array.  `{}` denotes an object.
Comment: The objects represented by subkey1, subkey2 are invalid.
Comment: Given that array keys are numeric, and your object keys are not numeric, it's unclear how you want to translate this to a true multi-dimensional array construct.
Comment: Do you mean `"subkey1": ["key1", "key2"]`?
Comment: Hello guys, yes, please take my apologies. It should be [ ]
Comment: Bottom left of the question there is an `edit` link you can use to fix issues with.
Comment: Perhaps you are feeling more like a "dictionary" but thinking in terms of an array. - WWC
Comment: the expected output is invalid
Comment: You can accept one answer (if it helps you) by click on big gray check button on its left side. If you wish you can add +10 points to any author of any good answer by click upper gray triangle
Answer: You could take an iterative and recursive approach and store the target object and the path for the next recursive call.
If no more object is found take the value and all keys as well as the actual key and generate a new property in an new object. Proceed for any other properties in the object.
The wuestion does not states the value of the inversed object. This approach assigns undefined to all leaves properties.

function setValue(object, keys, value) {
    var last = keys.pop(),
        target = keys.reduce((o, k) => o[k] = o[k] || {}, object);

    target[last] = target[last] || [];
    target[last].push(value);
}

function inverse(source, target = {}, path = []) {
    Object.entries(source).forEach(([k, v]) => {
        if (v && typeof v === 'object') return inverse(v, target, [k, ...path]);
        setValue(target, [v, k, ...path.slice(0, -1)], ...path.slice(-1));
    });
    return target;
}

var object = { key1: { subkey1: 'a', subkey2: 'b'}, key2: { subkey1: 'a', subkey2: 'a' } },
   inversed = inverse(object);

console.log(inversed);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Answer: try (where r={})
Object.entries(d).map(([k,x])=> Object.entries(x).map( ([s,a]) => (
  r[a]=r[a]||{}, r[a][s]=(r[a][s]||[]).concat(k)
)))

let d={
  "key1":{
         "subkey1":"a",
         "subkey2":"b",
      },
  "key2":{
         "subkey1":"a",
         "subkey2":"a",
      }
}

let r= {}

Object.entries(d).map( ([k,x])=> Object.entries(x).map( ([s,a]) => (
  r[a]=r[a]||{}, r[a][s]=(r[a][s]||[]).concat(k)
)))

console.log(r);
Comment: I would hunt down and kill the dev (bare hands) who left this in a codebase I was maintaining
Comment: @KamilKiełczewski - at the very very least, you could use _somewhat_ meaningful variable names. Or are you trying to code golf?
Comment: k=key, s=subkey, a=letters a,b
Comment: Why not use `key` and `subkey` in the first place?
Answer:

let input = {
  "key1": {
    "subkey1": 'a',
    "subkey2": 'b',
  },
  "key2": {
    "subkey1": 'a',
    "subkey2": 'a',
  }
};

let expected = {
  "a": {
    "subkey1": {
      key1: true,
      key2: true,
    },
    "subkey2": {
      key2: true
    }
  },
  "b": {
    "subkey2": {
      key1: true
    }
  }
};

let output = {};
Object.entries(input).forEach(([key, subObj]) => {
  Object.entries(subObj).forEach(([subKey, value]) => {
    output[value] = output[value] || {};
    output[value][subKey] = output[value][subKey] || {};
    output[value][subKey][key] = true;
  });
});

console.log(expected);
console.log(output);
Answer: You can try the PHP-style method:

var newArray = {};

for (var key in array) {
    for (var subKey in array[key]) {
        var val = array[key][subKey];

        if (!(val in newArray)) {
            newArray[val] = {};
        }

        if (!(subKey in newArray[val])) {
            newArray[val][subKey] = [];
        }

        newArray[val][subKey].push(key);
    }
}

console.log(newArray);


Git rebase interactive/ -i: what happens if I abort/or dont save the rebase

Question: This is the scenario:

made several commits
wanted to edit a certain commit
git rebase -i 'commit-hash'
choose wrong commit hash so I closed the editor window(sublime)
terminal(iterm) git message: Successfully rebased and updated refs/heads/*

my question is:

what exactly just happened?
did it actually rebase onto (x)-amount of commits onto eachother?
if so, how can I undo this?
Comment: Git ran the interactive rebase with your (unchanged) rebase plan but since no modifications were necessary, none of the original commits are affected. So you will end up in the same situation you started from.
Answer: If you did not actually change anything in the editor, nothing will change.  In general git rebase allows you to move a branch to a new base commit.  However, Git actually accomplishes this by creating new commits.  So, one way to tell if a rebase occurred is to look at the commit hashes.  If there are no new ones, then a rebase did not occur.  The -i option simply allows you to rebase with more flexibility.  Such as squashing or splitting commits.


Print whole numbers as integers in Pandas LaTeX conversion

Question: I'm trying to write a small script to print LaTeX tables based on CSV.
A lot of the functionality formerly in e.g. matrix2latex have now been included in Pandas proper, which is cool.
However, no matter what I do (I tried a number of the other suggestions on here, it ended up becoming a convoluted mess which in effect changes nothing), it keeps coming out like this:
[deco]/tmp/table ❱ python lala.py

Dataframe:

  Unnamed: 0     Treatment Implant Transgenic Untreated Mice  Transgenic Treated Mice  Wildtype Mice  Total Mice
0         P1   Armodafinil     VTA                     20+15                     20.0            5.0          60
1         P2           NaN      LC                        50                      NaN           10.0          60
2         P3  Escitalopram      DR                        20                     20.0            NaN          40
3         P4    Reboxetine      LC                        20                     20.0            NaN          40

LaTeX Table Conversion:

\begin{tabular}{lllllrrr}
 & Unnamed: 0 & Treatment & Implant & Transgenic Untreated Mice & Transgenic Treated Mice & Wildtype Mice & Total Mice \\
0 & P1 & Armodafinil & VTA & 20+15 & 20.000000 & 5.000000 & 60 \\
1 & P2 & nan & LC & 50 & nan & 10.000000 & 60 \\
2 & P3 & Escitalopram & DR & 20 & 20.000000 & nan & 40 \\
3 & P4 & Reboxetine & LC & 20 & 20.000000 & nan & 40 \\
\end{tabular}

[deco]/tmp/table ❱ cat lala.py
import pandas as pd

df = pd.read_csv("table.csv")
print("\n")
print("Dataframe:")
print("")
print(df)
tex = df.style.to_latex()
print("\n")
print("LaTeX Table Conversion:")
print("")
print(tex)
[deco]/tmp/table ❱ cat table.csv
,Treatment,Implant,Transgenic Untreated Mice,Transgenic Treated Mice,Wildtype Mice,Total Mice
P1,Armodafinil,VTA,20+15,20,5,60
P2,N/A,LC,50,,10,60
P3,Escitalopram,DR,20,20,,40
P4,Reboxetine,LC,20,20,,40

Is there any way to make sure that whole numbers are always displayed as integers?
Answer: the issue, that you seem to be facing is that missing table entries are interpreted as NaN, which then forces the entire column to float you can prevent the empty entries from getting read as NaN and have them just left empty by using
import pandas as pd

df = pd.read_csv("table.csv", keep_default_na=False)
print(df)
tex = df.style.to_latex()
print(tex)

this leads to the following output:
Unnamed: 0     Treatment Implant Transgenic Untreated Mice Transgenic Treated Mice Wildtype Mice  Total Mice
0         P1   Armodafinil     VTA                     20+15                      20             5          60
1         P2           N/A      LC                        50                                    10          60
2         P3  Escitalopram      DR                        20                      20                        40
3         P4    Reboxetine      LC                        20                      20                        40
\begin{tabular}{lllllllr}
 & Unnamed: 0 & Treatment & Implant & Transgenic Untreated Mice & Transgenic Treated Mice & Wildtype Mice & Total Mice \\
0 & P1 & Armodafinil & VTA & 20+15 & 20 & 5 & 60 \\
1 & P2 & N/A & LC & 50 &  & 10 & 60 \\
2 & P3 & Escitalopram & DR & 20 & 20 &  & 40 \\
3 & P4 & Reboxetine & LC & 20 & 20 &  & 40 \\
\end{tabular}

if you're dissatisfied with the numbering of the rows you might want to remove the first comma on the first line of your csv to get an output that looks like this:
       Treatment Implant Transgenic Untreated Mice Transgenic Treated Mice Wildtype Mice  Total Mice
P1   Armodafinil     VTA                     20+15                      20             5          60
P2           N/A      LC                        50                                    10          60
P3  Escitalopram      DR                        20                      20                        40
P4    Reboxetine      LC                        20                      20                        40
\begin{tabular}{llllllr}
 & Treatment & Implant & Transgenic Untreated Mice & Transgenic Treated Mice & Wildtype Mice & Total Mice \\
P1 & Armodafinil & VTA & 20+15 & 20 & 5 & 60 \\
P2 & N/A & LC & 50 &  & 10 & 60 \\
P3 & Escitalopram & DR & 20 & 20 &  & 40 \\
P4 & Reboxetine & LC & 20 & 20 &  & 40 \\
\end{tabular}

Comment: is there any way to do this without providing additional info, such as which rows to attempt to convert? (I know I can do this iteratively in a `try` statement)... but since the input is e.g. 20 shouldn't there be some easier way to get it to not expand it into something nonsensical like `20.000000`? There aren't any other floats on the column, so why would it think I suddenly need that precision?
Comment: ok, `keep_default_na=False` solves the issue here, though it doesn't quite accomplish what I was looking for. This basically removes support for NaN parsing, and additionally treats the whole column as strings.
Answer: You can format the integers using the .astype(int) function before converting to LaTeX. Also, you can use the format option to control the formatting of all columns in LaTeX:
import pandas as pd

df = pd.read_csv("table.csv")

# Format columns as integers
df = df.astype({"Transgenic Untreated Mice": int, "Transgenic Treated Mice": int, "Wildtype Mice": int, "Total Mice": int})

# Format all columns as integers in LaTeX
tex = df.style.format("{:.0f}").to_latex()

print("\n")
print("Dataframe:")
print("")
print(df)
print("\n")
print("LaTeX Table Conversion:")
print("")
print(tex)

Comment: That returns `ValueError: invalid literal for int() with base 10: '20+15'` — which is due to the more general issue: for this sort of approach I need to specify additional information as to what columns are supposed to be what type. I was looking more for a general purpose approach, where whole numbers don't get expanded to 6-precision decimal floats.
Answer: A more general way to do that would be to convert the missing values to an integer (if possible) and to convert the datatype using convert_dtypes
.
The same works without replacing nan values, convert_dtypes then replaces the datatype to Int64.
import pandas as pd

df = pd.read_csv("table.csv")

print("\n")
print("Dataframe:")
print("")
print(df)
tex = df.fillna(-1).convert_dtypes().to_latex()
print("\n")
print("LaTeX Table Conversion:")
print("")
print(tex)

LaTeX Table Conversion:

\begin{tabular}{lllllrrr}
\toprule
{} & Unnamed: 0 &     Treatment & Implant & Transgenic Untreated Mice &  Transgenic Treated Mice &  Wildtype Mice &  Total Mice \\
\midrule
0 &         P1 &   Armodafinil &     VTA &                     20+15 &                       20 &              5 &          60 \\
1 &         P2 &            -1 &      LC &                        50 &                       -1 &             10 &          60 \\
2 &         P3 &  Escitalopram &      DR &                        20 &                       20 &             -1 &          40 \\
3 &         P4 &    Reboxetine &      LC &                        20 &                       20 &             -1 &          40 \\
\bottomrule
\end{tabular}


Erro em código PHP - SQLSTATE[42000]

Question: Estou tentando listar as categorias e subcategorias presentes no banco de dados mas o seguinte erro é apontado:

Fatal error: Uncaught exception 'PDOException' with message
  'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an
  error in your SQL syntax; check the manual that corresponds to your
  MariaDB server version for the right syntax to use near
  ''loja_categorias' ORDER BY id DESC' at line 1' in
  C:\xampp\htdocs\lojacurso\classes\Site.class.php:8 Stack trace: #0
  C:\xampp\htdocs\lojacurso\classes\Site.class.php(8):
  PDOStatement->execute() #1
  C:\xampp\htdocs\lojacurso\pages\categoria.php(13): Site->getMenu() #2
  C:\xampp\htdocs\lojacurso\index.php(20):
  include_once('C:\xampp\htdocs...') #3 {main} thrown in
  C:\xampp\htdocs\lojacurso\classes\Site.class.php on line 8

O código é esse:
<?php

class Site extends BD{

    public function getMenu(){
        $pegar_categorias = "SELECT * FROM 'loja_categorias' ORDER BY id DESC";
        $executar = self::conn()->prepare($pegar_categorias);
        $executar->execute();

        if ($executar->rowCont() == 0) {
            # não faz nada pois não há categorias
        }else{
            while ($categoria = $executar->fetchObject()) {
                echo '
slug.'">'.$categoria->titulo.'';

                    $pegar_subcategorias = "SELECT * FROM 'loja_subcategorias' WHERE id_cat = ?";
                    $executar_sub = self::conn()->prepare($pegar_subcategorias);
                    $executar_sub->execute(array($categoria->id));
                    if ($executar_sub->rowCont() == 0) {
                        echo '
';
                    }else{
                        echo '
';
                        while ($subcategoria == $executar_sub->fetchObject()) {
                            echo '
slug.'/'.$subcategoria->slug.' ">'.$subcategoria->titulo.'
';
                        }//termina while subcategoria
                        echo '

';

                    }//termina else dos resultados da subcategoria
            }//termina while das categorias
        }//primeiro else
    }//TERMINA FUNÇÃO getMenu

}

?>

Answer: Tire as aspas simples do seu SELECT, ficando assim:
$pegar_categorias = "SELECT * FROM loja_categorias ORDER BY id DESC";

Outra alternativa é trocar as aspa simples pelo crase:
$pegar_categorias = "SELECT * FROM `loja_categorias` ORDER BY id DESC";

Comment: Quando tiro aponta o seguinte erro: Fatal error: Call to undefined method PDOStatement::rowCont() in C:\caminho\classes\Site.class.php on line 10"
Comment: Vi aqui o erro de grafia :D
Comment: "Count" e não "cont" como estava

Erro em código PHP - SQLSTATE[42000]


Feeling of a flat major vs. regular major chord?

Question: The simple comparison between major and minor chords seems typically to be between happy (major) and sad (minor).
Likewise, is there a feeling/mood that tends to be associated with the flat major chords?
For example, Adele's 'Hello' is (roughly) F min Ab Eb Db. In this context, the flat major chords sound emotionally muted, but not necessarily happy or sad (at least to me).
Just curious if there's a consensus around what mood the flat major chords tend to convey and thus when they're most appropriately used.
Comment: When a piece is in C# major,it could equally have been written in Db major. What then..? And if most of us heard that Adele song in F#m/A major or Em/G major instead, would we know? And would it change the mood? Doubtful.
Comment: So is your hypothesis founded on 'the black keys' on a piano. Going somewhat silly, Fb major (lots and lots of flats) sounds pretty well like E major (four sharps).
Comment: If you play it a semitone lower, Em G D C, you would ask about natural majors being different than something? How about if you tune your instrument between semitones?
Comment: @Tim Fair point, the question could have just as easily been phrased in terms of sharp majors.
Answer: The "moods of keys" (or chords) is a centuries-old superstition in music, with many famous composers claiming to prefer a certain key for inducing certain emotions.
This page has a list: https://www.wmich.edu/mus-theo/courses/keys.html
I don't have perfect pitch and I can't differentiate between the keys by ear, but I've been told that with modern equal temperament tuning those associations are basically musical religion and have no basis in observable/testable fact.
Maybe with the historical unequal/just intonation tunings that many composers wrote in, they were able to identify keys by those slight differences of interval distance, or maybe even the timbre/resonance of instruments playing in vs out of their native keys?
Comment: A bit more technical, but I also found [this section about "key coloration" in the wikipedia article on musical keys](https://en.wikipedia.org/wiki/Key_(music)#Key_coloration) to be a good summary of how non-equal tempered tuning affects the main interval distances, and it also led me to this concept I'd never heard of before: [the "wolf fifth."](https://en.wikipedia.org/wiki/Wolf_interval) That audio example made me do a hearing double-take! Boards of Canada had it right, music really is math.
Comment: I wouldn't exactly call it a "centuries-old superstition." It *is* of dubious relevance in modern equal temperament, but the differences in old tuning systems between keys were not small: try playing in C major, then in D-flat major in a meantone tuning, and you'll certainly notice a difference! Completely even equal temperament wasn't really practiced on keyboards until the 20th century, so many historical composers could hear differences among keys. For them it wasn't "superstition" and traditions of setting certain genres in certain keys meant the connections stuck around.
Comment: Very cool link. The specificity of the associated moods is wild :)
Answer: While a chord's quality (major, minor, diminished, etc.) is the primary factor in determining how it "feels", the context around it also plays a significant role. You are absolutely correct that the Ab, Eb and Db in your example feel a little less bright (a term I greatly prefer over happy) than an isolated major chord, but this has nothing to do with them being flat.
Instead, it is the preceding Fmin that sets a certain precedence, suggesting that we are in a minor key, and effectively darkening the entire progression. If you leave the Fmin off and only play Ab->Eb->Db they will sound a little brighter. Similarly, is you shift everything up a half step so you are no longer playing flats (F#min->A->E->D) it will have the same quality as your original progression, despite the lack of flats.
On their own, all chords of the same quality sound exactly the same (with identical tuning and ratios) and this is essentially the point of equal temperament tuning. A major, played on its own, will not sound any brighter or darker than Ab major. However, no music consists of a single, isolated chord. The voice leading surrounding any given chord changes its effective brightness. Once a contextual precedent has been established, chords of the same quality can have differing levels of brightness.
These interactions can be incredibly intricate and subtle, but, in many cases, lowering pitches can, in fact, darken the overall context and thereby each individual chord, so you're observations are not unprecedented. That said, be careful not to equate a lowered pitch with a flat note; flattening natural notes will have the same effect as naturaling sharp notes.


Finding height of a pyramid , thus finding the volume

Question: The picture below shows a pyramid PQRT is cut from a corner of a cube whose side is 16cm. If MP = DQ = 9 cm and BR = 8cm , find the volume of the pyramid PQRT

I found that
PQ = 9.89949 cm
PR = 10.63 cm
QR = 10.63 cm
And area PQR = 46.6 cm^2
Now I'm stuck on how to find the height of the triangular pyramid ... Can I get help ? Thanks in advance!
Answer: HINT: You don't have to use $\triangle PQR$ as the base. Instead, take $\triangle PTQ$ as the base; the height of the pyramid is then simply $TR$. You will definitely be able to find the solution with this.
(This is more formally a tetrahedron, which can have any of the four triangular sides as its base.)


Boost Geometry / intersection() seems to return inconsistent result

Question: I have a 3D vector adapted for Boost Geometry as a 2D point, and as a ring:
BOOST_GEOMETRY_REGISTER_POINT_2D(Vector3, float, cs::cartesian, x, y)
BOOST_GEOMETRY_REGISTER_RING( std::vector< Vector3 > )

Then:

Draw some non-convex polygon (ring)
Draw line segment, that cuts the non-convex polygon and divides it into 2 (the smaller one will be most often a triangle)
Mirror smaller of the new 2 polygons over the line-segment

Resulting are two polygons, that are overlapping and have 1 tangent edge.
I then check for intersection of the two polygons. In 15% cases, the intersection result is empty, which is a surprise (the smaller polygon can have area 1.0f..10.f, so it's not a corner case)
std::deque< Polygon > output;
bg::intersection(bigger_Polygon, mirrored_over_cutting_lineseg_Polygon, output);
// output.size() == 0 in 15% of cases

What can be the reason? I tried doing boost::geometry::correct() on each polygon before calling intersection(), but it did not help. I am running out of ideas
EDIT::
I have tested if creating new rings, with Boost Geometry types and double storage type will help:
void my_intersection( std::vector<Vector3>& polyA, std::vector<Vector3>& polyB, std::deque< ... > & output ) {
    typedef bg::model::d2::point_xy<double> point_type;
    bg::model::ring< point_type > ringA;
    bg::model::ring< point_type > ringB;

    for( int i = 0; i < (int) polyA.size(); i ++ ) {
        bg::append( ringA, bg::make< point_type >( polyA[i].x, polyA[i].y ) );
    }

    for( int i = 0; i < (int) polyB.size(); i ++ ) {
        bg::append( ringB, bg::make< point_type >( polyB[i].x, polyB[i].y ) );
    }
    ...
}

I do two intersection() calls, for polyA, polyB (my initial float Vector3), and for ringA, ringB. Then,  inconsistency appears:
A[6]( 58.20822143554688 100.0000076293945 , 89.18041229248047 100.0000076293945 , 100.0000076293945 93.08255767822266 , 100 80 , 64.98564147949219 80 , 58.20822143554688 100.0000076293945 )
B[4]( 89.18040466308594 100 , 100 93.08255004882812 , 93.72125244140625 90.17939758300781 , 89.18040466308594 100 )
INFO: ------ 1 vs 0 ------ INCONSISTENCY

The "1" means: output deque has size() == 1, so intersection occurs (this is for ringA/ringB intersection). "0" is for Vector3 -- empty result.
EDIT2:
Using boost models with float storage type causes incorrect results being returned also for the ringA & ringB calls. I have this confirmed. I got once confused that doubles do not change error's "logic", but it was because accidental removal of correct() calls. With the correct() calls and double storage type for ringA/ringB redundant rings I was unable to obtain empty intersection.
EDIT3:
Here are 5 cases in which intersection() returns:

empty result for the initial two rings (std::vector< Vector3 >),
correct result of size() == 1, when first creating double-typed copy of the std::vector<> rings (using boost::geometry models).

Case 1:
A[6]( 58.20822143554688 100.0000076293945 , 89.18041229248047 100.0000076293945 , 100.0000076293945 93.08255767822266 , 100 80 , 64.98564147949219 80 , 58.20822143554688 100.0000076293945 )

B[4]( 89.18040466308594 100 , 100 93.08255004882812 , 93.72125244140625 90.17939758300781 , 89.18040466308594 100 )

Case 2:
A[10]( 0 100 , 66.90238189697266 99.99999237060547 , 70.97279357910156 80 , 40 80 , 40 60 , 28.31221580505371 60 , 20 67.16078948974609 , 20 80 , 0 80 , 0 100 )

B[4]( 28.31221961975098 60.00000381469727 , 20.00000762939453 67.16079711914062 , 27.08192825317383 68.22066497802734 , 28.31221961975098 60.00000381469727 )

Case 3:
A[10]( 0 100 , 72.89675903320312 100 , 73.80842590332031 80 , 40 80 , 40 60 , 26.65167617797852 60 , 20 65.58068084716797 , 20 80 , 0 80 , 0 100 )

B[4]( 26.65167999267578 60.00000381469727 , 20.00000381469727 65.5806884765625 , 25.49577522277832 66.55047607421875 , 26.65167999267578 60.00000381469727 )

Case 4:
A[6]( 47.28099060058594 99.99999237060547 , 95.71660614013672 100 , 100 97.21295166015625 , 100 80 , 68.72442626953125 80.00000762939453 , 47.28099060058594 99.99999237060547 )

B[4]( 95.71659851074219 99.99999237060547 , 99.99998474121094 97.21293640136719 , 97.45189666748047 96.08384704589844 , 95.71659851074219 99.99999237060547 )

Case 5:
A[6]( 57.69097518920898 100 , 91.16551208496094 100 , 99.99999237060547 92.9193115234375 , 100 80 , 64.8609619140625 80 , 57.69097518920898 100 )

B[4]( 91.16550445556641 99.99999237060547 , 99.99998474121094 92.9193115234375 , 93.08920288085938 91.37748718261719 , 91.16550445556641 99.99999237060547 )

EDIT4:
Here is a function, that I use to mirror polygon over the crossing line (x0,y0)-(x1,y1). The tangent edge is created using this function -- after mirroring, point lands in the same place.
Vector3 mirror_point( Vector3 p, float x0, float y0, float x1, float y1 ) {
    float dx = x1 - x0;
    float dy = y1 - y0;

    float a = ( dx * dx - dy * dy ) / ( dx * dx + dy * dy );
    float b = 2.0f * dx * dy / ( dx * dx + dy * dy );

    float x2 = a * ( p.x - x0 ) + b * ( p.y - y0 ) + x0;
    float y2 = b * ( p.x - x0 ) - a * ( p.y - y0 ) + y0;

    return Vector3( x2, y2, p.z );
}

Comment: Can you add a sample (of input of a failing combination)?
Comment: @BarendGehrels: I have included example 2 rings, printed out with full float precision. Loading them into double based rings removes the doubtful behavior
Comment: Great images. I will look to the float's soon.
Comment: @BarendGehrels: cool. I have added a function that might create some "special" error-prone points (using printed out cases did not reproduce for me, even though I use 16 digit precission in cout; however I was reading into POLYGON(()) not into ring). Maybe it will help
Answer: My analysis on your input:
The second polygon (starting with 24.57) is counter clockwise. Also the second polygon of the second set (starting with 90.61) is counter clockwise. So boost::geometry::correct should certainly be called. And it makes difference.
So, if I use geometry::correct, I get the following results:
1) first combination, using double: intersection area=12.3854, one geometry, 4 points
2) first combination, using float: intersection area=12.3854, one geometry, 4 points (the same)
This result is identical to the results of SQL Server
3) second combination, using double: intersection area=34.7862, one geometry, 4 points
4) second combination, using float: intersection area=34.7862, one geometry, 4 points
This result is identical to the results of SQL Server.
Note that in both cases the second polygon is within the first polygon (in the second case non touching, in the first case it is touching - according to SQL Server).
So all output seems correct. You mention: "eliminate the empty intersections", that has been solved recently in Boost.Geometry. That fix is not yet released in 1.52, but will be in 1.53. So if that is the specific problem, you have to use the version of Boost.Trunk.
However, that would not cause empty output.
Comment: @BarendGehrels: The post is now rebuild. I have clarified that double does solve the problem. I removed redundant parts from my post. The data that you analysed was partly created when I accidently removed correct() callse. Sorry for that. I attached 5 well tested cases, in which doing copy from float ring to double ring causes no empty intersection cases (and copying to new float rings doesn't help).
Comment: Hello again. I hope my post will not be ignored. I recreate geometries before calling intersection(). If I recreate with float (model::d2::point_xy) -- pictures like the above will return empty intersections. If I recreate with double -- correct intersection geometries are being returned. Original data can be float or double. The recreation is intended as isolation from possible heap / stack disruptions (I could have some pointers incorrectly written, meaning anything can happen)


What is my voice type?

Question: my name is Joudrick Sanchez, my grandmother is a very nice singer, not famous but, she is great singer, she teach me certain things, but she doesn't told me anything about my voice type, either my teacher. I sing with tenors or bass very rarely.
My vocal register:
Low notes:
E2 - C3
Chest notes:
C3 - D4
Belted notes/Mixed:
C4 - G4 - A4
(I hit A4 very rarely, only when I happy or inspired) (normally it's just a F#4 or a G4)
Head voice & Falsetto:
C4 - C5 - E6 (sometimes I can hit a C5 in head) (not all times)
Many people told me that my voice is very weird...
:( what am I ? Baritone, tenor, low tenor, high baritone???
Comment: I'd say "Just sing, don't worry about labels." I've been a professional singer [studio session pop/rock] for 35 years & I still neither know nor care what a classically-trained professional would classify me as.
Answer: If your teachers don't consider it helpful to nail down a particular voice type at your current stage of training, do you think some random collection of people never having heard you will fare better?
You need basic stamina across your accessible range anyway regardless of what you are going to end up singing since you can get hoarse on any untrained part of your vocal apparatus.  It's quite likely that when you train your voice and connect and blend the different registers and work on achieving consistent quality, that the worthwhile range that people will be interested in hearing will be considerably smaller than your theoretically accessible range.
But it will likely require quite a bit of development before you can sensibly make such choices with some confidence.
Answer: I'd say you're a bass.
The bass range is generally something like E2-E4. E2 is only rarely used, so the low notes you're describing are similar to those of a bass.
In terms of upper range, the highest I've had to sing, as a bass, is F4.
So, you're probably a bass with a good falsetto and quite a large bass. Whether you're a bass or a baritone depends on how confident you are with those low and high notes, and how 'deep' your voice sounds.
If you want to know for sure you can sing repertoire for a range of voice types, and from what you feel most comfortable singing you can deduce your voice type.

What is my voice type?


Swift: Is it bad practice to access the AppDelegate window in order to get the superview of any view?

Question: I have class which is supposed to display a custom notification banner to let the user know if, for example, an API call succeeded or not. Currently, if you want to use this class, you have to pass in the SuperView in order for the banner to appear on the right view. I want to simplify it by creating a variable called private let appWindow: UIWindow = UIApplication.shared.delegate!.window!! in the notification banner class so that the dev does not have to worry about figuring what view is the super view. Then, in the notification banner class I set the constraints of the banner using appWindow as the View.
Basically, I want to always display the banner on top of every other View regardless if it's a tab bar controller, navigation controller, or any other type of View without knowing or passing in a view. The banner is a UIView itself.
Is it okay if I use the variable above? Is it good practice? Is there a better way to always get the top-most view or superview? If not, is there a better way to write the variable above?
Thank you for any help!
Comment: I'm not sure if it is bad practice or not, as you can aways access that windows via `UIApplication.shared.keyWindow`
Comment: @NoodleOfDeath I think keyWindow is deprecated starting with iOS 13 so that wouldn't work without using an #available if statement.
Comment: @matt Ideally, that's what I would do but I don't want to limit the user's interaction with the current view controller. Plus they have to be able to dismiss the banner by swiping or the banner dismisses itself after 3 seconds.
Comment: You can certainly configure the dismiss with a presented view controller. The downside is that the user can't interact with anything else, as you say.
Comment: How do you plan to unit test this? You *are* using tests, right? ()
Answer: If you actually want your notification on top of EVERYTHING including things like alert views then adding to the existing window is not going to work; someone else can still add a view on top of you.  If you really want your view on top of everything use another window for your banner with .greatestFiniteMagnitude and then it will truly be on top of everything (unless someone else makes another window with level .greatestFiniteMagnitude; in that case whoever made the most recent window wins).
  private lazy var bannerWindow = {
    let bannerWindow = UIWindow()
    bannerWindow.backgroundColor = .clear
    bannerWindow.windowLevel = .init(.greatestFiniteMagnitude)
    bannerWindow.isHidden = true
    return bannerWindow
  }

Comment: Someway somehow, I'm going to jam `.greatestInfiniteMagnitude` into a PR by the end of the week :)
Comment: Would this method allow the user to interact with the underlying view controller?
Answer: private let appWindow: UIWindow = UIApplication.shared.delegate!.window!!

You cannot assume that the app delegate has a window property. If it doesn't, you'll just crash. Instead, ask the app itself about its windows.
Comment: I changed it to `guard let appWindow: UIWindow = UIApplication.shared.delegate?.window ?? UIWindow() else { return }` and then set the superview equal to appWindow `superview = appWindow`. But as long as the app is running, wouldn't there always be a window to refer to?
Comment: Yes but that is why I say ask the app. You know nothing about the user's app delegate. Try it yourself: In Xcode 11, make a new project and run your expression. Kaboom.


Cusps and corners of smoothly parametrized curves

Question: Consider a smooth injective map $\psi:\mathbb R \to\mathbb R^2$ with only one critical point (or singularity) at $t=0$, i.e. $\psi'(0)=(0,0)$ and $\psi'(t)\neq (0,0)$ for $t\neq 0$. A simple example is the cusp $\psi_c(t)=(t^2,t^3)$. The critical point is of finite order: $\psi''(0)\neq (0,0)$ (the order is thus $2$).
In some sense the corner $E= \lbrace (x,0): x\ge 0 \rbrace \cup \lbrace (0,y):y\ge 0 \rbrace$ should be simpler than the cusp. However, the only way I see a parametrization is with critical points of infinite order, e.g. $$\psi_E(t)=\begin{cases} (e^{1/t},0), & t <0 \\ (0,0), & t=0\\(0,e^{-1/t}) ,&t \ge 0\end{cases}.$$
Is there a smooth parametrization of $E$ having only one critical point of finite order?
Answer: Seems to be quite simple: Say, $\psi=(\psi_1,\psi_2)$ is a parametrization with $\psi(0)=(0,0)$ and there are $t_1<0<t_2$ such that $\psi(t_j)$ is on the $j$th axis. The intermediate value theorem implies that then $\psi(t)$ is on the first axis for all $t<0$ which implies that $\psi_2$ is $0$ for all negative $t$ so that all derivatives of $\psi_2$ vanish at $0$. The same argument implies that all derivatives of $\psi_1$ vanish at $0$.


A problem about the sign of pitch angle in rotation.

Question: The sign of pitch angle in rotation.
In the Yaw-Pitch-Roll convention, for example, XYZ-Zup coordinates system.
When I'm reading page 194-195 of 《Linear Algebra with Applications》 7ED, of STEVEN J.LEON
I have this question, In the example of concrete value 45, -30, 45, I've understood.
My question is why in the general version of rotation matrix of Pitch, the matrix is
\begin{align}\begin{array}{ccc}
 \cos  v & 0 & -\sin  v \\
 0 & 1 & 0 \\
 \sin  v & 0 & \cos  v \\
\end{array}\end{align}
Is there a sign limit of the Pitch angle, how to decide the direction of the rotation?
Answer: It depends on what you are doing.  If you have only one observation of a vehicle, the observation will be the same if pitch is increased by $360^\circ$ or any integer multiple.  If you have only one observation, it makes sense to restrict pitch to an interval of $360^\circ$, usually $0-360$ or $-180 \text{ to } 180$ with one end open and one closed (take your pick).  If you are following a vehicle, it makes sense to assume pitch is continuous, so you resolve the $360^\circ$ ambiguity by taking the closest value to the last observation.  The trig functions won't care, which is why you can do either.  If you want to use successive observations to define a pitch rate, I recommend the second.
Comment: Hi, I want to know the rotation's direction, how to define the direction.
Comment: Generally you pick a set of body axes, $x,y,z$ that are in a right hand configuration.  For an airplane, $+x$ is forward, $+z$ is down, and $+y$ is to the right.  A figure is [here](http://en.wikipedia.org/wiki/Flight_dynamics).  Then +roll is a positive rotation around $x$, a bank to the right, +pitch is positive around $y$, nose up, and +yaw is positive around $z$, a turn to the right.  You can choose your axes however you want, but it is good to follow the right hand rule when linking axes to rotation.


Chapter 12 Spivak Calculus: Spivak's comments about implicit differentiation

Question: There is a passage in the Chapter 12 exercises of Spivak's Calculus (which is a book specific to  real-valued functions) that reads as follows:

In general, determining on what intervals a differentiable function is defined implicitly by a particular equation may be a delicate affair, and is best discussed in the context of advanced calculus. If we assume that $f$ is such a differentiable solution, however, then a formula for $f'(x)$ can be derived by differentiating both sides of the equation defining $f$ (a process known as "implicit differentiation").

I would like to make sure I am correctly understanding this comment.
Consider two different expressions:

$[-f(x)]^5-f(x)=x$

$[f(x)]^3-3f(x)=x$

To spare some space, rather than derive statements about these expressions, consider their graphs   of solutions (respectively) when we rewrite the expressions as: $-y^5-y=x$ and $y^3-3y=x$.

|
In the first expression, we have that $f$ is a function on all of $\mathbb R$. In the second case, the graph reveals that $f$ is not a function on all of $\mathbb R$.
If I proceed with the implicit differentiation of 1., then I have:
$$f'(x)=\frac{-1}{1+5[f(x)]^4}$$
If I proceed with the implicit differentiation of 2., then I have:
$$f'(x)=\frac{1}{3[f(x)]^2-3}$$
In the first case, there is clearly a single $f$ defined on all of $\mathbb R$ that exists. So differentiating the expression implicitly strikes me as an acceptable 'cheat code' of sorts...to get around the difficulty of isolating $f$ to one side of the inequality.
In the second case, however, it is not apparent to me which function $f$ I am implicitly differentiating.  Is this what Spivak means in his passage when he writes, "If we assume that $f$ is such a differentiable solution..."? Under these circumstances, what exactly does it mean, logically, to assume that such an $f$ is a solution to the expression and can therefore be differentiated?
It is simply: "Suppose $f_1$ is one such solution to the expression (where $f_1$ may necessarily be defined on a subinterval of $\mathbb R$) and is also differentiable. Then its derivative can be found through the implicit differentiation approach"
Answer: This is what we call a "necessary condition". If $S \implies N$, then $N$ is a necessary condition for $S$, because it's impossible for $S$ to be true without $N$ also being true, but if $S$ is false then the truth of $N$ is unknown.
In this case, $S = $ "$f$ is a differentiable function satisfying the given equation" and $N = $ "The derivative of $f$ satisfies the equation that results from implicit differentiation". So if a function $f$ does indeed exist, then it is guaranteed that its derivative meets that criterion.
Indeed, as you show one of the equations does not define a unique function on $\mathbb{R}$, but you can define multiple functions on different domains to represent various parts of the relation, and each of those functions will still have matching derivatives.
For reference, the opposite of a necessary condition is a "sufficient condition". If $S \implies N$, then $S$ is a sufficient condition for $N$ because knowing that $S$ is true is enough to know that $N$ is true, but it's also possible for $N$ to be true without $S$. For example, "$f$ is a differentiable function" is a sufficient condition for "$f$ is a continuous function". If a condition is both sufficient and necessary, then we might say that it is equivalent, i.e. $A \implies B$ and $B \implies A$ means $A \iff B$.


How to get data from a table

Question: I have to select player name, Captain name from below mentioned table structure.
table structure are as follows.
create table #temp (Playerid int, PlayerName varchar (100), CaptainId int)
PlayerId     PlayerName     CaptainId
--------------------------------------
1            Dhoni          NULL
2            Sachin         1
3            Rahul          1

I have to select player name along with his captain name from this table.
Can anybody
Answer: Assuming the CaptainId references the PlayerId on the same table, you would want the following:
select t.PlayerName, t2.PlayerName as CaptainName
from #temp t
left join #temp t2 on t.CaptainId = t2.PlayerId

If you wanted to exclude players with no captain, you would make it an inner join.
You could convert the null, of course:
select t.PlayerName, isnull(t2.PlayerName,'None') as CaptainName
from #temp t
left join #temp t2 on t.CaptainId = t2.PlayerId

Answer: You can use a self join and table aliases.
Something like
SELECT p.PlayerName,
 c.PlayerName CaptainName
FROM #temp p LEFT JOIN
 #temp c ON p.CaptainId = c.PlayerId

Answer: there are various ways to get answer of this queries like:
select playerName, (select t2.playername from #temp t2 where t2.playerid = t.captainid  ) from #temp t

select t1.playername , t2.playername captain from #temp t1 left join #temp t2 on t1.captainid = t2.playerid

Answer: SELECT PlayerName, CaptainName
FROM PlayerTable INNER JOIN CaptainTable
ON PlayerTable.CaptainID=CaptainTable.CaptainID
WHERE CaptainName = 'your query'

Comment: your misunderstanding the question. there is only 1 table - #temp. A self join is required.
Comment: And he might not want an inner join, which would omit players with no captain

How to get data from a table


Animated container can't use border radius and box shape circle at the same time?

Question: I used the animated container to create a button. When the button is tapped it will turn into a circle at inside the container I am showing a circle progress indicator. Now the issue is when I try to make the container circle with the shape property. it throws and error. How can I solve this error.
The error message is
Failed assertion: line 129 pos 12: 'shape != BoxShape.circle || borderRadius == null': is not true.

Loading Button:
class LoadingButton extends StatelessWidget {
  const LoadingButton(
      {super.key,
      required this.status,
      required this.onTap,
      required this.text,
      this.width,
      this.textColor,
      this.backgroundcolor,
      this.margin,
      this.padding});

  final bool status;

  final String text;

  final double? width;

  final Color? textColor;

  final Color? backgroundcolor;

  final EdgeInsetsGeometry? margin;

  final EdgeInsetsGeometry? padding;

  final VoidCallback onTap;

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: onTap,
      child: AnimatedContainer(
        width: status ? 50 : 200,
        height: 45,
        alignment: Alignment.center,
        duration: const Duration(milliseconds: 350),
        padding: padding,
        margin: margin,
        decoration: status
            ? BoxDecoration(
                color: backgroundcolor ?? kGreen, shape: BoxShape.circle)
            : BoxDecoration(
                color: backgroundcolor ?? kGreen,
                borderRadius: BorderRadius.circular(30)),
        child: status
            ? const Padding(
                padding: EdgeInsets.all(5),
                child: CircularProgressIndicator(
                  color: kWhite,
                  strokeWidth: 3,
                ),
              )
            : CommonText(
                text: text,
                size: 14,
                fontWeight: FontWeight.bold,
                textColor: textColor ?? kWhite,
              ),
      ),
    );
  }
}

Comment: can you include how you;ve used this widget
Answer: I have solved this issued by wrapping the animated container with the ClipRRect Widget. For some reason we can't give Both the border radius and the BoxShape.circle to the container at the same time. And when I change the border radius to null. the container didn't changed completely from rectangle to circle.
InkWell(
      onTap: onTap,
      child: ClipRRect(
        borderRadius: BorderRadius.circular(30),
        child: AnimatedContainer(
          width: status ? 50 : 200,
          height: 45,
          alignment: Alignment.center,
          duration: const Duration(milliseconds: 350),
          padding: padding,
          margin: margin,
          decoration: BoxDecoration(
              color: backgroundcolor ?? kGreen,
              shape: status ? BoxShape.circle : BoxShape.rectangle),
          child: status
              ? const Padding(
                  padding: EdgeInsets.all(5),
                  child: CircularProgressIndicator(
                    color: kWhite,
                    strokeWidth: 3,
                  ),
                )
              : CommonText(
                  text: text,
                  size: 14,
                  fontWeight: FontWeight.bold,
                  textColor: textColor ?? kWhite,
                ),
        ),
      ),
    );


Measuring quantization error for clustering - squared or not?

Question:
When measuring the quantization error of a clustering, should the distance between samples/centroid be squared or not? I found both variants in the literature.
Furthermore, is (squared) quantization error not the same as squared sum of errors?
Answer: The point of the squared error is that it results out of the underlying assumption, that your data is distributed with a Gaussian random component. (Like noise on your measurements, e.g.)
The sum of squares error comes from the log probability. Say your points are distributed according to $p$, then you want to pick your parameters $\theta$ (for K-Means the centroids, e.g.) to maximize the probability of the data:
$$p(D) = \Pi_i p(x_i|\theta)$$
However, maximization of products is hard, so we maximize the log instead, which makes the product to a sum:
$$argmax_{\theta} \sum_i \log p(x_i|\theta)$$
Now, the density of the Gaussian distribution is someting like $\frac{1}{\sqrt{2\pi\sigma^2}}\,e^{ -\frac{(x-\mu)^2}{2\sigma^2} }$. If you take the log of this, you are stuck with what you find in the exponent and some constant terms. You ignore the variance in most cases. And voilá, that's where the squared distance comes from.
Since the Gaussian punishes outliers very much (because of the square), sometimes it is more robust to assume a distribution that has heavier tails, like student's-t or Laplace.
If you only measure the absolute distance, this comes from a Laplace assumption.
Thus, it is a question that the statistician has to answer - it's more part of the model. Of course, you can use a model selection method (like cross validation) that does this part of the job.


Switching files to read from in python's .csv reader

Question: I am reading a csv file several times, but cutting its size every time I go through it.  So, once I've reached the bottom, I am writing a new csv file which is, say, the bottom half of the .csv file.  I then wish to change the csv reader to use this new file instead, but it doesn't seem to be working... Here's what I've done.
                    sent = open(someFilePath)
                    r_send = csv.reader(sent)
                    try:

                        something = r_send.next()

                    except StopIteration:
                        sent.seek(0)
                        sent.close()
                        newFile = cutFile(someFilePath, someLineNumber)
                        sent = open(newFile, "r")
                        r_send = csv.reader(sent)

where cutFile does..
def cutFile(sender, lines):
    sent = open(sender, "r")
    new_sent = open(sender + ".temp.csv", "w")
    counter = 0

    for line in sent:
        counter = counter + 1
        if counter >= lines:
            print >> new_sent, ",".join(line)

    new_sent.close()
    return sender + ".temp.csv"

Why is this not working?
Comment: What part of it doesn't seem to be working? What error message are you getting? Also, is your top section of code in some sort of loop?
Answer:
Is something = r_send.next() in some kind of loop? The way you wrote it, it's only going to read one line.
Why do you need ",".join(line)? You can simply print line itself, and it should work.
Plus, there really is no need to seek(0) before closing a file.
Comment: Are these answers to @ahhh's problem? This seems like it should be in a comment to me.
Comment: @Wilduck - I agree that your way is more educational. Regarding your question:
(1) is a clarification.
(2) is the actual answer (as far as I see).
(3) is a general observation regarding the code.
Answer: I suggest the following:
Use for something in r_send: rather than something = r_send.next(); you won't even need the try... except blocks, as you'll just put the stuff closing the original file outside that loop (as someone else mentioned, you aren't even looping through the original file in your current code). Then you'll probably want to wrap all that in another loop so it keeps continuing until the file has been fully manipulated.
Use new_sent.write(line) instead of print >> new_sent, ",".join(line). Not that it makes that much of a difference besides the ",".join bit (which you don't need since you aren't using the csv module to write to a file), which you shouldn't be using here anyway, but it makes the fact that you're writing to a file more evident.
So...
sent = open(someFilePath)
r_send = csv.reader(sent)

someLineNumber = len(sent.readlines())

while someLineNumber > 0:
    for something in r_send:
        # do stuff

    someLineNumber /= 2     # //= 2 in Python 3

    sent.close()
    newFile = cutFile(someFilePath, someLineNumber)
    sent = open(newFile, "r")
    r_send = csv.reader(sent)

Something like that.


Why does this warning always show up? ("Boolean method 'areNotificationsEnabled' is always inverted")

Question: Why does the following warning always show up?

Boolean method 'areNotificationsEnabled' is always inverted

Code
public boolean areNotificationsEnabled() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        return notificationManager.areNotificationsEnabled();
    }
    NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(context);
    return notificationManagerCompat.areNotificationsEnabled();
}

Gradle
android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"

    defaultConfig {
        applicationId "com.test.app"
        minSdkVersion 21
        //noinspection OldTargetApi
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"

        ...
    }

I can add @SuppressWarnings("BooleanMethodIsAlwaysInverted") and ignore this warning, but what is wrong with my method?
Comment: what is your `compileSdkVersion` and `targetSdkVersion` `? is it greater than android N ?
Comment: @Teo Check Edit
Answer: The warning means this method always will return false, because you are always using ! inside a statement like if(!requirementChecker.areNotificationsEnabled()).
But if you add another statement without !, like if(requirementChecker.areNotificationsEnabled()), then the warning will be removed.
Comment: The warning still in screen when I remove first statement
Comment: I found the problem, In other class I always used `if(!requirementChecker.areNotificationsEnabled())` so always will be false.
Comment: Please edit your answer with my solution to select this is correct answer


How to Use UILabel instance Method

Question: As I m new to iphone programming,
and i have also done little bit of coding in it.
I never gone through the apple's documentation.
But now I just started reading it,and I found some methodes very hard for me ,
I am feeling hard to implement this,as SOF been a key for my coding ,
that's why I am asking this.Please tell me how to use UILabel class's
 instance method
<code>– (CGRect)textRectForBounds:limitedToNumberOfLines:
– (void)drawTextInRect:
</code>
if possible provide some code,thanks in advance,expecting your help.:)
Comment: This question is way too broad. You are almost asking for a tutorial on objective-c. Tell us exactly what you are trying to accomplish and then we can help you.
Comment: Given the names of the methods and what the docs say about them, what do you think they do?
Comment: @sosborn i m just asking what can i do via using these methodes,thanks for the responce.
Comment: @sosborn i want to use – (void)drawTextInRect: for my UILabel,i am not getting what docs says about them.how can i use it?
Comment: As was asked earlier: "Tell us exactly what you are trying to accomplish and then we can help you."
Comment: i want  to draw the receiver's text (or its shadow) in the specified rectangle.by using

- (void)drawTextInRect:(CGRect)rect
    and why this method is overridden.
Comment: That should have been your original question. Anyway, see my answer below.
Answer: The method "textRectForBounds:limitedToNumberOfLines:" returns the drawing rectangle for the label's text.
Syntax:
(CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines
bounds
The bounding rectangle of the receiver.
numberOfLines
The maximum number of lines to use for the label. The value 0 indicates there is no maximum number of lines and that the rectangle should encompass all of the text
This method should not be called directly, bUt it should be overridden by the sub class.
It can be overlaoded in the following way:
<code>- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines (NSInteger)numberOfLines
{
return CGRectInset(bounds, MARGIN, MARGIN);
}

- (void)drawTextInRect:(CGRect)rect
{
[super drawTextInRect: CGRectInset(self.bounds, MARGIN, MARGIN)];
}
</code>
Comment: [a link](http://developer.apple.com/library/ios/#DOCUMENTATION/UIKit/Reference/UILabel_Class/Reference/UILabel.html#//apple_ref/occ/instm/UILabel/textRectForBounds:limitedToNumberOfLines:)
Comment: thanks for ur responce!but answer what i asked above in comments,if u know!
Answer: If you want to draw the text in a specific rectangle you need to subclass UILabel and override <code>– (CGRect)textRectForBounds:limitedToNumberOfLines:</code>. Just remember to use your subclass instead of UILabel.
For example, let's say I want to draw text only on the left half of the label:
<code>- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines {
   //Original method returns the bounds, so let's find the left half of the bounds
   CGRect leftHalfRect = CGRectMake(0, 0, self.bounds.size.width/2, self.bounds.size.height);
   return leftHalfRect;
}
</code>
Because this method now returns left half rect of the bounds, you text will only draw in the left half rect.
Comment: It may be little strange ,but please explain if possible,If i have a label  in one view controller class then how to implement this method for text.Please explain little brief,thanks for your help and response.
Comment: You should take some time to read some Objective-C tutorials, especially with respect to subclassing. It is a core concept and it is clear that you are not comfortable with it.

How to Use UILabel instance Method


Django query not passing to AJAX in JSON Format

Question: I'm trying to simply fill a textfield with its corresponding database value using Django and AJAX. The goal is that when the dropdown value is changed the textfield auto-updates. I get the following error in console:

SyntaxError: Unexpected token < in JSON at position 3 & Uncaught
  ReferenceError: data is not defined

I have tried doing it without the JSON but then the data turns out to be the whole html code of the currently loaded page.
tasks.html
<form method="POST" id="function" function-url="{% url 'synctool:load_function' %}" novalidate>
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Execute</button>
</form>

urls.py
url(r'^$', views.load_script, name='load_function'),

views.py
def load_script(request):

    function_id = request.GET.get('function_name')
    query = serialize('json', Task.objects.filter(function_name_id = function_id).values(), cls=LazyEncoder)

    return query

Comment: Why exactly you need that being a JSON? It's just a string.
Answer: Apparently Django querysets and JSON dont really match. I was able to find the solution myself. The final code:
views.py
# Dynamic Load/Ajax
def load_script(request):

    function_id = request.GET.get('function_name')
    query = Task.objects.filter(function_name_id = function_id).values_list('script_location', flat=True).first()

    return HttpResponse(query)

tasks.html

urls.py
url(r'^load_function/$', views.load_script, name='load_function'),

Answer: views.py
import json

        def load_script(request):
            if request.method == 'POST':
                response_json = request.POST
                response_json = json.dumps(response_json)
                data = json.loads(response_json)
                query = data['function_name']
                data ={'query': query}
                return JsonResponse(data, safe=False)

and in js
    var patch = {'function_name': function_id}

      $.ajax(
                                        {
                                            url: url,
                                            dataType: "json",
                                            data:
                                             patch,
                                            success: function (data)
                                            {
                                                console.log('success')

                                                $("#id_script_location").val(data);
                                            },
                                            error: function(jqXHR, textStatus, errorThrown)
                                            {
                                            console.log('jqXHR:');
                                            console.log(jqXHR);
                                            console.log('textStatus:');
                                            console.log(textStatus);
                                            console.log('errorThrown:');
                                            console.log(errorThrown);
                                            }
                                        });
                                        console.log("ajax executed")

                                    });


Cut a square of side 10 into 100 equal quadrilaterals, each inscribed in a circle of diameter $\sqrt{3}$

Question: Problem. Cut a square of side 10 into 100 equal quadrilaterals, each of which is inscribable in a circle of diameter $\sqrt{3}$.
This is a Russian Mathematics Olympiad problem (турниры городов) for student of 8-9 grade (9-10 American equivalent).
Usually these problems have a rather short answer, not necessarily easy to come to.
So far I have managed to exclude the case in which the quadrilaterals have a right angle (and hence at least two of them).
Comment: Credits to the problem poser https://mathoverflow.net/users/17581/ilya-bogdanov :D
Comment: You managed to exclude a case leading to a simple solution, it seems.
Comment: What is the question? The problem you have mentioned is a statement...?
Comment: @u8y7541 I simply translated the problem from its original formulation in Russian. Instead of "Cut a square...", I could have written perhaps "Explain how can one can cut a square..."
Answer: A proof (almost) without words: the side length of the largest square is $2$.


New Account, change Duplicate E-mail error

Question: I run a drupal / civicrm build for a non-profit.  We are very careful with our members information, and want to make sure that no one trying to, would be able to figure out if someone they knew was a registered user.
The problem we have is when someone goes to create a new user account, if they use an e-mail that is already on our site, they get an error message saying that they can't use that e-mail because it's already registered on the site.
There are plenty of people - bosses, spouses, etc who could be testing an e-mail address to see if someone they know is on our site, and this error message pretty much confirms it.
Is it possible to change the error message to something else?  We have the e-mail confirmation enabled, why can't it say, "An e-mail has been sent to email@example.com with your login information?"
Answer: You can do a couple of things. One, I would advise installing the Username Enumeration Prevention module:
https://www.drupal.org/project/username_enumeration_prevention
This will stop forgot password form abuse.
Secondly, hiding this fact on the registration side is hard. You can't have duplicate email or usernames in Drupal (not easily), and if you get an error on that then it is pretty apparent it is already in use. Giving a vague error here could also confuse actual users who are trying to register.
Comment: I get why drupal makes it hard to edit the error messages - to keep people from writing some confusing message.  But I don't think it would be that hard for drupal to have an error message that prevents that kind of 'snooping'.   Something like, "We've sent a confirmation message to xyz e-mail, if that is not your e-mail address or you did not receive the e-mail, please click here to create a new account with your correct e-mail address.'