Unifying a real-valued function over two branches

Question: I have a function that I want to evaluate numerically. These three forms listed below are all identical algebraically for nonnegative real $u$ (aside from removable discontinuities at $u=0$ and $u=1$), but none avoids complex numbers for its entire domain.
$$\begin{aligned}
f_1(u) &= \frac{1}{\sqrt{1-u^2}}\tan^{-1}\frac{\sqrt{1-u^2}}{u} \\
f_2(u) &= \frac{1}{\sqrt{1-u^2}}\left(\frac{\pi}{2}-\tan^{-1}\frac{u}{\sqrt{1-u^2}}\right) \\
f_3(u) &= \frac{1}{\sqrt{u^2-1}}\ln\left(u+\sqrt{u^2-1}\right)
\end{aligned}$$
The first two have imaginary values of the square root for $u>1$ and the third has imaginary values of the square root for $u<1$. None are well-conditioned numerically in close proximity to $u=1$.
Any suggestions on a different form for numeric evaluation?
Answer: Using the series expansion
$$\ln(x)=\sum_{n=0}^\infty\frac2{2n+1}\left(\frac{x-1}{x+1}\right)^{2n+1}$$
gives, according to the third representation,
\begin{align}f(x)&=\frac1{\sqrt{x^2-1}}\ln\left(x+\sqrt{x^2-1}\right)\\&=\frac1{\sqrt{x^2-1}}\sum_{n=0}^\infty\frac2{2n+1}\left(\frac{x-1+\sqrt{x^2-1}}{x+1+\sqrt{x^2-1}}\right)^{2n+1}\\&=\frac1{\sqrt{x^2-1}}\sum_{n=0}^\infty\frac2{2n+1}\left(\frac{\sqrt{x^2-1}}{x+1}\right)^{2n+1}\tag{Rationalize}\\&=\frac1{x+1}\sum_{n=0}^\infty\frac2{2n+1}\left(\frac{x^2-1}{(x+1)^2}\right)^n\\&=\frac1{x+1}\sum_{n=0}^\infty\frac2{2n+1}\left(\frac{x-1}{x+1}\right)^n\end{align}
which is convergent for all $x\ge0$ and is well-conditioned near $x=1$. It doesn't seem to be the case that there is a nice representation of $f$ over $\mathbb R_{\ge0}$, but for $x>1$ it is related to the inverse hyperbolic tangent function.
Comment: how is x related to u? (i'm just having trouble finding which algebraic manipulations produced that little tidbit)
Comment: yeah, sorry, I can't figure out how you reached your 2nd equation :/
Comment: @JasonS I substituted $u+\sqrt{u^2-1}$ into the logarithm and simply rationalized the quotient which comes from $(x-1)/(x+1)$.
Comment: ... ok well my brain works a bit more slowly... I guess I can see this working if you put $x=u+\sqrt{u^2-1}=u+\sqrt{(u+1)(u-1)}$ into $\frac{x-1}{x+1}$ and then that becomes $\frac{\sqrt{u-1}}{\sqrt{u+1}}\cdot\frac{\sqrt{u+1}+\sqrt{u-1}}{\sqrt{u-1}+\sqrt{u+1}}$ and the 2nd term there is 1
Comment: I edited in some steps, hopefully it should be clearer now.
Comment: 2nd to 3rd line is still fuzzy, but I can see how to get there myself. (also fyi 2nd line is missing exponent $2n+1$ instead of 2)
Comment: oh nm, about the $2n+1$ exponent; i missed the horizontal scrollbar
Comment: OK: so if you write for the numerator $N=x-1 + \sqrt{x^2-1} = \sqrt{x-1}\sqrt{x-1} + \sqrt{x-1}\sqrt{x+1}$ and for the denominator $D=x+1 + \sqrt{x^2-1} = \sqrt{x+1}\sqrt{x+1} + \sqrt{x-1}\sqrt{x+1}$ then....
Comment: ... $N/D = \frac{\sqrt{x-1}}{\sqrt{x+1}}\cdot\frac{\sqrt{x-1}+\sqrt{x+1}}{\sqrt{x+1}+\sqrt{x-1}}$ and the 2nd factor is 1, so $N/D = \frac{\sqrt{x-1}}{\sqrt{x+1}} = \sqrt{\frac{x-1}{x+1}}$.
Comment: Yes that works.


Spectral Measures: Boundedness

Question: This thread is only Q&A!
Given a Hilbert space $\mathcal{H}$.
Consider a spectral measure:
$$E:\mathcal{B}(\mathbb{C})\to\mathcal{B}(\mathcal{H})$$
Regard the domain:
$$\int|f(\lambda)|^2\mathrm{d}\|E(\lambda)\varphi\|^2<\infty$$
And the calculus:
$$\langle f(E)\varphi,\chi\rangle=\int_\mathbb{C} f(\lambda)\mathrm{d}\langle E(\lambda)\varphi,\chi\rangle$$
Then equivalence holds:
$$\|f(E)\|<\infty\iff\|f\|_\infty<\infty$$
Especially one has:
$$\mathcal{D}f(E)=\mathcal{H}:\quad\|f(E)\|=\|f\|_\infty$$
How to prove this?
Answer: Suppose one has:
$$\vartheta:=\|f(E)\|<\infty$$
Regard the sets:
$$\Omega_n:=\{\vartheta+\frac{1}{n}\leq|f|\leq\vartheta+n\}\in\mathcal{B}(\mathbb{C})$$
And their union:
$$\Omega:=\bigcup_{n=1}^\infty\Omega_n=\{|f|>\vartheta\}\in\mathcal{B}(\mathbb{C})$$
Regard the functions:
$$1_n:=\chi_{\Omega_n}:\quad 1_n(E)=E(\Omega_n)$$
Denote for readability:
$$f_n:=f1_n:\quad\|f_n\|_\infty<\infty$$
For them one has:
$$\mathcal{D}f_n(E)=\mathcal{H}:\quad f_n(E)=f(E)1_n(E)$$
So one obtains inequality:
$$\left(\vartheta+\tfrac{1}{n}\right)^2\|E(\Omega_n)\varphi\|^2=\int\left(\vartheta+\tfrac{1}{n}\right)^21_n^2\mathrm{d}\nu_\varphi\\
\leq\int|f|^21_n^2\mathrm{d}\nu_\varphi=\|f_n(E)\varphi\|^2=\|f(E)1_n(E)\varphi\|^2\leq\vartheta^2\|E(\Omega_n)\varphi\|^2$$
That only holds for:
$$E(\Omega_n)=0\implies E(\Omega)=0$$
So it was bounded:
$$E\{|f|>\vartheta\}=E(\Omega)=0$$
Conversely one has:
$$\|f(E)\varphi\|^2=\int|f|^2\mathrm{d}\nu_\varphi\leq\|f\|_\infty\|\varphi\|<\infty$$
Therefore it holds:
$$\mathcal{D}f(E)=\mathcal{H}:\quad\|f(E)\|\leq\|f\|_\infty\leq\|f(E)\|$$
Concluding the assertion.

Spectral Measures: Boundedness


Combined Fields filters and missing custom search api fields

Question: Drupal 8
I am using Search API and Views to search several fields from several content and media types. For example, I have a custom "description" field for Media->files so users can add a searchable summary field to pdfs they upload to a website.
While I can get it set up to search all the fields using exposed filters and an "OR" filter grouping, this leads to an exposed filter for each field... which is not ideal. I would rather a single input box that allows several search terms to be passed to each of the filters.
I have tried to use combined field filter however it is missing a number of the fields passed from the Search API index. For example, below is a simple example searching only pdfs with a custom description field.

Media type and Name are available but not Description or even filename. Is there a way to make these available in the combined filter?
Any other method to achieve the desired result of a single search box for multiple filters would also useful. Just to re-iterate. The filters work, I just want them in a single search field.
Answer: It's kind of a beginner error here but in case it's useful to anyone the solution is you want to use the Search API Search filter rather than the combined filter.
It handles the search of the provided index all as a single input field by design.


the depth of a set

Question: The depth of a set X is the maximal number of nestings it contains. The definition runs as follows:
if X contains no set, depth(X) = 0

otherwise
depth(X) = max ({depth(Y)| Y ∈ X}) + 1,

(where max(M) is the maximal number of a set of integer numbers M). Given this definition, determine
(1) depth(S), S = {f, g}

(2) depth ({ {a}, {{{{a}}}}, {{a}} }

(3) depth (℘(℘(℘(℘(S)))))

hense I can consider that
(1) 0
(2) (1+4+2) +1 =8?
(3) 4+1 = 5?

Can please somebody explain? I did`t really get the idea
Answer: Think about a set with the membership inclusion as some sort of a tree. The root is the set $X$. Leaves, or terminal nodes, of the tree are elements which are not sets.
The we want to ask what is the height of the tree, what is the length of the longest branch? That, in a nutshell, the idea of the depth. At least when concerning a universe of just finite sets (what happens if you take an infinite set which has sets of every possible finite depth? There's no $\max$ for the definition! Well, then we need ordinals, but I'm getting ahead of myself.
Note that the definition is not to add all the depths of sets in $X$ and then add $1$. It's to take the maximal depth, and add $1$. So in the case of $(2)$ the answer is not $8$, but rather $5$.
In the third answer you might want to prove something first, $\operatorname{depth}(\wp(S))=\operatorname{depth}(S)+1$, and then you can easily reiterate it to find out the correct answer.
Comment: then in 1) depth is equal 1 and 3) 4?
Comment: @user144257: Well, are $f$ and $g$ sets? If not, then $\{f,g\}$ is a set which contains no sets. In the fourth question, that depends on the depth of $S$.
Comment: yes right, just got cobfused. the first set contains no set so it should be still 0.
But about the last one...it`s still not clear.
Comment: Well, it's not clear what is the depth of $S$?
Comment: no, the depth of S should be 0 in (1) task
Comment: i didnt get the last one with the power set
Comment: I meant about the last one, with the power set. This is a repeated power set operation from *some* set $S$, do you know what this set is? What is its depth? In either way you can easily write it as a function of the depth of that $S$. If it's the same $S$ from the first part, then you already have the answer.

the depth of a set


Dictionary: Find same value using different but identical instances as keys

Question: Is it possible to achive the following behaviour from a dictionary in a convenient way:
Dictionary<MyObject, double> d = new Dictionary<MyObject, double>
MyObject foo = new MyObject("foo");
d[foo] = 1.0;

Console.Write(d[new MyObject("foo")]) ---> 1.0

The example is simplified, I am using a slightly more complex Object as key.
Edit replaced String with MyObject
Comment: I dont get it, different but identical instances? Your code works as expcted. It prints `1`.
Comment: with `string` it will work correctly ("out of the box")... With other object types, you have to override `GetHashCode` and `Equals`
Comment: It is to different strings, but identical contents. new MyObject() == new MyObject() --> False
Comment: usually you do `if (!d.ContainsKey(foo)) { d.Add(foo, 0) } d[foo] = 1.0;`
Comment: @CallumLinington: Why? OP's approach is more efficient.
Comment: What happens in the OPs approach if a key already exists?
Answer: Yes, it is possible, as long as the corresponding Equals() method of your key returns true, and GetHashCode() returns the same integer value for what you call different but identical instances.
In your example the result is 1.0 because String.Equals compares contents of the strings, not references (although, to be precise, references in your example will most probably be the same as well, because the compiler usually pools identical strings).
EDIT: this paragraph applied to the original question, where the OP used string as the key.
If you use custom class for keys, just override its Equals method to achieve desired behavior. Don't forget to override GetHashCode() as well for efficient dictionary lookup, see this for reasoning: Why is it important to override GetHashCode when Equals method is overridden?
Comment: Thank you, I must have made an error in my GetHashCode implementation. I'll do some testing :)
Comment: Always override `Equals` **and** `GetHashCode`. You can also implement an `IEquatable` or an `IEqualityComparer`. The former works implicitly, the latter by using [this dictionary constructor](https://msdn.microsoft.com/en-us/library/ms132072(v=vs.110).aspx).
Comment: @Tim Schmelter, good point, re-phrased my answer to include your recommendation


Agrupar hashes por valor em Ruby e manipulá-los

Question: Eu tenho esse array com hashes que simplifiquei para ficar menor. Meu objetivo é juntar pela marca dos carros para fazer um pequeno relatório mostrando o quanto aquela marca está lucrando baseado nas compras. Repare que a "marca1" repete 2 vezes e não quero que isso ocorra no relatório.
carros = [
  {
     modelo: 'modelo1',
     marca: 'marca1',
     compras: [{preco: 20000}, {preco: 30000}]
  },
  {
     modelo: 'modelo2',
     marca: 'marca1',
     compras: [{preco: 45000}, {preco: 60000}]
  },
  {
     modelo: 'modelo3',
     marca: 'marca2',
     compras: [{preco: 77000}, {preco: 23000}]
  }
]

Queria que o resultado final fosse algo do tipo:
Marca: marca1
Vendas realizadas: 4
Valor total: 155000
--------
Marca: marca2
Vendas realizadas: 2
Valor total: 100000

Answer: Uma forma de fazer essa manipulação é usando each_with_object inicializando com um hash vazio. Então para cada nova marca encontrada inicializa um hash para a marca com contadores zerados e soma as compras e valor total de cada carro.
carros.each_with_object({}) do |carro, marcas|
  marca, compras = carro.values_at(:marca, :compras)
  marcas[marca] ||= {vendas: 0, valor_total: 0}
  marcas[marca][:vendas] += compras.size
  marcas[marca][:valor_total] += compras.inject(0) { |soma, compra| soma += compra[:preco] }
end

Resultado:
{
  "marca1" => {
    vendas: 4,
    valor_total: 155000
  },
  "marca2" => {
     vendas: 2,
     valor_total: 100000
  }
}

Comment: Consegui adaptar para o meu problema, obrigado.


lighttpd authentication before redirection from https to http

Question: I would like to redirect from https to http after authentication so credentials go through a secure channel but everything else is transmitted in plain.
Here it is the relevant part of the conf file:
## Auth
# https://redmine.lighttpd.net/projects/1/wiki/docs_modauth
# type of backend
# plain, htpasswd, ldap or htdigest
auth.backend               = "htpasswd"
# for htpasswd
auth.backend.htpasswd.userfile = "/etc/apache2/auth.htpwd"
auth.require = ( "" =>
        (
                "method" => "basic",
                "realm" => "Authorization required",
                "require" => "valid-user"
        )
)

## Simple SSL
# https://redmine.lighttpd.net/projects/1/wiki/HowToSimpleSSL
$SERVER["socket"] == ":443" {
        ssl.engine = "enable"
        ssl.pemfile = "/etc/lighttpd/certs/lighttpd.pem"
}

## Redirect from https to http
# https://redmine.lighttpd.net/projects/1/wiki/HowToRedirectHttpToHttps
# https://redmine.lighttpd.net/boards/2/topics/3988
$HTTP["scheme"] == "https" {
        $HTTP["host"] =~ "([^:/]+)" {
                url.redirect = ( "^/(.*)" => "http://%1:1234/$1" )
        }
}

So far redirection is executed before authentication.
Any ideas?
lighttpd 1.4.35 on Linux 4.1.19
Comment: A bit irrelevant, but what if somebody goes directly to http without authentication? I don't see you setting any kind of token/cookie.
Comment: True. But now it does not bother me.
Answer: I answer myself.
My question makes no sense. HTTP is a stateless protocol, so even if I could authenticate over SSL and then jump to HTTP, credentials will always be send in plain in subsequent HTTP requests.


Variável PHP no JavaScript

Question: O método simples e prático que encontrei aqui no Stack de passar uma variável PHP para uma JS funcionou bem até agora. Porém, com um certo conteúdo funciona apenas se eu alimentar essa variável PHP, mas deixar essa variável receber esse conteúdo através de uma query, não. (OBS: O set result completo da query tem 13.700 caracteres)
<?PHP
    $consulta = mysql_query("SELECT MODELO FROM celular_banco");
    while($resultado=mysql_fetch_array($consulta))
    {
        $fracasso .= $resultado["MODELO"].',';
    }
  echo $fracasso; // LGA270.AVIVBK,LGA270.ACLRBK,
  $sucesso = "LGA270.AVIVBK,LGA270.ACLRBK,";

?>

FUNCIONA

Não FUNCIONA

Comment: Tente isso no `PHP`: `echo (string) $fracasso;`
Comment: As variáveis duvida nos dois scripts serão var duvida = ''; Tem que ser  e  Ou `` e ``
Comment: Precisamos do echo senão o JS não entende. Ou eu não entendi sua ajuda...
Comment: Camarada. Infelizmente não funcionou com o (string)
Comment: Por quê exatamente você precisa passar esse conteúdo para o JS, para ele escrever no documento? Simplesmente não faz sentido isso e, se viu algo assim aqui no site, seria legal informar, pois tem coisa muito errada aí.
Comment: Anderson, Vamos lá: Primeiro peguei o script de autocomplete no W3schools. Nesse script o JS tem uma array com os itens já pré-definidos (países). Aqui eu estou precisando colocar um conteúdo provindo de uma query do php. Por isso eu estou tentando passar a variavel PHP para JS. Já fiz isso diversas vezes com barcode e outros mas agora não sei porque raios não funciona... Consigo até passar outros valores de uma consulta simples. Mas quando tento passar o resultado dessa While não dá certo. Estou muito desconfiado que o problema é essa While. Mas não sei o que esta bloqueando.
Comment: O que vi aqui no Stack e ja fiz muito e deu muito certo até o momento foi o esquema de conversão PHP>JS. Postei o código na própria pergunta (A variável $sucesso)
Answer: Se o seu PHP entrega o próprio HTML ao cliente, o JavaScript nem precisa entrar na história. Isso que tentou fazer, mesmo que tenha visto no W3Scholls ou aqui mesmo no site, é gambiarra.
O que você pode fazer é entregar o HTML pronto. Algo como:
<input list="modelos" />
<datalist id="modelos">
<?php
  $consulta = mysql_query("SELECT MODELO FROM celular_banco");

  while($resultado = mysql_fetch_array($consulta))
  {
    echo "<option value='{$resultado['MODELO']}'/>";
  }
?>
</datalist>

Isso gerará para o cliente um HTML do tipo:

<input list="modelos" />
<datalist id="modelos">
  <option value="Foo"/>
  <option value="Bar"/>
  <option value="Baz"/>
  <option value="Acme"/>
  <option value="Zing"/>
</datalist>

Que possui a propriedade de sugestão conforme o usuário digita.
Pra que serve a tag </datalist>?
Outra opção que você tem é alimentar sua sugestão no formulário de forma assíncrona, via requisição AJAX, mas se você já entrega o HTML pronto com o PHP, não há necessidade de mais uma requisição.
Comment: Anderson!! E-s-p-e-t-a-c-u-l-a-r cara. Você OBLITEROU minha dúvida. Essa tag Datalist é tudo que eu precisava. SUCESSO INFINITO PRA VOCÊ MEU CHARÁ!!!!!
Answer: Parece que a variável $fracasso só existe dentro do while, tente:
<?PHP
    var $fracasso = '';
    $consulta = mysql_query("SELECT MODELO FROM celular_banco");
    while($resultado=mysql_fetch_array($consulta))
    {
        $fracasso .= $resultado["MODELO"].',';
    }
    // Não entendi a necessidade das linhas abaixo...
    echo $fracasso; // LGA270.AVIVBK,LGA270.ACLRBK,
    $sucesso = "LGA270.AVIVBK,LGA270.ACLRBK,";
   ?>

JS (Havia faltado a parte do JS, deve ser adicionado o echo para funcionar corretamente)

Comment: Celso, postei as linhas abaixo somente para mostrar que no PHP qualquer uma ecoam normalmente, Mas somente a $sucesso é recebida pela JS. To ficando maluco ja com isso...
Answer: Tente isso:

Comment: Leandro, Dentro da função, a página não traz resultado nem com um texto simples.

Variável PHP no JavaScript


Forçar o redirecionamento para ambiente HTTPS

Question: Como forçar o redirecionamento para o ambiente com HTTPS com HTACCESS?
Preciso que o código seja adaptado ao que já tenho:
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.*)$ index.php?url=$1

Answer: Tente inserir essas linhas :
RewriteCond %{HTTPS} !=on
RewriteRule ^ HTTPS://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]


Ação após voltar aplicativo de segundo plano

Question: Tenho uma webview no android que sempre verifica se há internet ao voltar do segundo plano verificando se foi mudado o estado de conexão caso esteja offline o app envia o usuário para uma tela de "reconecte-se e tente novamente" usando o código abaixo:
protected void onResume() {
        super.onResume();
        mWebView.onResume();
        if (isConnected(getApplicationContext())){
        } else {
            Intent i = new Intent(MainActivity.this, off.class);
            startActivity(i);
            overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
            finish();
        }
    }

Até ai tudo bem fiz uma versão para ios dessa webview mas não consegui reproduzir essa verificação quando o app retorna de segundo plano, como reproduzo esse "onresume" no swift do ios? (o código que verifica o estado de conexão já tenho)
Answer: Complementando a resposta do Rodrigo, apesar de o viewDidAppear ser uma possibilidade, esse método não chamado quando o app retorna de segundo plano. Na verdade viewDidAppear é chamado quando a view do ViewController se tornou visível. Isso nem sempre ocorre quando o app entra em primeiro plano.
Se a intenção é de fato perceber quando o app recebe o foco, ao invés de depender do ciclo de vida de UIViewController (ex: viewWillAppear, viewDidAppear), o correto é utilizar os métodos do ciclo de vida da aplicação (UIApplication).
Nesse caso você pode utilizar applicationWillEnterForeground: ou applicationDidBecomeActive:. Eles são chamados no AppDelegate quando os eventos acontecem.
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        return true
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
    }
}

Caso no seu código faça mais sentido que esses callbacks sejam disparados em uma classe específica, como um UIViewController por exemplo, você pode utilizar o sistema de notificação.
NotificationCenter.default.addObserver(forName: UIApplication.didBecomeActiveNotification, object: nil, queue: nil) { _ in
    //...
}

Answer: Segundo o ciclo de vida do iOS, o similar do onResume do Android, seria o viewDidAppear():
override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        //sua lógica
}

Na documentação diz também sobre o viewWillAppear(), que seria um passo antes do viewDidAppear(). Veja qual te serve melhor!


Use PowerDNS to update AD Integrated DNS Zone

Question: Before I embark on the experiment, I figured I might ask the community at large.
So I've got an odd situation that I'm trying to remedy. I have Terraform deploying virtual machines (Linux and Windows) into an on-premise datacenter (VMWare) with an Infrastructure predominant Windows (AD, AD-DNS, etc.). TF deploys the VMs into a DHCP VLAN with dynamic DNS, but when the host is re-deployed, the DHCP lease sticks around, and causes issue with the DNS record getting updated.
What I'm looking to do is deploy PowerDNS as a DNS server (since it has a Terraform Provider), and utilize that not as it's own Zone, but as a slave to the AD Integrated DNS Zone.
Before I spend a day or two tinkering with this, does anyone out there use PowerDNS to update DNS records in an AD Integrated DNS Zone? My google-fu isn't giving me much clarity on which directions I can update.
Answer: I don't really see how introducing a third-party DNS solution is going to help your situation.

Is it a Windows DHCP solution?
Are both Windows and Linux clients affected?
What's the DHCP lease interval? (Hint: is it longer than the interval you typically "recycle" machines? e.g. you redeploy machines daily, but your leases are 7 days)
Are you redeploying the same machines to the same subnets and if so, have you considered reservations? (Yes, some admin overhead setting it up, but it can be scripted and it takes care of itself if you ensure stale reservations are removed regularly.)
If it's Windows DHCP, are the options Always dynamically update DNS A and PTR records and Discard A and PTR records when lease is deleted enabled? (Not sure how that might work with Linux clients, it's been a while.)
Finally, what's the no refresh interval in the Aging properties for the DNS zone? Hint: is it greater than the DHCP lease interval?

And some resources:

The main Microsoft article on configuring dynamic DNS, with reference to Windows DHCP.
This article describes the no-refresh and refresh intervals on Windows DNS and how that works with scavenging. The records don't need to be scavenged to be refreshed (as long the record age has exceeded the no-refresh interval).  But if you don't want confusing records cluttering up DNS, set these all to fairly low intervals, as in hours rather than days.


Load balancing - Multiple servers, different locations

Question: I've been scaling out a service very rapidly, and have found a problem in the way I've been balancing the load.  My servers do not need a perfectly even distribution, so I was simply using a round robin DNS setup to direct clients to the servers.
However, it is very important that a client not be bounced between servers, and I've found that many of the clients running their software on Ubuntu do NOT cache the DNS result they receive, so they are constantly changing which server they communicate with.
Is there any way to force a DNS record to stick to them, or will I have to begin looking at a software or hardware load balancer?  My concern is the latency of a load balancer.  If the LB is in the US and the client is directed to the UK, my understanding is the client will always have to connect to the US load balancer before being redirected to the UK.
Answer: Unfortunately, there is no way to force a DNS record to stick to a particular user. A load balancer could track a user's session and always send them to the same server. However, it seems that you're running into issues with geographically separated application instances.
In this case, your best bet would to have the following setup:

Have a subdomain for each geographic area you want to represent that contains the IPs for servers in that area. us.yourdomain.com and uk.yourdomain.com
Have a web server handling the www.yourdomain.com record, or whatever users typically type in, that utilizes a Geographic lookup system (such as GeoIP) to redirect users to the appropriate subdomain.

Using this architecture, an initial HTTP request for a user in the US would look something like this:

User requests www.yourdomain.com.
Server handling www.yourdomain.com looks up geographic area of user.
Server determines that user is in the US.
Server redirects user to us.yourdomain.com.
User's browser accepts redirect, and all subsequent requests go to us.yourdomain.com.

This setup will require a total of at least 3 servers. One handling US requests, one handling UK requests, and one that handles redirecting users to the US/UK sites.
Answer: Sticky sessions suck!
While it may be inconvenient that users get sent around various machine, one of the main reasons for using RRDns is for availability. If you need to keep your users on the same server then you loose the benefits.
Certainly pushing users preferentially to a nearby server delivers good performance benefits - most large DNS providers now offer geo-aware DNS lookups (without the expense of a full content delivery network). And if you're feeling brave and do your own name serving, then you can configure bind to do it for you. Note that with normal RRDNS, the hosts are served up in a random order by the nameserver - it's quite possible to have a failover config where the 'local' servers are always presented in the same order to the same clients along with a failover list which always appears at the end.
A lot of what is appropriate depends on the scale you are working at. If you're confident that you've got good availability within each datacenter, then using a local load balancer at each datacenter might be the way to go (checkout HA-Proxy and Varnish).
Comment: GSLB at the DNS is the best way to do this. That way, European lookups are answered by multicast DNS nodes in Europe and directed to your European site. Some services will also offer monitoring, so traffic redirects to the other site in the event of a site failure.
Answer: Round robin DNS resource record set shuffling doesn't do what you think it to do, and doesn't do what you want.  Use SRV resource records or a proper load balancer.


What kind of notation is this?

Question: Working on Analyzing this Motet by Dufay, most of this fits a certain type of notation (I don't know the English name) but some doesn't. What's your opinion?
Comment: Also: does the treble clef with the 8 mean that it's transposed down by an octave?
Comment: Are the first two systems m. 1, and systems 3 and 4 m. 57?
Comment: @Richard indeed
Answer: The older type of notation seems to be a form of mensural notation common in the Renaissance era (when Dufay was active).
Mensural notation wasn't really codified quite like today's notation was, so there are different formats to it; in a way, it's like there are dialects of mensural notation. Here's another sample of a different piece:

Sometimes scores will mix mensural notation with modern notation just to give the performer an idea of the original notation. Usually I see the mensural portion before the piece; I've never seen it at the start of the piece like this. Perhaps there's another name for this hybrid notation that I'm not familiar with.
The double whole notes in the fourth system are still seen today, but the dotted double whole note of the top system, and the stemmed version in the second system, are much more rare. (I've never personally seem then in a context outside of Renaissance music.)
As for the barlines, this is an example of what we call Mensurstrich notation; since barlines were not really a thing in the Renaissance, these barlines are used in modern editions, only written between the staves, to help modern performers who are used to barlines.
And yes, the treble clef with the 8 on the bottom means it sounds an octave below it is written.
Comment: Sometimes it's easiest to just use the German term; I've never heard of anyone using an English translation of it. (Kind of like how we also say *Leitmotive*.)
Comment: Thx, I guess there is no English word for Mensurstrich notation? I'm German so I thought that this was just the German translation^^

What kind of notation is this?


Gaussian type and Euclidean sections

Question: I have a second question about Chapter 9 in Milman and Schechtman's book "Asymptotic theory of finite dimensional normed spaces" (first question here). It's about the proof of Theorem 9.7 (pg. 55). Here's a scan of the theorem and first paragraph of the proof.

I don't understand the first sentence of the proof. By definition, a normed space $X$ is said to have Gaussian type $p$ constant $\alpha$ if for all $x_1, \dots, x_n \in X$, $\alpha$ is the smallest value such that:
$$\left(\mathbb{E}\|\sum_{i=1}^n g_i x_i\|^2\right)^{1/2} \leq \alpha \left(\sum_{i=1}^n \|x_i\|^p\right)^{1/p} $$
where the $g_i$'s are independent gaussian variables. Hence, if the type 2 constant is $\alpha$, it would imply that:
$$\mathbb{E}\|\sum_{i=1}^n g_i x_i\| \leq \alpha \left(\sum_{i=1}^n \|x_i\|^2\right)^{1/2} $$
But this inequality is in the opposite direction as that shown in the proof...
I initially thought that it's a typo, but actually, the inequality in the given direction is crucially needed later on in the proof. I'm probably missing an easy point, but somehow, I'm having trouble getting it. Thanks!
Answer: Notice the role of $\alpha$ in the claimed inequality for $k$ - it provides a lower bound there. Thus, the essence of the assumption is that the type $p$ inequality does not hold for any smaller value of $\alpha$. Which is the same as saying that the reverse inequality holds for some collection of $n$ vectors.

Gaussian type and Euclidean sections


Having problems using drop-down menu variables to create a table filled with these variables in PHP

Question: I am a PHP beginner and I am stuck on an assignment for school. I have to create 6 different drop down menus (num1 , num2 , num3 , num4 , rows , columns) each with the numbers 1 through 10 in it. I then have make sure the form is submitted, and only when it is submitted all perfectly, then I have to use the variables to create a table based on even and odd numbers.
<form method="post" action="prelab2.php">
<select name="num1">

<option>Pick one</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
<option>9</option>
<option>10</option>

</select>

Above is the drop-down menu, now this is where I am really stuck.
<?php
$_POST['submit'];
$num_1=$_POST['num1'];
$num_2=$_POST['num2'];
$num_3=$_POST['num3'];
$num_4=$_POST['num4'];
$rows=$_POST['rows'];
$cols=$_POST['cols'];
?>

I figured out how to $_POST the variables, but how can I take these variables (only on submit) and turn it into a table?
This is the link to my assignment
Comment: Hint: you could loop through your `$_POST` values and create the `` tag elements (``, ``) as you go...
Answer: Welcome to SO. $_POST['submit'] is not neccesary. In your PHP script, create the HTML for the table, and then <?php echo $num_1; ?> (or the others) where needed. The HTML must be outside the PHP code.
Answer: A line like $_POST['submit']; has no side effect... That is, it does nothing. You're just reading the variable value and not storing it anywhere.
What you're searching for seems to be echo. It writes content to the output, in your case the HTML page.
In a template-style, you can use it this way:
<?php
    // initial PHP code (reading form value, etc.)

    $title = 'Foo';

    // after the closing tag, starts the output
?>

    <title><?php echo $title; ?></title>

Notice the PHP echo statement embeded into the HTML markup.
So now, you just have to compose your HTML page as intended, using your own variables...
Answer: Start here: http://www.w3schools.com/tags/tag_option.asp
<select>
  <option value="n1">Volvo</option>
  <option value="n2">Saab</option>
  <option value="n3">Opel</option>
  <option value="n...">Audi</option>
</select>

<?php $n1 = $_POST['n1']; ?>

Answer: if(isset($_POST['submit']))
{
//check if form is submitted
echo '
'; //css trick to make nicer borders

//get post vars

$num_1=$_POST['num1'];
$num_2=$_POST['num2'];
$num_3=$_POST['num3'];
$num_4=$_POST['num4'];

//put number values in array

$nums=array($num_1,$num_2,$num_3,$num_4);

//sort array -> we will need it for outpu

sort($nums);

$rows=$_POST['rows'];
$cols=$_POST['cols'];

for($i=0;$i<$rows;$i++)

{
//print rows in loop
echo '
';

for($j=1;$j<=$cols;$j++)

//now print colums -> starting from one!

{

echo '';

//modulo operator, to check if we are inside even or odd column

if($j % 2 == 0) {

foreach($nums as $num)

// loop thorough array of numbers

{

//if number is even -> print it

    if($num % 2==0) {

        echo $num;

    }

}

}

else  {

    //if we are in odd row

    foreach($nums as $num)

{

    //print odd numbers
    if($num % 2 !=0) {

        echo $num;

    }

}

}

echo '	';

}

echo '
';

}

echo '
';

}

P.S. I know that this could get many down votes, but... :)


RewriteRule fails if called after line 112 of .htaccess

Question: I'm having an issue that is similar to this question.
In short, I'm trying to use some custom RewriteRules to point old (no longer functioning) urls to new working urls. To accomplish this, I'm trying something similar to:
RewriteRule ^oldsite/directory/ABCD(.*)\.html? /search/$1 [NC,R=301,L]

The issue is, this is completely ignored (as mentioned in the question linked to before.) However, I've noticed that if I move my RewriteRule from the bottom of the .htaccess file up a bit to line 112, which is:
# Pass all requests not referring directly to files in the filesystem to
  # index.php. Clean URLs are handled in drupal_environment_initialize().
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^ index.php [L]

The the rewrite rules work just perfectly fine. The answer to the previous question said that you couldn't use a clean url destination. So this would work:
RewriteRule ^home/code/([^/]+) ?q=home/software/node/&code=$1

but this won't:
RewriteRule ^home/code/([^/]+) home/software/node?code=$1

Problem is neither of them seem to work for me. I remember a few D7 updates ago there was an update to the .htaccess files. Could that be effecting this? Is there another way around this issue to get RewriteRules to work?
Answer: Just put it above line 112. The reason it doesn't work below that is line 117:
RewriteRule ^ index.php [L]

that [L] means that if the conditions above it match and that rule is applied no further rules will be checked. If you put it above that line clean or non-clean style url will work fine but probably don't want to include an L on the end of your rule so use:
RewriteRule ^home/code/([^/]+) home/software/node?code=$1 [R=301,NC]

on line 111 (well whatever actual content rule you need).
Answer: RewriteRule has issues for some reason, but RedirectMatch doesn't. I suspect this is because the RedirectMatch is part of mod_alias, and the RewriteRule stuff is part of mod_rewrite. Both get applied, but at different points in the processing, and is likely RedirectMatch is better suited in this situation.
So instead of:
RewriteRule ^oldsite/directory/ABCD(.*)\.html? /search/$1 [NC,R=301,L]

use:
RedirectMatch 301 /oldsite/directory/ABCD(.*).html$ /search/$1

Not sure why this works, but it does work.


How to use ajax call to pass json data to controller and render a partial view as result?

Question: I need to pass model object to controller, and from there to call service to generate data for the partial view.  I am able to pass the json object to the main view, and I am able to generate the partial view.  However, I am having difficulties to render the partial view in the main view after the call. If I don't pass object to controller, I am able to render the partial view.
My Main goal is: to pass json object and render partial view with the same ajax call.
Would appreciate help on this.
I apologize for the lengthy code here, but not sure how I could do it some other way.
The following code works, where I do not pass Json object via ajax call, and create department object in the controller:
main view code:
@model PartialViewDemo.Models.School
....

    ....

        @Html.Partial("_MyPartialView", Model.Department )

    ....

    <input type="button" value="Click" id="btnClick"/>

controller code:
public ActionResult Index()
{
    var model = new School();
    model.Department = GetDepartmentList(3);
    return View(model);
}

public List<Department> GetDepartmentList(int counter)
{
    var model = new List<Department>();
    for (var i = 1; i <= counter; i++)
    {
        var data = new Department();
        data.DepartmentName = "Dept " + i;
        data.DepartmentRule = "Rule " + i;
        data.Comment = "Comment " + i;
        model.Add(data);
    }
    return model;
}

public PartialViewResult ShowPartailView()
{
    Department dept = new Department()
    {
        DepartmentName = "test Dept",
        DepartmentRule = "test rule",
        Comment = "We Rock!"
    };
    PartialViewResult result = PartialView("_MySecondPartialView", dept);
    return result;
}

Partial view code:
@model PartialViewDemo.Models.Department

_MyView from partial view using PartialView

@if (Model != null)
{

                ....

                    @Model.DepartmentName
                    @Model.DepartmentRule
                    @Model.Comment

}

Model:
public class Department
{
    public string DepartmentName { get; set; }
    public string DepartmentRule { get; set; }
    public string Comment { get; set; }
}

public class School
{
    public List<Department>  Department { get; set; }
}

However, when I pass in Json object to ajax call with all other code stay the same, except the following changes, the partial view won't show with click event.
$.ajax({
    url: '/home/ShowPartailView/',
    data: JSON.stringify(dept),
    dataType: 'json',
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    success: function (result) {
        $('#divTest').html(result);
    },
    failure: function (errMsg) {
        alert(errMsg);
    }
});

with controller code:
public PartialViewResult ShowPartailView(Department dept)
{
    PartialViewResult result = PartialView("_MySecondPartialView", dept);
    return result;
}

Comment: Show you code! What have you tried?
Comment: Just updated with code and result.
Comment: You can just use `data: dept,` and delete the `contentType: ...` option
Comment: Tried that, still no cigar.
Answer: In the second example where you pass the object, you have specified the
dataType: 'json',

ajax option but your controller method is returning a partial view so it needs to be
dataType: 'html',

Side note: You can omit the contentType option and just use data: dept,
Comment: Yes, contentType is what your send to the controller and dataType is what you get back
Comment: Thank you, That worked!  So  the dataType in the ajax call is for the response, and not for the  request, right?
Answer: If you have return partial view then try this to render partial view in Div or any other element.
$(document).ready(function () {
    $.ajax({
        url: '/YourContollerName/YourActionName',
        type: "POST"
    })
    .success(function (result) {
     $('.loadOnDivClass').empty();
     $('.loadOnDivClass').html(result);
 })
  .error(function (status) {
      alert(status);
  })

});

If Contrller Action return like this
return PartialView("_PartialList",modelObj);
Comment: This is not what I want. please see my edit above. I wanted to pass json object and render partial view with the same ajax call. which I am not able to accomplish that


"/etc/apache2/httpd.conf: No such file or directory" error after Ubuntu upgrade

Question: So I upgraded Ubuntu and I went to 127.0.0.1 in Chrome and got "Oops! Google Chrome could not connect to 127.0.0.1" so I restarted Apache but was met with this error:

apache2: Syntax error on line 215 of /etc/apache2/apache2.conf: Could not open configuration file /etc/apache2/httpd.conf: No such file or directory
Action 'configtest' failed.
  The Apache error log may have more information.
         ...fail!

This is the contents of my /etc/apache2 folder:
conf.d/
mods-available/
mods-enabled/
sites-available/
sites-enabled/
apache2.conf
apache2.conf.dpkg-dist
envvars
magic
ports.conf

What's going on? How can I resolve this?
Comment: It appears within your /etc/apache2/apache2.conf file, the file /etc/apache2/httpd.conf is being included or referenced. Try searching for this within your /etc/apache2/apache2.conf file to see where and provide that if you require further assistance.
Comment: I had the same problem after upgrading do Debian Wheezy, the accepted solution worked.
Answer: For some reason you are missing the http.conf which usually has no content.
Please try to create it and restart your web server

touch /etc/apache2/httpd.conf
Comment: This means: You are creating an empty file called httpd.conf in  /etc/apache2/ directory to overcome the error that prevented the apache to start because of the missing file.
Comment: I have no idea what this means but it worked. Thanks!
Comment: In my case, on debian rasperry the apache2.conf was missing. I created one. Then I got  apache2: Configuration error: No MPM loaded. I reinstalled apache2 and then finally got ` mpm_event_module (shared)` with `apache2 -M`. Now it works.


Convert CameraImage to Jpeg and display flutter on android and ios

Question: I am starting a CameraStream with ImageFormatGroup.nv21 and like to use the CameraImage to convert it to an JPEG for further proccesing, im only finding older implementations of this but nothing that works now,
starting Camera controller like this:
<code>_controller = CameraController(
      widget.camera,
      ResolutionPreset.medium,
      imageFormatGroup: ImageFormatGroup.nv21

    );

//

await _controller.startImageStream((CameraImage image) =>
            {
              processImage(image)

            });
</code>
I am using Flutter 3.10.5
I have searched for a solution that can convert cameraImage, all the solutions i found is not working, either it gives me error when trying to convert the image or the intrefaces have changed.
A am using an andorid phone to debug, i have tried ImageFormatGroup.bgr8888 and yuv420 also with no luck.
Answer: you have to knw the default camera image on android is yuv420 this forma cant be directly used or converted in jpeg or png   ,so at the first time  you need to convert the image in rgba format
<code>imglib.Image _convertYUV420toImageColor(CameraImage image) {
  const shift = (0xFF << 24);

 final int width = image.width;
 final int height = image.height;
 final int uvRowStride = image.planes[1].bytesPerRow;
 final int uvPixelStride = image.planes[1].bytesPerPixel!;

 final img = imglib.Image(width: height, height: width); // Create Image
buffer

 // Fill image buffer with plane[0] from YUV420_888
 for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
  final int uvIndex =
      uvPixelStride * (x / 2).floor() + uvRowStride * (y / 2).floor();
  final int index = y * width + x;

  final yp = image.planes[0].bytes[index];
  final up = image.planes[1].bytes[uvIndex];
  final vp = image.planes[2].bytes[uvIndex];
  // Calculate pixel color
  int r = (yp + vp * 1436 / 1024 - 179).round().clamp(0, 255);
  int g = (yp - up * 46549 / 131072 + 44 - vp * 93604 / 131072 + 91)
      .round()
      .clamp(0, 255);
  int b = (yp + up * 1814 / 1024 - 227).round().clamp(0, 255);
  // color: 0x FF  FF  FF  FFj
  //           A   B   G   R

  if (img.isBoundsSafe(height - y, x)) {
    img.setPixelRgba(height - y, x, r, g, b, shift);
  }
}
}

return img;
  }
</code>
this fonction can convert your image in rgba format


QT draw a rectangle on top of another when a button is clicked

Question:
I am completely new to QT and trying to draw a rectangle when a button is clicked,
The following steps should happen when a button is clicked,
1. when the button is clicked. it should open a popup with a dropdown of colors and user can select one color and click OK then a rectangle with that color should be drawn on the screen.
2. The user can click the button again and another rectangle should be stacked on top of the previous rectangle.
I have written code to create a rectangle when a button is clicked but it is not drawing anything on screen and the following message is thrown.
#include "dialog.h"
#include "ui_dialog.h"

#include <QDialog>
#include <QComboBox>
#include <QHBoxLayout>
#include <QStringList>
#include <QDebug>
#include <QGraphicsItem>
#include <QGraphicsScene>

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);
}

Dialog::~Dialog()
{
    delete ui;
}

class CustomDialog : public QDialog
{
public:
    CustomDialog(const QStringList& items)
    {
        setLayout(new QHBoxLayout());

        box = new QComboBox;
        box->addItems(items);
        layout()->addWidget(box);

        QPushButton* ok = new QPushButton("ok");
        layout()->addWidget(ok);
        connect(ok, &QPushButton::clicked, this, [this]()
        {
           accept();
        });
    }

    QComboBox* combobox() { return box; }

private:
    QComboBox* box;
};

void Dialog::on_pushButton_clicked()
{
    QStringList itemList({"Red", "Blue", "Green"});
    CustomDialog dialog(itemList);
    if (dialog.exec() == QDialog::Accepted)
    {
        scene = new QGraphicsScene(this);
        ui->graphicsView->setScene(scene);
        QBrush redBrush(Qt::red);
        QBrush blackBrush(Qt::black);
        QPen blackpen(Qt::black);
        blackpen.setWidth(3);
        rectangle = scene->addRect(10,10,100,100,blackpen,redBrush);

        rectangle->setFlag(QGraphicsItem::ItemIsMovable);
    }
}

I can now get one rectangle but if i click the button again ,it should add another rectangle.
How to do that.
Comment: 1. Understood 2-4. If I understand you correctly [QGraphicsScene](http://doc.qt.io/qt-4.8/qgraphicsscene.html) might get handy in your case. However it would good if you could show your desired result (the stacked rects) on some image for clarification. The rectangles are movable only programatically (by adding the new rect). The user cannot directly move a rectangle, correct?
Comment: Isn't the topic slightly related to your other question? [link](http://stackoverflow.com/questions/40919414/have-a-combobox-inside-a-message-box)
Comment: yes it is.. Can you please help today ?
Comment: 1. Do you want a color picker widget or just some of your predefined colours to be available from the list? How does the user specify where the rectangle is drawn? Click and drag or there is just some static area which should be coloured? 2. What do you mean by stacked? Just drawn over the old one or you need to be able to do smth with the old one afterwards
Comment: 1.I have few predefined colors.
2. Yes I have a predefined area which will be on the mainwindow.
3.No click and drag when I click Ok in the popup button the rectangle of the selected color is drawn on the main window and the next rectangle will be stacked on the top of the old one.
4. The rectangle is clickable as if the user wants he can choose the rectangle and create a new rectangle in between the other two. ( it should be like wooden blocks stacked over each other and you can insert a new one in between the 2 wooden stacks)
Comment: yes absolutely. User cannot move the rectangles. User can just select the rectangle(can show the selected by different border may be?) and add a rectangle on top of it.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/129660/discussion-between-psdebugger-and-dusteh).
Comment: Any success with the proposed approach?
Comment: Not really. I tried my best but still not able to draw multiple rectangles on click of a button
Answer: If you want to have more rectangles than the one you already can draw and you want to make some interactions to them you need to do two things.
First you need to have a way to access all the rectangles in the scene. You can do this using QGraphicsScene::items method which will give you a list of QGraphicsItem objects (convertible to the QGraphicsRectItem).
I'm not sure if in your case the actual rectangle dimensions will be constant or they should adjust each time a rectangle is added. Either way since you can access their collection you can iterate through the items and adjust their sizes and positions how you like.
As to the rectangle selection to know where to add the new shape you should look into the QGraphicsScene signal called focusItemChanged or to a method focusItem. In your case I would go with the latter one.
QGraphicsItem *QGraphicsScene::focusItem() const

You should call this method in your on_pushButton_clicked() slot implementation. It gives you the currently selected shape in the scene. You can simply cast the QGraphicsItem* to QGraphicsRectItem* to read position and size of the object in the scene.
Hope this helps.


Integral of $\frac{1}{x^{n}+1}$ for odd $n$

Question: I am trying to find a general formula for
  $$ \int \frac{1}{x^{n}+1} \, dx $$
where $n$ is an odd integer.
I can't find any answers on this site for this question, and I have already tried the following.
We can write
  $$ x^{n} + 1 =  (x+1)\sum_{k=0}^{n-1} (-1)^{k}x^{k} $$
and so we get
  $$ \int \frac{1}{x^{n}+1} \, dx  = \int \frac{1}{x+1} + \frac{\sum_{k=0}^{n-2} a_{k}x^{k}}{\sum_{k=0}^{n-1} (-1)^{k}x^{k}} \, dx$$
for some numbers $a_{k}$.
When $n=3$, this is easy enough to solve using partial fractions. When $n=5$ it is tricky but doable. For $n \geq 7$ it becomes intractable and even Mathematica fails to evaluate.
Is there a way to continue with my approach? Is there a better way to find a general formula?
Answer: It's doable but the details are pretty ugly so sorry for not completing this calculation. But I will give a complete algorithm for it.
The idea is to write $\frac{1}{x^n+1} = \sum_{i=1}^{n}\frac{1}{f'(\psi_i)(x-\psi_i)}$, where $\psi_i$ are the n-th roots of unity. Now you can further write the sum by grouping $\frac{1}{f'(\psi_i)(x-\psi_i)} + \frac{1}{f'(\psi_{n-i})(x-\psi_{n-i})} = \frac{(2cos\frac{2\pi}{n})x-2}{x^2-(2cos\frac{2\pi}{n})x+1}$ so we have actually managed to split our poly into fractions of irreducible polys over R(of degree 1 and 2!), which we know how to integrate.
Comment: I think this is a great answer and I would love to accept them all. I think that comparing this to the other answers is mathematically interesting, because all solutions are equal which means with have some surprising equalities between seemingly unconnected expressions.
Answer: $\frac 1 {x^{n}+1}=1-x^{n}+(-x^{n})^{2}+\cdots$ and you can  integrate this term by term for $|x| <1$. Note that for $n$ odd the integrand has a singularity at $-1$.
Answer: We know that $$x^n+1=\prod _{k=1}^{n} x-e^{i{2k+1\over n}\pi}$$since all the roots are of order $1$, we can write $${1\over x^n+1}={1\over\prod _{k=1}^{n} (x-e^{i{2k+1\over n}\pi})}={1\over n}\sum_{k=1}^{n} {e^{-i\pi {n-1\over n}(2k+1)}\over x-e^{i{2k+1\over n}\pi}}$$by integrating we obtain$$\int{1\over x^n+1}dx={1\over n}\sum_{k=1}^{n} {e^{-i\pi {n-1\over n}(2k+1)} \ln | x-e^{i{2k+1\over n}\pi}|}+C$$
Comment: I'm a little fuzzy about using absolute values for logarithms when the argument is complex.  Would be more comfortable if you combined complex conjugate pairs of fractions making fractions with quadratic denominators, which allows an expression with real domain functions only.
Comment: You're right. I wrote it that way for sake of simplicity while both the ways of expressing that lead to the same result.
Comment: This is actually close to what I was thinking, but didn't manage to find a nice expression for the numerator. Thank you; I learned from this answer.
Comment: You're welcome. I also couldn't find any better expression :)
Answer: Let's find the Taylor series for $x^a$. Assume that $D_b^kf(x)=\frac{\mathrm{d}^k}{\mathrm{d}x^k}f(x)\big|_{x=b}$.
$$D^0x^a=x^a$$
$$D^1x^a=ax^{a-1}$$
$$D^2x^a=a(a-1)x^{a-2}$$
$$\cdots$$
$$D^kx^a=x^{a-k}\prod_{i=0}^{k-1}(a-i)$$
We'll center our Taylor series about the point $x=1$. Thus, we know that our Taylor-Series coefficients are given by
$$c_k=\frac1{k!}\prod_{i=0}^{k-1}(a-i)$$
And hence
$$x^a=\sum_{k\geq0}\frac{(x-1)^k}{k!}\prod_{i=0}^{k-1}(a-i)$$
This series has a radius of convergence of $1$, which is something to keep in mind.
We proceed by noting that
$$(1-x)^a=\sum_{k\geq0}(-1)^k\frac{x^k}{k!}\prod_{i=0}^{k-1}(a-i)$$
And plugging in $a=-1$ gives
$$\frac1{1-x}=\sum_{k\geq0}(-1)^k\frac{x^k}{k!}\prod_{i=0}^{k-1}(-1-i)$$
$$\frac1{1-x}=\sum_{k\geq0}(-1)^k(-1)^k\frac{x^k}{k!}\prod_{i=0}^{k-1}(i+1)$$
$$\frac1{1-x}=\sum_{k\geq0}x^k$$
$$\frac1{1+x}=\sum_{k\geq0}(-1)^kx^k$$
$$\frac1{1+x^n}=\sum_{k\geq0}(-1)^kx^{nk}$$
So if we assume that $|x|<1$, we have that
$$
\begin{align}
\int\frac{\mathrm{d}x}{1+x^n}=&\int\sum_{k\geq0}(-1)^kx^{nk}\mathrm{d}x\\
=&\sum_{k\geq0}(-1)^k\int x^{nk}\mathrm{d}x\\
=&\sum_{k\geq0}(-1)^k\frac{x^{nk+1}}{nk+1}\\
\end{align}
$$
And there you go.
Comment: This is great! I had thought on similar lines just using the formula for $S_{\infty}$ of a geometric sequence, but the detail here is really interesting, particularly about convergence. Out of interest: if I compare this answer with the answer of Mostafa Ayaz, can we say that
$$ {1\over n}\sum_{k=1}^{n} {e^{-i\pi {n-1\over n}(2k+1)} \ln | x-e^{i{2k+1\over n}\pi}|} = \sum_{k\geq0}(-1)^k\frac{x^{nk+1}}{nk+1} $$
and thus get the Taylor Polynomial of the left hand side for free?
Comment: @Shai I guess so. Of course the equality would only hold for $|x|<1$, and $n\in \Bbb N$. There are ups and downs to each series: Taylor series works for *any* $n$, but only converges for $0<x<2$, while the LHS probably has a better radius of convergence, but only works for $n=1,2,3,\dots$
Comment: @shai in order to learn more about the convergence of this Taylor series, check this question of mine out: https://math.stackexchange.com/q/3020447/583016


How to have auto-correct QLineEdit when typing?

Question: How do I have a QLineEdit auto-correct when a key is typed?
For this example, when you type the "<" I want it to auto-correct to "less than".
from PyQt5.QtWidgets import *
import sys

class Window(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        layout = QGridLayout()
        self.setLayout(layout)

        # auto complete options
        names = ["Apple", "Alps", "Berry", "Cherry" ]
        completer = QCompleter(names)

        # create line edit and add auto complete
        self.lineedit = QLineEdit()
        self.lineedit.setCompleter(completer)
        layout.addWidget(self.lineedit, 0, 0)

app = QApplication(sys.argv)
screen = Window()
screen.show()
sys.exit(app.exec_())

Comment: From what I understand you, you want that if you type a key such as "<" then it must be replaced with another one, in this case "less than". I am right?
Comment: yes, I know there would be a keysequence in there too now that you mention it. Basically I need my GUI lineedit to replace  "<" to "less than" and " ' " for " ` "
Answer: You can check if a character was added and if so, replace the QLineEdit text. A possible implementation can be override the keyPressEvent method:
import sys

from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QCompleter, QGridLayout, QLineEdit, QWidget

class LineEdit(QLineEdit):
    def __init__(self, mapping, parent=None):
        super(LineEdit, self).__init__(parent)

        self.mapping = mapping

    def keyPressEvent(self, event):
        last_text = self.text()
        super(LineEdit, self).keyPressEvent(event)
        new_text = self.text()
        if last_text + event.text() == new_text:
            new_text = self.mapping.get(event.text())
            if new_text is not None:
                self.setText(last_text + new_text)

class Window(QWidget):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)
        layout = QGridLayout(self)

        names = ["Apple", "Alps", "Berry", "Cherry"]
        completer = QCompleter(names)

        mapping = {"<": "less than", ">": "greater than", "'": "`"}
        self.lineedit = LineEdit(mapping)
        self.lineedit.setCompleter(completer)
        layout.addWidget(self.lineedit, 0, 0)

if __name__ == "__main__":

    app = QApplication(sys.argv)
    screen = Window()
    screen.show()
    sys.exit(app.exec_())

Comment: perfect answer, exactly what i needed
Comment: @spaceguy101 If my answer helped you then do not forget to mark as correct, if you do not know how to do it then check the [tour]
Comment: I asked the same question but using QPlainTextEdit if you want to help with that one? https://stackoverflow.com/questions/59380082/how-do-i-have-a-qplaintextedit-auto-correct-when-a-key-is-typed-for-this-exampl


Finding where memory was last freed?

Question: Very general:
Is there an easy way to tell which line of code last freed a block of memory when an access violation occurs?
Less general:
My understanding of profilers is that they override the allocation and deallocation processes.  If this is true, might they happen to store the line of code that last freed a section of memory so that when it later crashes because of an access violation, you know what freed it last?
Specifics:
Windows, ANSI C, using Visual Studio
Answer: Yes!
Install the Windows Debugging Tools and use Application Verifier.

File -> Add Application, select your .exe
Under Basics, select Memory and Heaps.
Run the debug build of your program under ntsd (ntsd yourprogram.exe).
Reproduce the bug.

Now when you make the crash happen, you will get additional information in the debugger from AppVerifier.  Use !avrf (may take a long time to run (minutes)) and it will try to give you as much useful information as possible.
You can all use the dps command on the memory address to get all the stored stack info (allocation, deallocation, etc).
You can also use the !heap command on the memory address:
0:004> !heap -p -a 0x0C46CFE0

Which will dump information as well.
Further Reading:

Advanced Windows Debugging, Hewardt and Pravat
Debugging with PageHeap
Answer: Short answer: no.
What you need is a debug malloc.  I don't keep up with Windows any longer but there are several about, including this free one.
Update
Looks like Visual Studio C has a built in version.  See here

When the application is linked with a
debug version of the C run-time
libraries, malloc resolves to
_malloc_dbg. For more information about how the heap is managed during
the debugging process, see The CRT
Debug Heap.

... and see here for _malloc_dbg.
Answer: No, not unless you provide your own allocators (e.g. by overloading new/delete) to store this information.
What profilers do is highly dependent on what they're profiling. I'm not aware of any profiler that tracks what you're looking for.
Perhaps if you provided more details on your situation people could suggest an alternative means of diagnosing the problem you're encountering.
Comment: e.g.= example. In this case use a custom/malloc free in your app, which if memory performance is important you will already have.

Finding where memory was last freed?


I'm having issues tuning my classical guitar

Question: For some reason I cannot tune my classical guitar, I've used phone apps and actual tuners.
I'm starting to believe that the issue is that the guitar is too cheapy. I bought for 100$ from  the brand fender. I'm especially having problems with my low E string, it sounds terrible. I replaced the string and it still sounds the same, it has this very high pitched sound. I've tried to make it lower pitch and it sounds even worse.
I'm not sure what to do at this point. All the strings sound so plastic like instead of a more savory sound a classical guitar is supposed to have.
I'm not sure what the brand of the strings are originally when I bought it but I bought and used DAddrío pro larté nylon core normal intention classical guitar strings if that helps anyone.
Comment: That doesn't sound like a tuning issue.  Could you share an audio recording?
Comment: Yeah the tone is different from the tuning. A photo of the guitar and the strings might help also. And how are you trying to tune? With an electronic tuner?
Comment: You really have to separate the tone from the tuning. The tuning comes from the tension of the strings. The tone comes from your right hand technique.
Comment: @Mya You can upload a clip to Youtube, Soundcloud, or another website, and then post a link to it here.
Comment: Welcome! To make the question answerable, please use the "Edit" button to add some more information. Right now this question seems to be about tone—the way a string might "sound different" even if it's in tune, might have a richer or thinner sound. If you're having trouble even making it be an E, then please tell more about the trouble you're having—is the string changing pitch on its own? Are you having trouble telling whether it needs to move up or down?
Comment: A video or audio clip of how it actually sounds would be really helpful. Some time ago I bought an acoustic guitar and tried some Fenders at the time. They did not sound or feel great but the ones on display weren't so bad that they couldn't be played in tune so I suspect it's something else.
Comment: "I've tried it with electronic tuner and phone apps" — and what do those tell you? Is the pitch always too high, no matter how much you loosen the string; or too low, no matter how much you tighten it? Does it alternative between being too high and too low, and you can't find (or stay on) the right tension? Does tuning one string cause others to go out of tune? Does the tuner not show a pitch for the string(s) in question? Or does it show the correct pitch but you don't like the sound?
Comment: I've tried turning by ear, I've tried it with electronic tuner and phone apps
Comment: Has it always been like this? If possible, return it to the shop, and let them solve the problem.
Comment: @ToddWilcox of course there are mechanical factors independent of the player's technique that also affect the tone.   Most of these have nothing to do with tuning either, of course.
Comment: As you say, it could be the quality of the instrument if it's cheaper.  I have a cheap one that is impossible to play in tune.  I gave up and bought a nicer one.  You could take yours to a reputable repairer and see if they can do anything.
Comment: I would take it to a shop and ask someone there for an opinion.  You might need to make an appointment.  I don't know what this type of appointment is called.  For string instruments, one makes an appointment for an adjustment.
Comment: Alright, I'm not sure though how to add a video or audio clip. I you could tell me how do that I would be happy to add that. Thank you.
Answer: It could be a problem of distances between the Nut and the Bridge, or maybe the tuning peg does not allow you to be as exact with the turns. However, if this problem is increased by playing a note somewhere on the fret, you could add a neck bend problem. Cheap guitars are usually a mess with tuning.
Comment: How does poor intonation give high pitched sound on low E string?


Rule to remove two specific items from commerce cart

Question: I am using Drupal commerce and I try to make a rule to remove two specific line items from the cart. However, the most I can achieve is to empty the whole cart.
Can this be done with rules?
Comment: Which specific line items do you wnat to remove? and if possible why?
Comment: The SKU's for the two line items I want to remove are "item1" and "item2"when a user adds a certain line_item to the cart I want to just loop through all items in the cart and remove the two with matching SKUs. "item1" and "item2" are separate products but if a user adds the "doublepack" product which is a bundle of them both, then I want to remove any of the two previous products that might have been added separately to the cart.
Answer:
You remove a product from the cart by deleting the line-item entity for that product.
But first you must expose the line-item data to your Rule so you can check whether it should be deleted. Line-item data including sku is not available to Rules Actions unless you do this.
Note that you can access some properties about the line-item, such as commerce-line-item:type, in your Rule Condition, but this is for the line-item referenced in the event, not for the other line-items in the cart. You cannot access other line-items' data, such as sku, in your Rule Action.
You force the other line items' sku and other data to become available to your Rule Actions by checking a property of each line item in the Action, even if you don't otherwise need to do the check. In this example I check the type of each line-item to be evaluated for deletion.
Much of the documentation available as of today is a couple of years old and calls for use of Rules components ... nowadays Rules Conditional is the way to go as it allows you to bring conditional logic right into your Action (so you can choose which line items to delete, for example). You may choose to put this Rule in a component if you have many varied situations in which you want to call it. If you only have one or two situations, using conditional logic within the Rule Action, via Rules Conditional, is much simpler.

In the example below, the Rule is evaluated on the event "After removing a product from the cart" because I have an add-on product that should be removed after the "mother" product is removed by the customer. But you can use any Commerce event.
The Condition here is to check whether the product removed from the cart by the customer was a "mother" product ... you may not need any conditions for your Rule.
The Action first does the aforementioned check of the line-item type to bring the line-item properties into scope for the Action data selector, then loops through the list of line-items, and tests each one for the skus you want to delete. Then deletes the line-item if there is a match. You could of course delete based on price, quantity, or anything else in the line-item data.
Note that once you start to loop through a list, the data you are after will be accessed through the variable list-item: which represents whatever you are looping through; in this case, the line-items. Note that list-item and line-item are syntactically very close, watch for typos!
{ "rules_delete_products_from_cart_by_sku" : {
    "LABEL" : "Delete Products from Cart by SKU",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "Commerce Cart" ],
    "REQUIRES" : [ "rules", "rules_conditional", "commerce_cart" ],
    "ON" : { "commerce_cart_product_remove" : [] },
    "IF" : [
      { "data_is" : {
          "data" : [ "commerce-line-item:type" ],
          "value" : "my_product_type"
          }
       }
     ],
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "commerce-order:commerce-line-items" ] },
          "ITEM" : { "list_item" : "Current list item" },
          "DO" : [
            { "CONDITIONAL" : [
                {
                  "IF" : { "data_is" : { "data" : [ "list-item:type" ], "value" : "product" } },
                  "DO" : [
                    { "CONDITIONAL" : [
                        {
                          "IF" : { "data_is" : {
                              "data" : [ "list-item:commerce-product:sku" ],
                              "op" : "IN",
                              "value" : { "value" : [ "SKU-01", "SKU-03" ] }
                            }
                          },
                          "DO" : [ { "entity_delete" : { "data" : [ "list-item" ] } } ]
                        }
                      ]
                    }
                  ]
                }
              ]
            }
          ]
        }
      }
    ]
  }
}

Hope this helps someone on the same journey I am!
Comment: Hi and welcome to Drupal Answers. Thorough answer!
Comment: It works perfect!
Comment: Interesting answer. Though instead of using "Conditional Rules" (which still does not have an oficial D7 relese, and some bugs), I prefer using Rules Components, stil. For more details, refer to [this question](https://drupal.stackexchange.com/q/245049/39516).


SQL Server - Replace datatime field with another date

Question: I am trying to replace a particular datetime value with another one. I tried it with:
SELECT REPLACE(t.date,'1999-01-01 00:00:00.000','1900-01-01 00:00:00.000')
FROM table t

But that results into
Jan  1 1999 12:00AM

What am I doing wrong here?
Comment: Is this specific to one date, as shown, or is the logic more complicated? Do you just want 1999 to be 1900, or do you want every date to be rolled back by 99 years?
Comment: @3BK It's just specific to that date.
Answer: You can't use replace() on a datetime datatype, but you can use a combination of isnull() and nullif(), or a case expression.
using isnull(nullif()):
select isnull(nullif(t.date,'1999-01-01 00:00:00.000'),'1900-01-01 00:00:00.000')
from table t

using a case expression:
select case when t.date = '1999-01-01 00:00:00.000'
            then '1900-01-01 00:00:00.000'
            else t.date
            end
from table t

rextester demo: http://rextester.com/QMI12865


Zariski closure of the boundary of the first quadrant

Question: What is the Zariski closure of the boundary of the first quadrant in $\mathbb{R}^2$?
I know that the boundary is $S=\{(a,0)\in\mathbb{R}^2:a\geq0\}\cup\{(0,b)\in\mathbb{R}^2:b\geq0\}$. As per the definition of the Zariski closure, I suppose I need to find $\textbf{I}(S)$ and then find its variety. Is this the way to proceed? If so, what to do exactly to get the ideal and then the variety?
Answer: Take the ideal $I=\langle xy\rangle$ where $xy=0$ iff $x=0$ or $y=0$.
Comment: so in terms of variety (set), is the Zariski closure the union of the entire x-axis and y-axis?
Comment: @BernhardListing The zariski closure of a union is the union of the zariski closure of each set. See Lemma 3 of Ideals, Varieties, and Algorithms of Cox, Little, & O'Shea.


Json Parsing in Android in list view

Question: Anyone know of any examples to dynamically load Json data into a ListView, most examples I have seen just use a static array of some kind. I need to load say 10 rows of Json data, then at the bottom have a load more.. to get the next 10 etc etc. Examples using Json please....
Comment: try with link : http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html
Comment: I am beginner on android. Please dont vote down it. If you cant help thats fine
Comment: To make things really easy, you can use the gson library with a custom adapter to populate a listview, if you are ok with using external libs
Comment: What budget do you have? I'll do it for you... Otherwise show us your attempts, your trials
Comment: Thanks Varsha, Please vote my question I already lost my points :(
Answer: Check this link, it's very well explained: https://guides.codepath.com/android/Using-an-ArrayAdapter-with-ListView
Comment: Just FYI, answers with link only are frowned upon, as the link can go dead.

Json Parsing in Android in list view


Simplifying an function with complex numbers

Question: Given that variables $h_i, h_d $ are $\in \mathbb{C}$ i.e complex numbers.
Can the following be further simplified
$$h_dh_d,+h_ih_i+h_dh_d^*+h_ih_i^*\leq 2h_ih_d+h_ih_d^*+h_dh_i^*\tag 1$$
I know that (1) can be simplified into
$$h_dh_d,+h_ih_i+|h_d|^2+|h_i|^2\leq 2h_ih_d+h_ih_d^*+h_dh_i^*\tag 2$$
Any further tricks and properties of complex numbers to further simplify (2)?
Thanks
Comment: Wait, so you know in advance that both sides are real numbers?
Comment: yes thats corrct
Answer: The original inequality is
$$
h_dh_d,+h_ih_i+h_dh^∗_d+h_ih^∗_i \leq 2h_ih_d+h_ih^∗_d+h_dh^∗_i
$$
In order for this inequality to make sense, both sides have to be real. Looking at the right hand side, we can recognise the last two terms as $2\Re (h_ih^*_d)$. This means that the first term on the right hand side is also real, as the difference between two real numbers is also real. We can therefore move $2h_ih_d$ to the left hand side.
On the left hand side, the last two terms are the magnitudes of complex numbers, exactly as you noticed, and these must also be real. We can therefore move them to the right hand side. Doing this yields
$$
h_dh_d,+h_ih_i - 2h_ih_d \leq h_ih^∗_d+h_dh^∗_i - h_dh^∗_d - h_ih^∗_i
$$
The left hand side can now be factored as $(h_d - h_i)^2$, while the right hand side also simplifies:
\begin{align*}
h_ih^∗_d+h_dh^∗_i - h_dh^∗_d - h_ih^∗_i &= -\left( h_dh^∗_d + h_ih^∗_i - h_ih^∗_d - h_dh^∗_i\right)\\
&= -\left( h_d - h_i\right)\left(h^∗_d - h^∗_i\right)\\
&= -\left\lvert h_d - h_i\right\rvert^2\\
&= - \left\lvert\left( h_d - h_i\right)^2\right\rvert\\
\end{align*}
The inequality then becomes
$$
 \left(h_d - h_i \right)^2 \leq - \left\lvert\left( h_d - h_i\right)^2\right\rvert
$$
If we let $\left(h_d - h_i \right)^2 = k$, for some $k \in \mathbb{R}$, we see that we have an inequality of the form $k \leq - |k|$, which can only be satisfied for $k \leq 0$. In terms of $h_i$ and $h_d$, this means that
$$
\left(h_d - h_i \right)^2 \leq 0,
$$
so the difference between $h_i$ and $h_d$ must be purely imaginary.


Properties of Bernoulli Polynomials

Question: I have pored over the internet and can't seem to find any proof of a particular property of Bernoulli Polynomials. The property is:
$P'_{n}(x) = nP_{n-1}(x)$
I have not found anything conclusive in any of my textbooks that lay out a clear proof or anything on the internet. Any help or resources as to what the proof might be would be greatly appreciated!
Comment: This is well-known and comes from the explicit formula: https://en.wikipedia.org/wiki/Bernoulli_polynomials#Explicit_formula . Also there one finds an integral formula https://en.wikipedia.org/wiki/Bernoulli_polynomials#Integrals which is pretty much the same as the derivative formula.
Comment: Of course, any proof would require a definition of Bernoulli polynomials. Which one do you want to use?
Comment: See [Appell Sequence](https://en.wikipedia.org/wiki/Appell_sequence)
Answer: From the definition of bernoulli polynomials, we have
$$B_n(x)=\sum_{k=0}^n\binom{n}{k}B_{n-k}x^k$$
where $B_k$ are the traditional Bernoulli numbers.  Differentiate both sides to get
\begin{eqnarray*}B'_n(x)&=&\frac{d}{dx}\sum_{k=0}^n\binom{n}{k}B_{n-k}x^k\\&=&\sum_{k=1}^n\binom{n}{k}kB_{n-k}x^{k-1}\\&=&\sum_{k=0}^{n-1}\binom{n}{k+1}(k+1)B_{n-k+1}x^k\\&=&n\sum_{k=0}^{n-1}\binom{n-1}{k}B_{n-1-k}x^k\\&=&nB_{n-1}(x)\end{eqnarray*}
Where we used the combinatorial identity
$$(k+1)\binom{n}{k+1}=n\binom{n-1}{k}$$

Properties of Bernoulli Polynomials


Smallest number of groups to sniff

Question: The question given: The sniffer dog at the airport stops beside a trolley piled high with 60 suitcases. One of the suitcases contains contraband peanuts. The dog can tell whether peanuts are hidden in any one of a group of suitcases, but it gets tired if it has to do too much sniffing.
What is the smallest number of groups of suitcases it must sniff in order to isolate the suitcase with the peanuts?
My reasoning: Divide the 60 into 2 groups of 30 suitcases. Make the the dog sniff both of the groups. Divide the group of 30 that the dog identifies into 2 groups of 15. Make the dog sniff both of the groups. Divide the group that the dog identifies into 8 and 7. 8 will lead to the maximum sniffs so lets say the dog identifies the group with 8. Divide that group into 2 groups of 4 (dog again sniffs 2 groups). Then the resulting group into 2 groups of 2 until finally we are left with 2 groups of 1.Then, the dog sniffs both of them and identifies the once with peanuts.
I counted and got 12 groups to sniff. Why is the answer 6?
Comment: Given two groups. one of which contains the peanuts, the dog only has to sniff one group. This is nuts.
Answer: At each split the dog doesn't need to sniff both groups. If its not in the one the dog sniffed it must be in the other group. So you've done twice as much as needed.
So your reasoning/thinking is correct just your "code" is inefficient. :)

Smallest number of groups to sniff


Use other image as thumbnail for Sparkling Theme Polular Post Widget in wordpress

Question: I have installed Sparking Theme. I tried to use Sparkling Polular Post Widget to display my popular posts in the side bar. By default it shows a thumbnail which always shows the featured image. I want to show any other image as thumbnail, say the first image found in the post as thumbnail. Beacuse if any post doesn't have the featured image, it shows just blank, I want to show first image of the post as thumbnail.
Is it possible to somehow achieve it? I am new to wordpress and may be I a missing something. Please help.

Thanks
Manish
Comment: Upload your chosen image as feature image from your post detail page from wordpress admin so it will automatically come as thumbnail for popular post.
Answer: you can try using this plugin https://wordpress.org/plugins/autoset-featured-image/ or this https://wordpress.org/plugins/easy-add-thumbnail/ .the second one works out of the box .when you publish a post it checks for a featured image. If it does not find one, then it looks for the first image attached to the post and sets it as featured image


Unavailable projects in vs 2010?

Question: Where does the indication of unavailable or available (loaded) projects / websites  is saved?
I have a solution which has some unloaded projects while only the website is loaded
Of course I can right click and reload it but still, I want to now where this [unavailable or available] info is saved?

I've been looking in the sln, there is no difference (beyond compare) between loaded one and unloaded one.
Also in Websites.xml, there is no such difference
Comment: I believe it's in the .suo file
Comment: @SteveB this is what i also thought .....bnut it is a binary file. can i delete it ? will vs will recreate it ?
Comment: The suo file stands for "solution user object" (it's a guess). It's a per-user container of solution settings. You can safely delete it, but you will loose some other non important things, like breakpoints, and so on. In most VCS, this file is in the standard exclusion list, as it should remain specific for each user.
Comment: It will certainly recreate it, but I'm not sure how much information is there. Certainly the code won't stop compiling.
Answer: The suo file stands for "solution user object" (it's a guess).
It's a per-user container of solution settings.
You can safely delete it, but you will lose some other non important things, like breakpoints, and so on.
In most VCS, this file is in the standard exclusion list, as it should remain specific for each user. This is the evidence you can safely delete it.
Comment: You rock man ! I deleted the file , it did recreate it ( after 5 min of "get latest from source control" and then it reseted all the avilable/unavailable thing. now i can disable/enable projects. thanks :-)
Comment: I was suspicious about that strange file.  I even got to a point where i thought it keeps it in registery(after negate the *.sln and websitecache.xml)
Comment: I had the same exact problem and deleting the *.sou file fixed it.
Answer: I believe the information regarding loaded and unavailable projects in a solution is stored in the .suo file. As mentioned previously, this is a user-specific, binary settings file auto-generated and maintained by Visual Studio.
It's worth pointing out that some projects won't load if the machine doesn't have the relevant software installed (e.g. an MVC web application project won't load on a machine that does not have it installed; similarly for WIX projects).
If you have intentionally unloaded projects to improve the overall load time of your solution, then you should know that Visual Studio 2012 now supports asynchronous loading of projects.
You might also have a look at spinning some projects out into other solutions, grouping by major system features (be wary of breaking project dependencies.)

Unavailable projects in vs 2010?


Making predictions with limited, skewed binary response data

Question: Suppose I have 5 predictor variables, a binary response variable, and 100 data points. I want to try to predict what the chance of the binary response being -1 or 1 is, but 99 of the response values are -1.
What is the best way to go about making predictions on this data set (with heavily 'skewed' responses) without collecting additional data?
To clarify, it is clear that a model fitted to this data will probably do a bad job classifying new data. Can we, for example, make up data in order to improve the results? What are some other ways to try to get a better idea of what the data might look like at 1000 samples?
Answer: I guess that by "make predictions" you mean find a predictively accurate model, since you already know the true response values for this data.
Logistic regression is the usual tool for probabilistic classification. It's hard to guess in advance whether it will be able to beat the trivial model that guesses a probability of .99 for every case, but you can try it. Fancier models are unlikely to do better in this situation.
Comment: I've added a follow up to my question, I think there might have been some confusion. Thanks!
Comment: @114 Regarding your first question, I'm not sure what you would expect to get out of simulated data here. Regarding your second, under the usual assumption of IID sampling, a sample of 1,000 would be most likely to look like the sample of 100 you already have.


Excel search and copy from more sheet

Question: I have a file.xls with three sheets.
Sheet1, 2 columns, 3000 rows;

ColumnA: location_id
ColumnB: location_label

Sheet2, 2 columns, 5000 rows;

ColumnA: location_id
ColumnB: screen_id

Sheet3, 2 columns, 6000 rows;

ColumnA: screen_id
ColumnB: screen_name

how to group data into a new sheet4 with the following syntax (view image);

ColumnA: Location_label
ColumnB: screen_name

location_id get location_label name in sheet 1, location_id get screen_id value in sheet2, screen_id get screen_name value in sheet3 and in sheet4 result with location_label and screen_name.
#EDIT QUESTION WITH USE VLOOKUP;
I tried to use VLOOKUP but from error after the first id number 19 of sheet2...i have used this '
=VLOOKUP(Sheet2!A2;Sheet1!A2:B2133;2;)
i get

RED
GREEN
YELLOW
#N/D
#N/D
Answer: Well I'm not the best with Excel and I do not fully understand what you want as an end result. But here is my guess what I think is the problem.
I suspect that in sheet 4 you type you code in A2 and use your mouse to drag the formula to the bottom of the column. If this is the case, your formula will not be exactly the same in every cell, because your matrix in the formula will change while you drag your mouse. Therefore the error #N/D
To prevent your matrix from changing while dragging your mouse you should use '$'.
So your formula would be:

=VLOOKUP(Sheet2!A2;Sheet1!$A$2:$B$2133;2;)

Possibly a tip:
I see you have the same columns in more than 1 sheet. You can put all you data in 1 sheet and then use filters to select the data you want. See this article.
Answer: Public Sub pair_value()

'here i tried to deconstruct the code so it is easy to follow
'this type of paring would work much better with access
'you can use this code to start
Dim h1 As Integer 'row count in sheet1
Dim h2 As Integer 'row count in sheet2
Dim h3 As Integer 'row count in sheet3
Dim h4 As Integer 'row count in sheet4
Dim ar1() As Variant
Dim ar2() As Variant
Dim ar3() As Variant
Dim ar4() As Variant
Dim pair1() As Variant

Dim range1 As Range
Dim range2 As Range
Dim range3 As Range

Dim i As Integer
Dim j As Integer

'---------------------------------------------------
'This exercise would be so much easier using ACCESS
'---------------------------------------------------

'number of rows in each sheets
h1 = Worksheets(1).Cells(Rows.Count, 1).End(xlUp).Row
h2 = Worksheets(2).Cells(Rows.Count, 1).End(xlUp).Row
h3 = Worksheets(3).Cells(Rows.Count, 1).End(xlUp).Row
h4 = Worksheets(4).Cells(Rows.Count, 1).End(xlUp).Row

'define arrays
ReDim ar1(h1, 2)
ReDim ar2(h2, 2)
ReDim ar3(h3, 2)

ReDim pair1(h2, 2)

'set range
Set range1 = Worksheets(1).Range(Worksheets(1).Cells(2, 1), Worksheets(1).Cells(h1, 2))
Set range2 = Worksheets(2).Range(Worksheets(2).Cells(2, 1), Worksheets(2).Cells(h2, 2))
Set range3 = Worksheets(3).Range(Worksheets(3).Cells(1, 1), Worksheets(3).Cells(h3, 2))

'load range into arrays
ar1 = range1
ar2 = range2
ar3 = range3

'associate location_label to screen_id using location_id as primary key
For i = 1 To UBound(ar2)

    For j = 1 To UBound(ar1)
        If ar2(i, 1) = ar1(j, 1) Then
            'load screen id + label in pair1 in pair1 array
            pair1(i, 1) = ar2(i, 2)
            pair1(i, 2) = ar1(j, 2)

        End If
    Next j
Next i

'associate location_label to screen_name using screen_id as primary key
For i = 1 To UBound(ar3)

    For j = 1 To UBound(pair1)
        If ar3(i, 1) = pair1(j, 1) Then
            Debug.Print j
            'past results in sheets(4)
             h4 = Worksheets(4).Cells(Rows.Count, 1).End(xlUp).Row
             Worksheets(4).Cells(h4 + 1, 1).Value = pair1(j, 2)
             Worksheets(4).Cells(h4 + 1, 2).Value = ar3(i, 2)
        End If
    Next j
Next i

End Sub

Excel search and copy from more sheet


Creating Variables foreach Info a cmdlet delivers

Question: So a bit of a Rookie Question here i guess, but Google can't help me anymore, since I'm lacking the terms to describe what I want to do.
What I want to do is simply ask for the State of .NET Framework Optional WindowsFeatures and - if one of them is not installed, do so.
My approach was to
Get-WindowsOptionalFeature -Online | Where-Object {$_.FeatureName -clike "Net*"}

Output is Expected to be:
FeatureName : NetFx3
State       : DisabledWithPayloadRemoved

FeatureName : NetFx4-AdvSrvs
State       : Disabled

FeatureName : NetFx4Extended-ASPNET45
State       : Disabled

Now I want to Parse this to a Foreach Method so every Feature, where State=Disabled* gets installed.
I tried to create a Variable foreach of those where the Name of the Variable is also what was given as an Value, such as:
$NetFx3 = Netfx3

And this - as I said - for each of the Features that are currently Disabled but not for any other.
This way I could just use them, but there should be an easier way, which I cannot see...
Comment: You can change your condition to `Where-Object {$_.FeatureName -like "Net*" -and $_.State -ne 'Enabled'}` to only get feature that are not enabled. If you pipe this to `Enable-WindowsOptionalFeature` you're done.
Answer: If you pipe the output of your current command into ForEach-Object, PowerShell will automatically create a variable for you.
Try it and you will find you'll have an object called $psItem which contains all of the properties for an item of the list, and it automatically moves on to the next item in the list too.
Get-WindowsOptionalFeature -Online | Where-Object {$_.FeatureName -clike "Net*"}|
  ForEach-Object{
    Write-host "The status of the feature called $($PSItem.FeatureName) is $($PSItem.State)"
   }

Sidebar, fun with variables
Since I get the impression you might be interested in knowing a few fun tricks, I encourage you to play with the output and see what the properties are, which is sooo easy!
Just slap -OutVariable myVar to the end like this.  Here's some fun commands to get you started.
Get-WindowsOptionalFeature -Online | Where-Object {$_.FeatureName -clike "Net*"} -OutVariable myVar

#pick the first item in the list and see some properties
>$myVar[0]

FeatureName : NetFx3
State       : Enabled

#see ALL of its properties

>$myVar[0] | Format-List * -Force
FeatureName      : NetFx3
State            : Enabled
Path             :
Online           : True
WinPath          :
SysDrivePath     :
RestartNeeded    : False
LogPath          : C:\WINDOWS\Logs\DISM\dism.log
ScratchDirectory :
LogLevel         : WarningsInfo

#access one or two of them
>$myvar[0] | select FeatureName, Online,LogPath

FeatureName Online LogPath
----------- ------ -------
NetFx3        True C:\WINDOWS\Logs\DISM\dism.log

#get those same properties for every item in the list
> $myvar | select FeatureName, Online,LogPath

FeatureName             Online LogPath
-----------             ------ -------
NetFx3                    True C:\WINDOWS\Logs\DISM\dism.log
NetFx4-AdvSrvs            True C:\WINDOWS\Logs\DISM\dism.log
NetFx4Extended-ASPNET45   True C:\WINDOWS\Logs\DISM\dism.log

#Save a spreadsheet with this info
> $myvar | select FeatureName, Online,LogPath | Export-Csv C:\pathTo\This.csfv -NoTypeInfo

Back to your question
However, if you wanted to automatically install any roles that were missing you could do this.
$missingDotNet =  Get-WindowsOptionalFeature -Online | Where-Object {$_.FeatureName -clike "Net*" -and $_.State -ne 'Enabled'}
if ($missingDotNet.Count -eq 0){
   Write-Host "All Dotnet features installed (or not running as Admin)"
}
else{
   Enable-WindowsOptionalFeature $missingDotNet
}

Comment: Hey there, thanks for the great help!
Also thank you for your additional information on "Fun with Variables" :D
Answer: At the end, I went into an Error, because what the Variable was giving out seemed to be "$_.FeatureName = NetFx3"
But with the code following I was able to get it running.
    #####Check on all .Net Features
    $missingDotNet =  Get-WindowsOptionalFeature -Online | Where-Object {$_.FeatureName -clike "Net*" -and $_.State -ne 'Enabled'} | Select -ExpandProperty FeatureName

#####If no .Net Feature is missing Script just prints "All .NET Features are installed or not running as Admin (no guarantee)"
    if ($missingDotNet.Count -eq 0){
       Write-Host "All .NET Features installed or not running as Admin"
    }
#####If there are .Net Features that are missing this line will install them
    else
    {
        Enable-WindowsOptionalFeature -Online -FeatureName ($missingDotNet)
    }

So now - since the Script is meant to install SAP GUI install completley - I can crawl back into my cave and get the rest done.