How to use multidimensional constant array in for iterator block in matlab/simulink?

Question: I have an array (300x6) and I want to use it for this block in simulink. But I have a problem. How can I use "for iterator" block to take the q(i,:), q(i+1,:) , q(i+2,:) ... elements respectively? Or is there any other way to do this idea? Thanks.
Comment: What are you trying to do with the rows?  Are you trying to use a different row at successive simulation time steps?  If so, that's not what the "for iterator" in Simulink is used for.  Using the "for iterator" in your model would make q, qd and qdd take the values from the last row only (after doing the calculation for all the other rows and then throwing the results away).
Comment: @Phil Goddard  Yes I am trying to use a different row at successive simulation time steps. By using for iterator block I cant do this , so how can I do dou you know?
Comment: You want to use a From Workspace or an Inport block to import the data. See http://www.mathworks.com/help/simulink/ug/importing-signal-data-in-simulink.html for a description of different approaches.
Answer: In Matlab, for iterates over matrix columns. So you can just transpose to iterate over rows:
A = [1 2 3; 4 5 6; 7 8 9]; %// example matrix
for v = A.'
    v = v.'; %// v will be [1 2 3], then [4 5 6] etc
    %// Do stuff with v
end

I'm not into Simulink but I guess you can adapt this to that environment.
Comment: How can I do in block diagram ? @Luis Mendo
Comment: @DMD In Simulink you can edit a block's contents and put Matlab code there, right? I don't use Simulink, I can't tell you much more about that, sorry


Making a subdirectory with the mkdir posix command

Question: The latest assignment in my Operating Systems class required us to create a subdirectory(named tmpFolder) using the mkdir command, with no context whatsoever.  The code I currently have is based off of the Minix3 appendix and the manual for mkdir  My professor isn't the most helpful and the rest of the class is also having trouble with it so I figured I'd ask about it here.
Here is my relevant code:
<code>#include <sys/stat.h>

{
    int tmpFolder;
    tmpFolder = mkdir(tmpFolder, 0777);
}
</code>
Can someone please explain to me why that is wrong because it is very frustrating having the professor not explaining why I'm wrong
Comment: There is no relationship between your variable name `tmpFolder` and the string `"tmpFolder"`; the latter is what `mkdir` expects as its first argument.
Comment: See the [man pages](http://linux.die.net/man/2/mkdir).
Answer: mkdir's first argument is the path you want to create. You're providing tmpFolder which is an int. Something like this would make more sense:
<code>int status;
status = mkdir("/tmp/subdir", 0777)
</code>


For what values $\alpha$ for complex z $\ln(z^{\alpha}) = \alpha \ln(z)$?

Question: For example, when $\alpha = 2$, $\ln(z^{2}) \neq 2\ln(z)$, because argument z is determined up to constant $2 \pi k$. So
$$
\ln(z^{2}) = \ln(z) + \ln(z) = \ln(z_{k_{1}}) + \ln(z_{k_{2}}) \neq 2\ln(z_{k_{3}}).
$$
Of course, two of correct answers - $1, -1$. But I know, that there are an infinite number of answers for $\alpha$. Can you help me?
Comment: What is your definition of $z^\alpha$, given complex numbers $z$ and $\alpha\ $?
Answer: Using this and this,
$Log (a+ib)^{x+iy}$
$=\frac{1}{2}x\log (a^2+b^2)-y(2m\pi+\tan ^{-1}\frac{b}{a})+i(\frac{1}{2}y\log (a^2+b^2)+x(2m\pi+\tan ^{-1}\frac{b}{a}))$
$Log (a+ib)= \frac{1}{2}\log (a^2+b^2)+i(2n\pi+\tan ^{-1}\frac{b}{a})$
$(x+iy)Log (a+ib)$
$=\frac{1}{2}x\log (a^2+b^2)-y(2n\pi+\tan ^{-1}\frac{b}{a})+i(x(2n\pi+\tan ^{-1}\frac{b}{a})+\frac{1}{2}y\log (a^2+b^2))$
The principal values will be same if $-\pi<\frac{1}{2}y\log (a^2+b^2)+x\tan ^{-1}\frac{b}{a}\le \pi$ else $2r\pi$ (where $r$ is any integer) must be added to this argument to adjust its value in $(-\pi, \pi]$.
If $x=0$ or $(b=0$ and $a>0 ⇔ \tan ^{-1}\frac{b}{a}=0)$ , the condition becomes $-\pi<\frac{1}{2}y\log (a^2+b^2)\le \pi$
If $y=0$ or $a^2+b^2=1 ⇔ \log (a^2+b^2)=0$, the condition becomes $-\pi<x\tan ^{-1}\frac{b}{a}\le \pi$
If $y=0$ or $a^2+b^2=1$ and $x=-1$ the condition becomes $-\pi<-\tan ^{-1}\frac{b}{a}\le \pi\implies \pi>\tan ^{-1}\frac{b}{a}\ge -\tan ^{-1}\frac{b}{a}$ which is true for all $a,b$.
If $y=0,x=2$ the condition becomes $-\pi<2\tan ^{-1}\frac{b}{a}\le \pi $
$\implies -\frac{\pi}2<\tan ^{-1}\frac{b}{a}\le \frac{\pi}2$ i.e, $a>0$.
Comment: Thank you! But how did you get a condition
$$
-\pi < \frac{1}{2}y ln(a^{2} + b^{2}) + x arctg\left(\frac{b}{a}\right) \leqslant \pi ?
$$
Comment: Please look into http://en.wikipedia.org/wiki/Argument_(complex_analysis)#Principal_value and http://en.wikipedia.org/wiki/Atan2
Comment: Thank you! You helped me very much.
Comment: There is another solution of this problem, as I think. For simplifying I make for $\alpha$ value $x = Real$. So for $z = re^{i(\varphi + 2 \pi k)}$ I can earn for multivalued $Ln(z^{\alpha})$

$$
Ln(z^{\alpha}) = \alpha\left(i(\varphi + 2 \pi k) + ln(r)\right) + 2 \pi j i = \alpha \left(i(\varphi + 2 \pi k) + ln(r) \right) + 2 \pi j i \qquad (.1),
$$

and for $\alpha Ln(z)$

$$
\alpha(Ln(z)) = \alpha (i(\varphi + 2 \pi n) + ln(r)) .
$$

So

$$
 \alpha (Ln(z)) = Ln(z^{\alpha}) \Rightarrow |(.1)| \Rightarrow 2 \pi i ( j  + \alpha k ) = \alpha 2 \pi i n.
$$
Comment: So, $\alpha = \frac{1}{n}, n$ - any whole number.


Private DNS Question

Question: I received the below request, just curious how I can go about doing this. I have IPs direct from ARIN and my own rdns server.
**
As you guys know I am a mailer, but I keep things very clean. My other provider I am currently getting Class C's from provides a private DNS. This way the public cannot view RDNS setup but the ISP's are allowed to see and verify RDNS. Do you offer this? The reason behind non-public rdns is to help a mailer like myself to keep IP space long term when using Class C's. There are blacklist organizations that scan Internet IP space looking for Class C's with a huge RDNS setup and then listing those IP blocks. By making the RDNS private you are making it so when these organizations scan there is nothing to see. However with ISP's being able to see the DNS server they are able to complete RDNS verification before accepting mail from the IPs. If you don't have this setup available that is fine I was just wondering since I am interested in larger IP space, but just need this kind of setup to be confident in keeping things long term.
Comment: Decided to post my answer.
Answer: There are two ways to do this, but it involves building a filter list that won't be accurate.  You can put the filter list of "good" IP addresses to access the zone in the named server configuration itself (a view) or you can build a firewall to drop packets from anything not on your good list.
However, this isn't a good tactic to use in the first place even if you could get the list of addresses that are valid to query from to be stable and accurate (which you can't).  It's likely that the querying ISP will be using their own normal resolver that is the same resolver that the ISP's clients will use.  If that's the case you're adding the client's default resolver to the white list, so everyone using the ISP can see the results too.
In short: that's a bad thing to do and you'd waste a ton of time trying to get it to work and it never will completely.
Answer: I am not an ISP, but do accept email.  If I can't verify your rDNS then I am likely to block your email.  If you are using your ISPs servers as a relay, give the Class C back and use their private namespace.  As a mailer you need postmaster@ and abuse@ address open for every sending domain.  Track bounces and bit bucket the rest.  If you are mailing on behalf of someone use a secondary domain like campaign.client.com.  Check out http://www.maawg.org/sites/maawg.
Setup an SPF like 'v=spf1 a -all' for all your sending domains.  This will help limit their use by spammer. Failing this SPF on your HELO will get your message rejected.  I may investigate its use on the rDNS address of the host as well.  It should be the same as the HELO address but unfortunately is not always.
Bulk and automated mailers make blocking server forgeries difficult because they so often get their DNS and server configuration wrong.  I hope you do it right.

Private DNS Question


php-zmq is not shown on phpinfo() page

Question: I am using Wamp Server on Windows and I installed zmq library. When I write php --info on console, I see that zmq is shown as intalled.

zmq
ZMQ extension => enabled
ZMQ extension version => 1.1.2
libzmq version => 3.2.2

But when I create a php page with phpinfo() function to show php configuration, it does not show anything about zmq. Plus, it is unable to find ZMQContext and other ZMQ classes, like ZMQSocket. I guess it's not fully installed, but I don't know what to do anymore. I have already modified both php.ini files with required info.

C:\wamp\bin\php\php5.5.12\php.ini
[ZMQ]
extension=php_zmq.dll

C:\wamp\bin\apache\apache2.4.9\bin\php.ini
[ZMQ]
extension=php_zmq.dll

Does anyone have any idea about why?
Comment: Did you manage to solve this problem? I'm currently having the same issue on mac osx.
Answer: I know this is old thread; however, I had the same problem and it took me time to fix the problem. The fix is to add following line in httpd.conf file
<code>LoadFile "D:/xampp/php/libzmq.dll"
</code>

php-zmq is not shown on phpinfo() page


Autocomplete com ajax em Entity Framework

Question: Tenho seguinte código HTML:
<input id="pesquisaEstilo" name="pesquisa" type="text" placeholder="Destrito, Concelho" />
<input type="submit" value="Pesquisar" id="botaoPesquisar"/>

Quero fazer autocomplete na barra de pesquisa usando a função de JQuery .autocomplete() com seguinte cógio:
$(function () {
$("#pesquisaEstilo").autocomplete({
    source: function (request, response) {
        $.ajax({
            url: "/Home/GetAutoCorrect",
            data: { term: request.term },
            success: function (ficheiro) {
                response($.map(ficheiro, function (item) {
                    return
                    {
                        val: item;
                    }
                }))
            },
            select: function (event, ui) {
                $("#pesquisaEstilo").val(ui.item.val);
            }
        });
    }
});

Código da ActionResult de /Home/GetAutoCorrect :
public ActionResult GetAutoCorrect(string term)
    {
        List<SelectListItem> lista = new List<SelectListItem>();

        //variavel "db" está definida em cima como private Lab4DBEntities1 db = new Lab4DBEntities1();
        var concelhos = db.Concelho.Where(a => a.Nome.Contains(term));

        foreach(var i in concelhos)
        {
            lista.Add(new SelectListItem() { Text= i.Nome.ToString(), Value = i.Nome.ToString()});
        }

        return Json(new SelectList(lista, "Text" , "Value"), JsonRequestBehavior.AllowGet);
    }

Como resposta do servidor recebo ficheiro json com os concelhos, porém não aparecem as sugestões na barra de pesquisa. Alguém me pode ajudar a resolver este problema?
Answer: Jquery esta faltando: type: "POST",  dataType: "json"
$(function () {
$("#pesquisaEstilo").autocomplete({
    source: function (request, response) {
        $.ajax({
            url: "/Home/GetAutoCorrect",
            data: { term: request.term },
               type: "POST",
               dataType: "json",
            success: function (ficheiro) {
                response($.map(ficheiro, function (item) {
                    return
                    {
                        val: item;
                    }
                }))
            },
            select: function (event, ui) {
                $("#pesquisaEstilo").val(ui.item.val);
            }
        });
    }
});

E no controller [HttpPost] e trocar ActionResult por JsonResult
[HttpPost]
public JsonResult GetAutoCorrect(string term)
    {
        List<SelectListItem> lista = new List<SelectListItem>();

        //variavel "db" está definida em cima como private Lab4DBEntities1 db = new Lab4DBEntities1();
        var concelhos = db.Concelho.Where(a => a.Nome.Contains(term));

        foreach(var i in concelhos)
        {
            lista.Add(new SelectListItem() { Text= i.Nome.ToString(), Value = i.Nome.ToString()});
        }

        return Json(new SelectList(lista, "Text" , "Value"), JsonRequestBehavior.AllowGet);
    }


How to display constant values using custom-columns format of kubectl?

Question: I have multiple clusters and I want to check which ingresses do not specify explicit certificate. Right now I use the following command:
~$ k config get-contexts -o name | grep -E 'app(5|3)41.+-admin' | xargs -n1 -I {} kubectl --context {} get ingress -A -o 'custom-columns=NS:{.metadata.namespace},NAME:{.metadata.name},CERT:{.spec.tls.*.secretName}' | grep '<none>'
argocd               argo-cd-argocd-server    <none>
argocd                argo-cd-argocd-server                                <none>
reference-app         reference-app-netcore-ingress                        <none>
argocd                  argo-cd-argocd-server                 <none>
argocd         argo-cd-argocd-server   <none>
test-ingress   my-nginx                <none>

~$

I want to improve the output by including the context name, but I can't figure out how to modify the custom-columns format to do that.
Comment: one way is to dich the `custom-column` and use `jsonpath`, something like this: `k config get-contexts -o name  |  xargs -n1 -I {} kubectl  get ingress -A -o jsonpath="{range .items[*]}{} {.metadata.namespace} {.metadata.name} {.spec.tls.*.secretName}{'\n'}{end}" --context {}`
Comment: what does `kubectx | grep -E 'app(5|3)41.+-admin' ` return ? (not a `kubectx` user)
Comment: Sorry, let me update the question.
Comment: Replaced `kubectx` with `k config get-contexts -o name`
Comment: the other option is use bash looping to add the context to each line.
Comment: @P.... - although not using `custom-columns`, but still very close and I can use it instead. Could you arrange it as an answer so I could credit you and others find it more easily?
Answer: The below command would Not yield the exact desired output, but it will be close. using jsonpath, it's possible:
kubectl config get-contexts -o name  |  xargs -n1 -I {} kubectl  get ingress -A -o jsonpath="{range .items[*]}{} {.metadata.namespace} {.metadata.name} {.spec.tls.*.secretName}{'\n'}{end}" --context {}

If the exact output is needed, then the kubectl output needs to be looped in the bash loop. Example:
kubectl config get-contexts -o name  |  while read context; do k get ingress -A -o 'custom-columns=NS:{.metadata.namespace},NAME:{.metadata.name},CERT:{.spec.tls.*.secretName}' --context "$context" |awk -vcon="$context" 'NR==1{$0=$0FS"CONTEXT"}NR>1{$0=$0 FS con}1'; done |column -t
NS       NAME                  CERT            CONTEXT
default  tls-example-ingress   testsecret-tls  email@example.com
default  tls-example-ingress1  testsecret-tls  firstname.lastname@example.com
default  tls-example-ingress2  <none>          firstname.lastname@example.com

To perform post-processing around the header and context, the awk command was used. Here is some details about it:
Command:
awk -vcon="$context" 'NR==1{$0=$0FS"CONTEXT"}NR>1{$0=$0 FS con}1'; done |column -t

-vcon="$context": This is to create a variable called con inside awk to store the value of bash variable($context).
NR==1: Here NR is the record number(in this case line number) and $0 means record/line.
NR==1{$0=$0FS"CONTEXT"}: This means, on the 1st line, reset the line to itself followed by FS(default is space) followed by a string "CONTEXT".
Similarly, NR>1{$0=$0 FS con} means, from the 2nd line onwards, append the line with FS followed by con.
1 in the end is the tell awk to do the print.
Comment: Right now this is a script friendly output, `custom-columns` produce human friendly output. Can we format the output nicely with the header and tabulated output? Would you mind updating your answer to make it on a par?
Comment: @mark checkout the update.
Comment: That answers the question, but the last part with `awk` and `column` requires some googling.


How to find $\arg\max$ of a neural network?

Question: Let's say I have a neural network $f$ that takes input $\vec x \in \mathbb {R}^n$ and produces output $f(\vec x) \in \mathbb{R}$.
How can I find $\hat x = \underset{\vec x}{\arg\max} \; f(\vec x)$?
Answer: You would have to do it in the same way you train it: numerical optimisation.
This comes down to applying backprop but having a loss function of the negative output and not changing the weights, but adapting the input. You would have to change your neural net software in a way that you also get the deltas at the input layer.


Laravel - Storage::url() não retorna url correta

Question: Iniciei no laravel a pouco tempo, no momento os arquivos estão sendo armazenados dentro da pasta storage, mas irei usar a biblioteca de armazenamento na nuvem do google cloud, consigo criar e ler arquivos normalmente mas o problema é ao tentar obter a url do arquivo para poder vizualizar os arquivos no aplicativo que vai estar consumindo minha api rest.
Essa é a estrutura de arquivos:
storage
      |- app
      |    |- data
      |    |- public
      |            |- images
      |                    |- produtos
      |                    |- supermercados
                                          |- 1
                                             | - 9d92b1d506a2065c4c0d132dbeb32217016d2a57f67a48ca7373cdff6bcd9ee6.jpeg
df974bf001ec886ab8ace6cdfab5850cf12ae66323927d55ccf591cc2f3079c0.jpeg
      |- framework
      |- logs

Estou tentando obter o link assim:
Storage::url('data/images/supermercados/' . $supermercado->id . '/' . $supermercado->foto);

Onde id é a pasta do supermercado e foto é o nome da foto
Porém ao invés de receber um link eu recebo este caminho:
 \/storage\/data\/images\/supermercados\/1\/df974bf001ec886ab8ace6cdfab5850cf12ae66323927d55ccf591cc2f3079c0.jpeg

Como faço para obter uma URL como http://site.com/imagem.jpge ?
Comment: Basta setar uma rota com esse nome `/imagem.jpge` e na rota escrita no controller coloque algo como `public function imagem() { return Storage::download('data/images/supermercados/' . $supermercado->id . '/' . $supermercado->foto, 'image.jpg', [ 'Content-Type' => 'image/jpeg' ]); }`
Comment: Tive um problema parecido com esse ontem. Faça um teste. Abra o `php artisan tinker` e digite `env('APP_URL')`. Se tiver retornando diferente do que está no arquivo `.env`, é bem provável que sua pasta `bootstrap/cache` tenha salvo alguma informação vazia ou diferente da configuração atual. Se não me engano, pode ser resolvido facilmente com `php artisan cache:clear`.
Comment: @GuilhermeNascimento estou em dúvida, eu uso uma biblioteca para carregar as imagens chamada Glide, ao passar a url ela vai efetuar um download ou a biblioteca vai carregar ela do servidor?
Comment: Vc disse q estava usando um cloud, então isso seria interno da propria API do laravel para resolver, agora se vc fez algo proprio não temos como saber e a duvida fica ambígua. Se puder detalhar nos ajudará a ajuda-lo.
Answer: Tive um problema parecido com esse ontem.
Eu estava tendo a url completa na minha máquina local e de mais duas pessoas funcionando corretamente, mostrando o caminho completo, ao chamar Storage::url. Porém, quando estava em produção, o caminho era retornado apenas com uma / antes.
O que acontece é que o Laravel geralmente utiliza o que está em APP_URL para poder montar a URL, em casos da configuração do disco public, no arquivo config/filesystems.php. E as demais configurações de storage também têm suas próprias configurações.
O que aconteceu foi que o Laravel criou um cache dentro da pasta bootstrap/cache, com valores que estavam bem diferente do .env ou dentro da pasta config.
O problema pode ser resolvido removendo ou renovando o cache de configuração, para forçar a atualização desses valores.
Você pode rodar o comando php artisan config:clear ou php artisan config:cache para tentar resolver isso.
Um bom teste é fazer o seguinte:
1 - Abra o .enve altere o valor de APP_URL para um valor qualquer, só pra testar.
2 - Abra o php artisan tinker e digite env('APP_URL'). Em seguida, dê ENTER pra exibir o valor.
2 - Compare o valor que está em .env e o valor retornado no seu terminal.
Se os valores forem diferentes, tente verificar se a pasta bootstrap/cache possui o arquivo config.php (que é o arquivo de cache de configuração).
Caso tenha problemas de permissão, você não consiga remover com o comando php artisan config:clear. Você pode optar por apagar o arquivo config.php manualmente.
NOTA: O problema do cache de configuração me causou problemas tanto na montagem de URL no disk public quanto no cloud que uso. Ambos os casos estava exibindo informações diferente do que estava configurado ou esperado.
Comment: Sim, é que no vs code não mostra como atalho, mas ao verificar no explorador de arquivos vi que é um link mesmo, problema resolvido, bastou acessar com asset()
Comment: Fiz o que você disse o APP_URL esta retornando localhost, porém no Storage::url() retorna nada
Comment: No caso, você conferiu o arquivo `filesystems.php`? Geralmente, onde está configurado como `disks.public`, tem um trecho que contém a montagem da url, dessa forma `'url' => env('APP_URL') . '/storage`.
Comment: Outra coisa: Chama `echo Storage::url('')` em uma rota qualquer e chama `Storage::url('')` no `php artisan tinker`. Veja se os resultados são idênticos. Eu estava tendo problemas quando chamava via Browser e Via Terminal. Os resultados eram diferentes.
Comment: @SamuelIves rode o comando `ls bootstrap/config` e vê se aparece algo. Claro, se tiver usando algum sistema Unix Like. No Windão, só entra na pasta e vê se têm algo lá
Comment: 'public' => [
            'driver' => 'local',
            'root' => storage_path('app/public'),
            'url' => env('APP_URL').'/storage',
            'visibility' => 'public',
        ],
Comment: Se root aponta para public então por que Storage::put() coloca em data?
Comment: Porque `root` é a raiz. O caminho que você passa como argumento de `put`, é acrescentado o que está defindo em `root`. Exemplo: `Storage::put('pasta/arquivo.txt', 'meu arquivo')` irá criar o caminho `storage/app/public/pasta/arquivo.txt`.
Comment: Storage::put('data/juno/token.json', json_encode($tokenData)); ele deveria estar indo para public
Comment: O Laravel separa esses arquivos na pasta `public`, porque, quando é invocado `php artisan storage:link`, é criado um link simbólico (atalho) dentro da pasta public, para disponibilizar a visualização dos arquivos através da `$url/storage/$caminho_do_arquivo`.
Comment: Sobre a pasta que você está armazenando, é melhor sempre você conferir qual é o adapter configurado em `filesystems.default`. Você pode olhar o arquivo `config/filesystems.php` ou mesmo chamar no `php artisan tinker`: `config('filesystems.default')`
Comment: Esta tudo configurado como local, php artisan storage:link cria a pasta public porém apenas com um .gitignore
Comment: Consegui resolver o problema porém, sempre que eu enviar um arquivo vou ter que abrir o terminal e digitar: php artisan storage:link? E por que o laravel duplica os arquivos criando uma pasta storage no diretório public?
Comment: Ele não duplica. Como eu disse antes, isso é um link simbólico (é como se fosse um atalho do windows)
Answer: Eu estava com problema semelhante. Funcionando perfeitamente no localhost, com VS Code etc. Fiz o DEPLOY acertei vários probleminhas, mas as imagens não apareciam na relação dos itens (Biblioteca ==> capa dos livros, logo das editoras, fotos dos usuários e dos leitores) e nem nas visualizações. Apliquei php artisan route:cache; php artisan route:clear; php artisan cache:clear; php artisan view:clear; php artisan config:cache; php artisan config:clear e, depois composer dump-autoload, seguido de php artisan storage:link. Funcionou.


Are all series in the elementary Ramanujan class R = 1 non-summable by analytic continuation of Dirichlet series?

Question: We say that a series $\sum_{n=1}^\infty a_n$ and the corresponding power series $f(x)=\sum_{n=1}^\infty a_nx^n$ belong to the Ramanujan class $R=1$ if $g(x)=f(x)-f(x^2)$ is Abel summable at $x=1$ (here).
Does the analytic continuation of the Dirichlet series $F(s)=\sum_{n=1}^\infty a_n n^{-s}$ have a simple pole at $s=0$?
Example 1. The harmonic series
$$
1+\frac{1}{2}+\frac{1}{3}+\cdots~,
$$
corresponding to $f(x)=-\ln(1-x)$, $g(x)=\ln(1+x)$ ($|x|<1$) (here) and $F(s)=\zeta(s+1)=\eta(s+1)/(1-2^{-s})$.
Example 2. The series $1+1+0+1+0+0+0+1+\cdots$ corresponding to
$f(x)=\sum_{k=0}^\infty x^{2^k}$, $g(x)=x$ and $F(s)=1/(1-2^{-s})$.
Example 3. For $g(x)=x-x^2+x^3-\cdots=x/(1+x)$ ($|x|<1$) corresponding to the Grandi series $1-1+1-\cdots$ Abel summable to $1/2$, we have $a_n=1-m_2(n)$, where $m_2(n)$ is the multiplicity of 2 (the 2-adic order) of $n$ and $F(s)=\eta(s)/(1-2^{-s})$.
In general, for a power series $g(x)=\sum_{n=1}^\infty b_n x^n$ Abel summable at $x=1$, the coefficients $a_n$ are determined by the recursive relations $a_{2n-1}=b_{2n-1}$ and $a_{2n}=b_{2n}+a_n$. Is the analytic continuation of $(1-2^{-s})F(s)$ holomorphic at $s=0$?
Answer: No. The analytic continuation of $F(s)$ can be holomorphic at $s=0$ if $\lim_{x\to 1^-}g(x)=0$.
Example 1. $f(x)=x$, $g(x)=x-x^2$, $F(s)=1$ for all $s$.
Example 2. $g(x)=x-x^3$, $f(x)=\sum_{k=0}^\infty x^{2^k}-x^{3\times2^k}$,
$F(s)=(1-3^{-s})/(1-2^{-s})$, with $F(0)=\ln3/\ln2$ and $F'(0)=-\ln3\times\ln(3/2)/2\ln2$.
If $\lim_{x\to 1^-}g(x)\neq 0$, the analytic continuation of $F(s)$ has a simple pole at $s=0$, since the recursive relation between the coefficients of $f(x)$ and $g(x)$ implies $F(s)=G(s)/(1-2^{-s})$, where $G(s)=\sum_{n=1}^\infty b_n n^{-s}$ (here and here).


Mobile Tools detects mobile and iPad, not Android tablet

Question: I have used the Mobile Tools module for Drupal 6 to distinguish between mobiles,tablets and browsers. I am not using themes, just provided the redirection urls from the drupal admin settings.
The aim is  to redirect to mobile site while accessing from mobile(mysite.com/mobile).
Must redirect to the existing site while taken from tablet and web browsers(mysite.com).
It works fine for iphone,andorid mobile,blackberry and iPad.
But it redirects to mobile site when taken from Android tablet while I need to redirect to the desktop url.
Can anybody suggest how can I handle the android tablet using mobile tool so that it does not get redirected to mobile site?
Comment: Is the browscap current?
Comment: When browscap module was added and enabled,the drupal site went down.Therefore,i removed it. is there any provision to forcefully redirect the android tablet users to desktop site using mobile tool?
Comment: Pretty sure D6 module can use a brows cap file if you configure PHP.ini properly. It sounds like you just need updated definitions, but that is just a guess.
Answer: Have you looked at ThemeKey? It has OS based redirection rules. Here is a quote about it (from the module's project page):

... allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties. It can also be easily extended to support additional properties exposed by other modules. In combination with Drupal's theme inheritance you can easily achieve features like:

individually-styled channels
a front-page / "splash" screen
a date/time-selected Christmas theme
mobile themes for different auto-detected mobile devices
special themes for "limited" or "old" browsers
content, user, or role -specific themes
indicating your environment (production, staging, testing, sandbox, … )
testing your redesign safely on a live server
Answer: Finally, I made some modification in the mobile tool file to work for android tablet and it seems to be okay now.


Calcular idade através da data de nascimento

Question: Estou tentando calcular a idade em um campo de um formulário através da data de nascimento , só que me retorna o erro de compilação 13 type mismatch. Por favor alguém me ajude? Eis o CODIGO.
Private Sub CmbCalcular_Click()

    Dim datanasc As Date, idade As Integer

    datanasc = CDate(MskDataNasc.Mask)
    idade = CInt((Date - datanasc) / 365)
    TxtIdade = Str(idade) & "anos"

End Sub

Comment: o problema se dá na linha onde se encontra o maskedbox.
Answer: Há alguns erros o seu exemplo. Na linha idade = CInt((Date - datanasc) / 365) você está usando a classe Date como se fosse uma instancia.
Outra coisa é que para obter intervalos de tempo como número de dias, meses ou numero de anos use a classe TimeSpan(https://docs.microsoft.com/system.timespan)
Private Sub CmbCalcular_Click()

    ' Declare a variável intervalo com sendo do tipo TimeSpan
    Dim datanasc As Date, idade As Integer, intervalo As TimeSpan

    'Use propriedade Text ao invés de Mask.
    'Mask é mascara de edição e Text é o valor digitado
    datanasc = CDate(MskDataNasc.Text)

    ' Compute a diferença ente hoje e datanasc
    intervalo = Now - datanasc;

    ' use a propriedade TotalDays para obter número de dias decorridos
    idade = Math.Abs(intervalo.TotalDays  / 365)

    TxtIdade = Str(idade) & "anos"

End Sub

Answer: Utilize IsDate(valor) que vai retornar true se a data for válida, utilize Text para pegar o valor do conteúdo MaskedBox e por fim não Date é Now para pegar a data atual, ou seja, tem três problemas no seu código:
Solução:
Private Sub CmbCalcular_Click()
    Dim datanasc As Date, idade As Integer
    If IsDate(MskDataNasc.Text) Then
          datanasc = CDate(MskDataNasc.Text)
          idade = CInt((Now - datanasc) / 365)
          TxtIdade = Str(idade) & "anos"
    Else
          TxtIdade.Text = "Data inválida"
    End If
End Sub

O erro informado type mismatch, significa que tentou converter para um determinado tipo, mas, essa conversão não é válida, então, utilize IsDate(valor) antes para verificar se é possivel a conversão para Date
Answer: Public Function CalculaIdade(ByVal dDataNasc As Date, Optional ByVal dDataHoje As Date = Nothing) As String

    Dim cResult As String = ""

    If dDataHoje = Nothing Then
        dDataHoje = Today
    End If

    If dDataNasc <> Nothing AndAlso dDataNasc <= dDataHoje Then

        Dim dDataTemp = dDataNasc
        Dim anos = DateDiff("yyyy", dDataTemp, dDataHoje)

        dDataTemp = dDataTemp.AddYears(anos)

        Dim meses = DateDiff("m", dDataTemp, dDataHoje)
        If meses < 0 Then
            anos = anos - 1
            dDataTemp = dDataTemp.AddYears(-1)
            meses = DateDiff("m", dDataTemp, dDataHoje)
        End If

        dDataTemp = dDataTemp.AddMonths(meses)

        Dim dias = DateDiff("d", dDataTemp, dDataHoje)
        If dias < 0 Then
            meses = meses - 1
            If meses < 0 Then
                anos = anos - 1
                meses = 12 + meses
            End If
            dDataTemp = dDataTemp.AddMonths(-1)
            dias = DateDiff("d", dDataTemp, dDataHoje)
        End If

        If anos <> 0 Then
            cResult = cResult & anos & IIf(anos = 1, " ano", " anos")
        End If

        If anos < 18 Then
            If meses <> 0 Then
                cResult = cResult & IIf(cResult.Length = 0, "", ", ") & meses & IIf(meses = 1, " mes", " meses")
            End If
            If anos <= 2 Then
                If dias <> 0 Then
                    cResult = cResult & IIf(cResult.Length = 0, "", " e ") & dias & IIf(dias = 1, " dia", " dias")
                End If
            End If
        End If

    End If

    Return cResult

End Function


Distribution of the F-statistic of a Wald test

Question: On the Wikipedia page for the Wald test, there is a derivation for the test statistic under multiple hypotheses. The derivation ends in an F-distribution. I am curious about the final step in that derivation, repeated below.
Suppose $\hat{\theta}_n$ is a $P\times 1$ vector and $R$ is a $Q\times P$ matrix.
The null and alternative hypotheses are: $$H_0: R\theta =r\text{   with }H_1: R\theta \ne r$$
Suppose $$\sqrt{n}(\hat{\theta}_n-\theta)\rightarrow N(0,V) $$
Then, by Slutsky's theorem and the properties of the normal distribution, multiplying by $R$ has distribution
$$R\sqrt{n}(\hat{\theta}_n-\theta)\rightarrow N(0,RVR') $$
Recalling that a quadratic form of normal distribution has a chi-squared distribution:
$$\sqrt{n}(R\hat{\theta}_n-r)[RVR']^{-1}\sqrt{n}(R\hat{\theta}_n-r)\rightarrow \chi^2_Q $$
Rearranging $n$ gives
$$(R\hat{\theta}_n-r)[R(V/n)R']^{-1}(R\hat{\theta}_n-r)\rightarrow \chi^2_Q $$
The step that confuses me is next.
If the covaraince matrix, $V$, is not known but needs to be estimated and we have a consistent estimator, $\hat{V}_n\sim \chi^2_{n-P}$ of $V$, then by independnece of the covariance estimator and equation above, we have,
$$(R\hat{\theta}_n-r)[R(\hat{V}_n/n)R']^{-1}(R\hat{\theta}_n-r)\rightarrow F_{Q,n-P} $$
I am confused because $\hat{V}_n$ is a matrix. What does it mean for a matrix to be distributed as $\chi^2$ ? Also, how is independence applied to derive the final result?
I'm essentially just looking for a couple more details in this final step and greatly appreciate any help.
Answer: I will give it a try. Assume that the Gauss-Markov assumptions hold and we deal with a simple linear regression model:
$$
\boldsymbol{y}=\boldsymbol{X}\boldsymbol{\beta}+\boldsymbol{u} \quad, \boldsymbol{u} \vert \boldsymbol{X} \sim {\cal N}(\boldsymbol{0}_n, \sigma^2 \boldsymbol{I}_n)
$$
You want to test $H_0: \boldsymbol{R}\boldsymbol{\beta}=\boldsymbol{r}$ where $\boldsymbol{R} \in \mathbb{R}^{n \times k}$ with $rank(\boldsymbol{R})=r$. The F-statistic is defined as
$$
F= \frac{(\boldsymbol{R}\hat{\boldsymbol{\beta}}-\boldsymbol{r})^\top[\boldsymbol{R}(\boldsymbol{X}^\top\boldsymbol{X})^{-1}\boldsymbol{R}^\top]^{-1}(\boldsymbol{R}\hat{\boldsymbol{\beta}}-\boldsymbol{r})/r}{\hat{\sigma}^2}
$$
which is $F_{r,n-k}$ distributed under $H_0$. By definition, if $X_1 \sim \chi^2(d_1)$ and $X_2 \sim \chi^2(d_2)$, and $X_1$ and $X_2$ are independent, then $F=\frac{X_1/d_1}{X_2/d_2}$ is $F_{d_1,d_2}$ distributed.
Note that an unbiased and consistent estimator for the variance of the disturbances is given by $\hat{\sigma}^2=\frac{\boldsymbol{\hat{u}}^\top\boldsymbol{\hat{u}}}{n-k}$. So, we can write:
\begin{align}
F&=\frac{(\boldsymbol{R}\hat{\boldsymbol{\beta}}-\boldsymbol{r})^\top[\boldsymbol{R}(\boldsymbol{X}^\top\boldsymbol{X})^{-1}\boldsymbol{R}^\top]^{-1}(\boldsymbol{R}\hat{\boldsymbol{\beta}}-\boldsymbol{r})/r}{\hat{\sigma}^2}\\
&=\frac{(\boldsymbol{R}\hat{\boldsymbol{\beta}}-\boldsymbol{r})^\top[\boldsymbol{R}(\boldsymbol{X}^\top\boldsymbol{X})^{-1}\boldsymbol{R}^\top]^{-1}(\boldsymbol{R}\hat{\boldsymbol{\beta}}-\boldsymbol{r})/r}{\frac{\boldsymbol{\hat{u}}^\top\boldsymbol{\hat{u}}}{n-k}}\\
&=\frac{d/r}{q/(n-k)}
\end{align}
Where $d=(\boldsymbol{R}\hat{\boldsymbol{\beta}}-\boldsymbol{r})^\top[\sigma^2\boldsymbol{R}(\boldsymbol{X}^\top\boldsymbol{X})^{-1}\boldsymbol{R}^\top]^{-1}(\boldsymbol{R}\hat{\boldsymbol{\beta}}-\boldsymbol{r})^\top$ and $q=\frac{\boldsymbol{\hat{u}}^\top\boldsymbol{\hat{u}}}{\sigma^2}$, $\sigma^2$ is now the "true" variance of the disturbances. Basically, all we have to do now is to show that:

$d \vert \boldsymbol{X} \sim \chi^2(r)$
$q \vert \boldsymbol{X} \sim \chi^2(n-k)$
$d$ and $q$ are independent conditional on $\boldsymbol{X}$

Proof of 1
Let $\boldsymbol{a}=\boldsymbol{R}\hat{\boldsymbol{\beta}}-\boldsymbol{r}$. Under $H_0$, this becomes $\boldsymbol{R}\hat{\boldsymbol{\beta}}-\boldsymbol{r}=\boldsymbol{R}(\hat{\boldsymbol{\beta}}-\boldsymbol{\beta})$. Since the sampling error $\hat{\boldsymbol{\beta}}-\boldsymbol{\beta}$ is distributed as $\hat{\boldsymbol{\beta}}-\boldsymbol{\beta}\vert \boldsymbol{X} \sim {\cal N}(\boldsymbol{0}_k,\sigma^2(\boldsymbol{X}^\top\boldsymbol{X})^{-1})$, we know that $\boldsymbol{a}$ is Mv normal with mean vector $\boldsymbol{0}_k$ but we still need to calculate the covariance matrix:
\begin{align}
Var(\boldsymbol{a} \vert \boldsymbol{X})=Var(\boldsymbol{R}(\hat{\boldsymbol{\beta}}-\boldsymbol{\beta})\vert \boldsymbol{X})=\boldsymbol{R}Var(\hat{\boldsymbol{\beta}}-\boldsymbol{\beta}\vert \boldsymbol{X})\boldsymbol{R}^\top=\boldsymbol{R}\sigma^2(\boldsymbol{X}^\top\boldsymbol{X})^{-1}\boldsymbol{R}^\top
\end{align}
Thus, $d$ can be written as $\boldsymbol{a}^\top Var(\boldsymbol{a} \vert \boldsymbol{X})\boldsymbol{a}$ which is a quadratic form.
Furthermore, if $\boldsymbol{y} \in \mathbb{R}^{m \times 1}$ is $\cal{N}(\boldsymbol{\mu},\boldsymbol{\Sigma})$ distributed, the quadratic form $(\boldsymbol{y}-\boldsymbol{\mu})^\top\boldsymbol{\Sigma}^{-1}(\boldsymbol{y}-\boldsymbol{\mu})$ is $\chi^2(m)$ distributed.
It follows that $d \vert \boldsymbol{X} \sim \chi^2(r)$.
Proof of 2
Remember:
\begin{align*}
\frac{\boldsymbol{\hat{u}}^\top\boldsymbol{\hat{u}}}{\sigma^2}&=\frac{\boldsymbol{u}^\top\boldsymbol{M}\boldsymbol{u}}{\sigma^2}
\end{align*}
Where $\boldsymbol{M}=\boldsymbol{I}_n-\boldsymbol{X}(\boldsymbol{X}^\top\boldsymbol{X})^{-1}\boldsymbol{X}^\top$ is the residual maker matrix (which is symmetric and idempotent). Since $\boldsymbol{u} \vert \boldsymbol{X} \sim {\cal N}(\boldsymbol{0}_n, \sigma^2 \boldsymbol{I}_n)$ and $rank(\boldsymbol{M})=tr(\boldsymbol{M})=n-k$, we have ${q\vert \boldsymbol{X} \sim \chi^2(n-k)}$. Where the last part follows from the fact that if $\boldsymbol{y} \sim {\cal N}(\boldsymbol{0}_n,\sigma^2 \boldsymbol{I}_n)$ and $\boldsymbol{M} \in \mathbb{R}^{n \times n}$ is a symmetric, idempotent, and non-stochastic matrix, then the distribution of the quadratic form $\boldsymbol{y}^\top\boldsymbol{M}\boldsymbol{y}$ is given by:
\begin{align}
\boldsymbol{y}^\top\boldsymbol{M}\boldsymbol{y} \sim \chi^2(tr(\boldsymbol{M}))
\end{align}
It follows that $q \vert \boldsymbol{X} \sim \chi^2(n-k)$.
Proof of 3
Basically, $d$ is a function of $\hat{\boldsymbol{\beta}}$ and $q$ is a function of the residuals $\boldsymbol{\hat{u}}$. Now, note that:
\begin{align}
Cov(\boldsymbol{\hat{\beta}},\boldsymbol{\hat{u}}\vert \boldsymbol{X})&=E([\boldsymbol{\hat{\beta}}-E(\boldsymbol{\hat{\beta}}\vert \boldsymbol{X})][\boldsymbol{\hat{u}}-E(\boldsymbol{\hat{u}}\vert \boldsymbol{X})]^\top \vert \boldsymbol{X})\\
&=E([\boldsymbol{\hat{\beta}}-\boldsymbol{\beta}][\boldsymbol{M}\boldsymbol{u}-E(\boldsymbol{M}\boldsymbol{u}\vert \boldsymbol{X})]^\top \vert \boldsymbol{X})\\
&=E((\boldsymbol{X}^\top\boldsymbol{X})^{-1}\boldsymbol{X}^\top\boldsymbol{u}[\boldsymbol{M}\boldsymbol{u}-\boldsymbol{M}E(\boldsymbol{u}\vert \boldsymbol{X})]^\top \vert \boldsymbol{X})\\
&=E((\boldsymbol{X}^\top\boldsymbol{X})^{-1}\boldsymbol{X}^\top\boldsymbol{u}[\boldsymbol{M}\boldsymbol{u}-\boldsymbol{M}]^\top \vert \boldsymbol{X})\\
&=E((\boldsymbol{X}^\top\boldsymbol{X})^{-1}\boldsymbol{X}^\top\boldsymbol{u}[\boldsymbol{M}\boldsymbol{u}]^\top \vert \boldsymbol{X})\\
&=E((\boldsymbol{X}^\top\boldsymbol{X})^{-1}\boldsymbol{X}^\top\boldsymbol{u}\boldsymbol{u}^\top\boldsymbol{M}^\top \vert \boldsymbol{X})\\
&=(\boldsymbol{X}^\top\boldsymbol{X})^{-1}\boldsymbol{X}^\top E(\boldsymbol{u}\boldsymbol{u}^\top\vert \boldsymbol{X})\boldsymbol{M}^\top\\
&=(\boldsymbol{X}^\top\boldsymbol{X})^{-1}\boldsymbol{X}^\top \sigma^2\boldsymbol{I}_n\boldsymbol{M}^\top\\
&=\sigma^2(\boldsymbol{X}^\top\boldsymbol{X})^{-1}\boldsymbol{X}^\top\boldsymbol{M}^\top\\
&=\sigma^2(\boldsymbol{X}^\top\boldsymbol{X})^{-1}(\boldsymbol{M}\boldsymbol{X})^\top\\
&=\boldsymbol{0}_{n \times n}
\end{align}
Where the last line follows from the property of the residual-maker matrix that $\boldsymbol{M}\boldsymbol{X}=\boldsymbol{0}_{n \times n}$. Therefore, $\boldsymbol{\hat{\beta}}$ and $\boldsymbol{\hat{u}}$ are independently distributed conditional on $\boldsymbol{X}$ (two joint normal uncorrelated random variables are independent). Furthermore, if two random vectors $\boldsymbol{x}$ and $\boldsymbol{y}$ are independent, so are every measurable functions $f(\boldsymbol{x})$ and $g(\boldsymbol{y})$. Thus, $d$ and $q$ are independent conditional on $\boldsymbol{X}$.
Finally, combining these results yields the desired result $F \vert \boldsymbol{X} \sim F_{r,{n-k}}$. However, since this distribution does not depend on $\boldsymbol{X}$, the conditional distribution is identical to the unconditional distribution and we get $F \sim F_{r,{n-k}}$.
As you can see, you need to have a solid understanding about linear regressions and the distribution of quadratic forms to understand this explanation. If you want to refresh your knowledge about this stuff, I can recommend the book of Greene "Econometric Analysis". Especially the appendix of this book is helpful to get an overview about the distribution of quadratic forms and the multivariate normal distribution.
I hope that you find this answer helpful.
Comment: Thank you Lars. I am aware of two economists by the name of Lars, I don't know if you are either of them, but I have great respect for each.
Comment: The exact distribution of $F$ critically relies on the assumptions of homoskedasticity and normality. However, if you assume that the assumptions for applying the CLT are fulfilled, you get the same results asymptotically.
Comment: If the error is not normally distributed. Would your point 2 need to appeal to the Central Limit Theorem?


Get specific value with Spring JDBC multiple condition java

Question: I try to get data with multiple conditions in Spring database with this code
public void AbsenStaff(int id, String category) {
    Staff staff = new Staff();
    String sql = "Select Absensi from Karyawan WHERE id=? AND Category=?";
    int a = jdbcTemplate.queryForObject(sql, new Object[] { id },new Object[]{category},Integer.class);
    staff.setjmlhAbsensi(a);
}

However, IntelliJ gives me this error:
Cannot resolve method 'queryForObject(
     java.lang.String,
     java.lang.Object[],
     java.lang.Object[],
     java.lang.Class<java.lang.Integer>)'

Is there something wrong with my code?
Answer: You need to send all parameter values in an object array, so you are calling a different method.
Try like this:
public void AbsenStaff(int id, String category) {
    Staff staff = new Staff();
    String sql = "Select Absensi from Karyawan WHERE id=? AND Category=?";
    int a = jdbcTemplate.queryForObject(sql, new Object[]{id, category}, Integer.class);
    staff.setjmlhAbsensi(a);
}

In addition, this usage has been depracated in the current version. I suggest you write as below:

jdbcTemplate.queryForObject(sql, Integer.class, id, category);
Answer: According to https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/jdbc/core/JdbcTemplate.html
These are the valid method signatures for the queryForObject method

queryForObject(String sql, Class requiredType)
queryForObject(String sql, Class requiredType, Object... args)
queryForObject(String sql, Object[] args, Class requiredType)
queryForObject(String sql, Object[] args, int[] argTypes, Class requiredType)
queryForObject(String sql, Object[] args, int[] argTypes, RowMapper rowMapper)
queryForObject(String sql, Object[] args, RowMapper rowMapper)
queryForObject(String sql, RowMapper rowMapper)
queryForObject(String sql, RowMapper rowMapper, Object... args)

So you must choose one of these (according to your needs) and provide the parameters in the right order and with the right data types.
I suppose you want to use this one
queryForObject(
  String sql,
  Object[] args,
  Class<T> requiredType)

In this case, you should use
int a = jdbcTemplate.queryForObject(
  sql,
  new Object[] {id,category},
  Integer.class);


Menu em C que se move com as setas do teclado?

Question: Vi uma vez um algoritmo em C onde na seleção de menu tinha uma "mini navegação" se é que posso chamar assim, onde usava as setas do teclado para navegar no menu e enter para selecionar a opção, fiquei curioso pra saber como fazer aquilo, alguém pode mostrar?
Grato!
Comment: Pesquisa por uma lib em C chamada "ncurses", é a única que eu conheço que faz isso.
Comment: No stackoverflow, nos ajudamos a consertar algum erro em códigos, ou tiramos duvidas sobre temas considerados importantes no escopo do site. Se você tiver algo pre pronto, ajudaria muito para te ajudar
Comment: @BrumazziDB Não tenho, como disse é uma curiosidade =/ não encontrei nada na internet sobre isso, gostaria de saber se preciso de alguma biblioteca ou algo do tipo.
Answer: Encontrei uma maneira, porém só funciona com duas opções no menu =/
<code>#include<stdio.h>
#include<stdlib.h>
#include<conio.h>

#define KEY_UP 72
#define KEY_DOWN 80
#define KEY_ESC 27
#define KEY_ENTER 13

void menu_draw();

int main (int argc, char ** argv)
{
     menu_draw();
     return 0;
}

void menu_draw ()
{
    int key = 0;
    while(1)
{
    system("cls");
    printf("\n   ******** Menu Principal ********\n");
    printf("   *                              *\n");
    printf("   * %s Opcao 1                    *\n", (key == KEY_UP)? "Û": " ");
    printf("   * %s Opcao 2                    *\n", (key == KEY_DOWN)? "Û": " ");
    printf("   *                              *\n");
    printf("   ********************************\n");
    key = getch();

    if (key == KEY_ESC)
        return;
    }
}
</code>
Comment: isto é a solução da pergunta ou uma nova dúvida?
Comment: Uma solução que encontrei pesquisando.
Comment: Entendi, você pode marcar como accept quando o sistema permitir. Estava parecendo uma nova dúvida no texto da resposta.
Comment: rsrs tranquilo amigo.


Generate Byte Array from Stream

Question: I am trying to generate byte array from a stream of ".rtf" file.
The code is as follows:
<code>Public Sub Button_Click(ByVal sender As Object, ByVal e As System.EventArgs)

    Try
        Dim result As System.Nullable(Of Boolean) = textDialog.ShowDialog()

        If result = True Then
            Dim fileStream As Stream = textDialog.OpenFile()

            GetStreamAsByteArray(fileStream)
        End If
    Catch ex As Exception

    End Try

End Sub

Private Function GetStreamAsByteArray(ByVal stream As System.IO.Stream) As Byte()

    Dim streamLength As Integer = Convert.ToInt32(stream.Length)

    Dim fileData As Byte() = New Byte(streamLength) {}

    ' Read the file into a byte array
    stream.Read(fileData, 0, streamLength)
    stream.Flush()
    stream.Close()

    Return fileData

End Function
</code>
The above code generates stream length for the file opened however the byte array returned only have 0's in the array.
How can i generate correct byte array?
Answer: You function does not returns the byte array to any object. This example works for me:
<code> Dim bytes = GetStreamAsByteArray(textDialog.File.OpenRead)
 MessageBox.Show(bytes.Length.ToString)
</code>
Comment: textDialog.File.OpenRead is not available
Comment: I ran a test in Silverlight, what version are you using?

Generate Byte Array from Stream


Consequence of separability in a locally compact metric space

Question: The reason why I didn't find an answer to my problem in the first place, was that I wasn't familiar with the concept "second countable" and therefore didn't realize that the condition of my problem implied second countability. No problem if this reason is insufficient for reopening. Here is my original question :
I am trying to prove that in a locally compact metric space $E$, separability implies that $E$ is a countable union of compact sets.
I know that (in a locally compact space) every compact set (and not just every point) has a compact neighborhood. Let $\{x_1, x_2, \dots \}$ be an enumeration of a countable and dense subset of $E$. I know that the set of open balls around $x_1, x_2, \dots$ with positive rational radii constitutes a basis of the topology of $E$, and I wonder how using this fact might complete my proof.
My idea is the following : let $C_1$ be a compact neighborhood of $x_1$ and $O_1=\dot{C}_1$ (interior of $C_1$). We have $C_1=\bar{O}_1$. Then, let $C_2$ be a compact neighborhood of the compact set containing the union of $C_1$ with a compact neighborhood of $x_2$ and let $O_2=\dot{C}_2$. We have $C_2=\bar{O}_2$. By continuing in this way, I'm afraid that $\bigcup_{n \in \mathbb{Z}_{+}} C_n$ might not be equal to $E$. The reason why I introduce $O_1, O_2, \dots$ is that I might need to replace them somehow by the open balls that form a basis of the topology and use the fact that their union is $E$.
If I use the open balls which constitute a basis of the topology or the corresponding closed balls, to have the union "grow more rapidly", I'm afraid that these closed balls might not be compact and I don't know how to argue that they have a compact neighborhood.
Answer: If $E$ is a metric space then separabaility$\iff$second countable space. Let $\mathcal{B}=\{B_{n}: n \in \mathbb{N}\}$ a countable base. Since for every $x\in E$ by hypothesis $\exists U$ such that U is open and $x\in U_x\subset K_x$ where $K_x$ is compact. Since every metric space is T2, $K_x$ is even closed, and that Is what you need in this situation. Since $\mathcal B$ is a base for every $x \in E$ $\exists B_n \in \mathcal B$depending on x.Let $B_{n_x}=B_n$ then $B_{n_x}\subset U_x\subset K_x$. Now because $K_x$ is closed you have that $\overline B_{n_x}\subset \overline K_x\subset K_x$ so $\overline B_{n_x}$ is compact since is closed in a compact. Consider now $\Phi = \bigcup_{x \in E}\overline B_{n_x}$ it is indexed on E but $\Phi\subset \overline {B}=\{\overline B_{n}: n \in \mathbb{N}\}$ which is countable. $\square$
Comment: Thank you, @giorgiokyn23. You answered perfectly my question. I missed that for all $x \in E$ there is a $n_x$ such that $B_{n_x} \subset U_x \subset K_x$, which was exactly what I needed to learn :-)
Comment: I spent half an hour to realize it was countable. It is not intuitive at all. Thanks to you is a very good problem. Have a good day.


Is it possible to add template suggestions for image styles?

Question: I am experimenting with durpal 8 theme hook suggestions. I tried to customize the the theme suggestions based on the style name. I want the ability to add a twig template for each style if I wanted so I tried this:
function themename_theme_suggestions_image_style_alter(&$suggestions, array $variables, $hook) {
  $suggestions[] = [$hook . '__' . $variables['style_name']];
}

and
function themename_theme_suggestions_image_alter(&$suggestions, array $variables, $hook) {
  $suggestions[] = [$hook . '__' . $variables['style_name']];
}

I was expecting to see this as a theme hook suggestion in the html comments printed by in the page source after enabling twig debuging.
Using xdebug the hook is triggered but I don't find it in the suggestions list in the html after enabling   twig.config.debug to true.
am I missing anything?
Answer:
hook_theme_suggestions_HOOK_alter doesn't use a third argument.
You are supposed to add the suggestions as string.

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYTHEME_theme_suggestions_image_style_alter(array &$suggestions, array $variables) {
  $suggestions[] = $variables['theme_hook_original'] . '__' . $variables['style_name'];
}

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYTHEME_theme_suggestions_image_alter(array &$suggestions, array $variables) {
  $suggestions[] = $variables['theme_hook_original'] . '__' . $variables['style_name'];
}

Comment: [the $hook param is not required but it does get passed](https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21theme.api.php/function/hook_theme_suggestions_alter/8.2.x) to hook_theme_suggestions_HOOK_alter . Not sure why it's not in the documentation you referenced. But it's indeed the array that I did not catch. Not sure how I missed it ... thanks
Comment: I wish there was a way to come back and upvote an answer that I'd already upvoted from a while back. Thanks again for the fish!


How to check data connectivity ,phn number, operator name in J2ME

Question: I used System.getProperty("wireless.messaging.sms.smsc") but it is showing some other number. How to get mobile number, operator of the SIM which is used and to check data connectivity.
Comment: what j2me version ? CLDC? MIDP? As far as I can remember how to obtain the information you seek was (if at all possible) device and vendor dependent. So vendor and model might help, too.
Comment: Thanks for reply . I am working with MIDP model  is Nokia and vendor is AIRTEL
Comment: Sorry, my comment was unclear. What would be helpful would be your **J2ME** **Version**. J2ME is split up into **CLDC** (Connected Limited Device Configuration) and **MIDP** (Mobile Information Device Profile). Both the CLDC version and the MIDP version would be of interest. Further more, the specific device you are using and what additional libraries are supported by that device is important, too. you can find a list of libraries associated with J2ME [here](https://en.wikipedia.org/wiki/Java_Platform,_Micro_Edition)
Comment: Thank you for providing document ,but I need system property to display phone number which I am using. I am beginner so only I don't know how to search for vendor also...
Comment: I want exact code to read phn number , anybody know about that ???
Answer: Ok, short answer: You can't get the phone number.
see this answer
The properties you have to read to get thinks like IMSI, MNC, MCC are completely vendor/model specific so unless you can't give these refer to this post
Concerning connectivity, I am not sure whether you mean availability of internet or wireless connectivity or something else. But in most cases the answer would be: You will have to check if the device vendor offers an SDK for that.
Comment: Is there no way to get phone number . Or like IMSI,MNC AND MCC as input is there is any way to display????
Comment: Ok then how to check whether device vendor offers SDK??


How does the view filter: Search: Search Terms works? Can I improve it?

Question: I have a View with and Exposed Filter: Search: Search Terms to filter the view result based in the keywords entered in this filter.
I works, but not as I expected.
Lets say I have a node with the title "The car, a good transport". Then:

if I enter the keyword: car the node is shown
if I enter the keywords: car a good the node is not shown
if I enter the keywords: good car  the node is not shown

Is this behaviour right? I need the node to be shown in all these situations
UPDATE: I see that there is already an open issue about this: http://drupal.org/node/1615438
Comment: do you want that node "The car, a good transport" as result, if you enter anyone of above 3?
Comment: yes that is what I need
Comment: If you want to search nodes based on title alone, you can try with Node:title instead of Search:search terms in filter section and select the operator as "Contains any word".
Comment: good idea, but I also need to search into the body of the node.
Comment: @Sathiya Based in your idea I added the node:title and node:body and get it working. Do you mind to move your comment as an answer so that I can accept it?
Answer: If you want to search nodes based on title alone, you can try with Node:title instead of Search:search terms in filter section and select the operator as "Contains any word"
Answer: Search API allows the indexing of multiple fields. This would allow you to search both title and body fields.
Answer: It's better to use operator "contains all words". Drupal search is no good, it's indexing everything but then you can't find anything..


Nested random effects and interaction terms in lme4

Question: I have a data set containing various vegetation and geomorphic variables sampled in 3 distances on both sides of 43 drainage ditches (Location). Roughly half of these ditches are occupied by a beaver, the other half is empty. Now I want to run a model with the binomial response variable Status ("beaver == 1" / "beaver == 0")
I'm struggling with the order and layout of the nested and interaction effects using glmer. So far I've got
fit <- glmer(Status ~ BankslopeScaled + Connectivity +
                      Canal_width + Distance:Food_crops +
                      Distance:Edible_trees +
                (1 | Distance/Side/Location),
              data, family=binomial(link="logit")

but I'm not sure if I still have pseudoreplication in my data or whether I correctly applied the formula in order to estimate the influence of the predictors in every distance on both sides in each Location.
Like, if food_crops in the 3rd distance on the left side is lower than edible_trees in the 2nd distance on the right side, then ...
I feel like there's something wrong with my random effects-term.
My output looks like this:
summary(fit)

Generalized linear mixed model fit by maximum likelihood (Laplace Approximation) ['glmerMod']
Family: binomial  ( logit )
Formula: Status ~ BankslopeScaled + Connectivity + Canal_width + Distance:Food_crops +
Distance:Edible_trees + (1 | Distance/Side/Location)
Data: Satz

     AIC      BIC   logLik deviance df.resid
   314.6    360.8   -144.3    288.6      245

Scaled residuals:
     Min       1Q   Median       3Q      Max
-2.18541 -0.71205  0.07243  0.82483  1.75303

Random effects:
 Groups                   Name        Variance  Std.Dev.
 Location:(Side:Distance) (Intercept) 2.834e-02 1.683e-01
 Side:Distance            (Intercept) 2.074e-10 1.440e-05
 Distance                 (Intercept) 2.085e-10 1.444e-05
 Number of obs: 258, groups:  Location:(Side:Distance), 258; Side:Distance, 6; Distance, 3

 Fixed effects:
                        Estimate Std. Error z value Pr(>|z|)
 (Intercept)            -2.86517    0.79747  -3.593 0.000327 ***
 BankslopeScaled         1.76475    0.62541   2.822 0.004776 **
 Connectivity            0.10394    0.02729   3.809 0.000140 ***
 Canal_width             0.19138    0.11089   1.726 0.084364 .
 Distance1:Food_crops    0.03667    0.09366   0.391 0.695441
 Distance2:Food_crops    0.10852    0.08996   1.206 0.227694
 Distance3:Food_crops    0.06303    0.08502   0.741 0.458510
 Distance1:Edible_trees  0.02273    0.01327   1.712 0.086818 .
 Distance2:Edible_trees -0.01750    0.02992  -0.585 0.558738
 Distance3:Edible_trees  0.09769    0.07986   1.223 0.221201
 ---
 Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

 [correlation of fixed effects snipped]

A point into the right direction is much appreciated!
Answer: A few things to keep in mind:

You probably shouldn't treat Distance as a random effect in any case (estimates of random effects with only 3 levels are very unreliable)
You already implicitly have the main effects of Distance in your model through the Distance:Food_crops and Distance:Edible_trees interactions.
... for both these reasons, you should leave Distance out of your random-effects specification: (1 | Distance:Side) + (1 | Distance:Side:Location) should work to include the two lower nested levels.
you will still probably find that the (1|Distance:Side) random effect has variance of effectively zero ... but you might as well leave it in.
Comment: Tanks a lot!!
The random effect variance of `(1|Distance:Side)` is indeed actually zero. And so is is `(1|Distance:Side:Location)`. That's peculiar... And another thing came to my mind: Most of the time, `Edible_trees` and `Food_crops` and other variables differed hugely on both `Sides` of one `Location`, regardless of their apparant promximity to each other. So, `Side` does not necessarily have to be included as a random effect after all, although I feel I somehow should tell the model that there are 2 `Sides` in each `Location`.
Is there a possibility to account for that?
Thanks again.
Comment: edit: `Side` should not be a random effect anyways. I just have to weave that in somehow.


Which type of microphone is optimal to use for the singing piano player?

Question: A piano player obviously cannot use a hand held microphone. From that I have seen in various shows, it is possible to use

a bigger microphone what is attached to the stand and positioned in front of the performer, or
a headset - like microphone that is much smaller and attached to the head of the
performer.

While a piano player needs no freedom to run around, the keyboard is rather wide so with the fixed microphone the head is unlikely to be always same distance from the mic. How much is this the issue? From the other side, headset microphones look somewhat unusual, optimized for wireless transfer that seems redundant and require converters even to plug into standard XLR jack with phantom power. Headset microphones seem taking a more narrow price range: they are not exactly cheap, however prices do not go a high as for the best free standing microphones.
Which of these two setups is considered optimal and more professional, are any know positive and negative sides?
For the simplicity, let's set recording of the piano sound aside. It probably needs separate additional microphones anyway, or (if digital) may need no any.
Answer: I'm not sharing yo's misgivings. I use a dynamic mic- Shure 58 (others are available!) just like a heck of a lot of other stage vocalists. It's on a boom stand sited on the opposite side of the keys to where I sit/stand.So it points directly at me, as a mic should. It doesn't pick up anything extraneous, and is only switched on when I'm singing. The stage piano is only as high as its keyboard - not an upright.
I used to use a headset mic wirelessly. Proper use of a mic means varying the distance between mouth and mic. Impossible with a headset.
Watch performers who sing and play piano, and the option as in my first paragraph would seem to be the favoured one. For t.v. work, they probably have a lavalier mic as well but it's not easy to spot.
Condenser mics, excellent as they are, are not particularly suited to stage work in comparison to dynamics.
Comment: Could you explain why "varying the distance" is required for singing? Varying the distance as needed looks  challenging if you also play outside the center of the keyboard at the same time. Where the song requires, vocalist should be able to vary the loudness of the own voice!
Comment: @h22 - True, but varying the distance from mouth to mic gives even more control and change of tone - dependent on the mic quality of course. A lot of singers just sing from around an inch or two from the mic, but good, experienced vocalists will use proximity to good advantage. As in singing loudly with the mic away sounds different from singing quietly with the mic close. Same overall volume, change of timbre.
Comment: I will second Tim's point on varying your proximity to the mic. Paradoxically, when seeking to convey an intimate tone, tight on the mic is best, singing at a low volume. Think of a Smokey Robinson ballad. When giving full voice, singing "legit", it is best to back away to avoid distorting the audio signal. Also, if you are blending with other voices, you will be listening closely to your monitor to be sure you are at just the right distance. The big adjustment for me when I started in bands was listening for my voice in the room instead of in my head/body, as I would with no support.
Comment: How far do you have the microphone? And as well, do you have sheet music in front of you? (Other than that, I +1'd your answer for sure!)
Comment: @yo' - obviously this works best for a hand-held mic, but I've worked with vocalists who work the mic on occasions from a foot away to close proximity. Sometimes I am an inch away, sometimes 3 or 4, whilst playing keys. Also depends on who else is harmonising, to get a balance.However , this is skewing off the point of the original question.            Rarely use sheets on stage!
Answer: The answer is: It depends. It depends on your expectations, on the type of music and type of playing you do, what type of piano have you got etc. I don't have so much experience and very likely someone else will come with a better answer, but I'll share my 2 cents worth.
You have the following options:

a headset: They can do a really good job and certainly meet the expectations of the freedom of movement. You can stand on your head on the piano stool and play and the microphone will catch your voice.
However: If you get a dynamic microphone, the sound will probably miss some "spark" since the diaphragm is small -- deep frequencies stretch it a lot and the response to the higher frequencies is then quite bad.
If you get a condenser, then it catches a lot of noise from all around you -- the piano keys, the sounds of your shirt sleeves moving on your arms, whatever. It's difficult to clean the sound, but the result can be good. However, you'll pay a lot for a good condenser.
dynamic microphone just in front of you: This is the setting I currently use, but it is far from being perfect. It is difficult to put the stand in such a position that it does not block your view. I mean, it will always block your view to some extent, and you have to experiment with the setup. I have the stand on the right from the keyboard, and the microphone on a long horizontal bar. I've been fiddling with the stand setup for a long long time to get the best out of it. Still, it blocks my view to a part of the keyboard and to a part of the sheet stand in front of me, depending on where my head is.
Second disadvantage is that you have to sing in the microphone from couple centimetres distance, and really sing into it, not close to it. Therefore when you play c'''', you move your shoulders to the right, stretch your right arm to the right, but keep your head turned left. Looks weird and feels weird at the beginning, but one can get used to it.
On the other hand, good dynamic microphone is not as expensive as a condenser headset.
stage condenser: That's the 3rd option. You sing in this type of microphone from larger distance and it catches the singing really well. However, I think it's usable only with electronic pianos since with grand or upright, you don't have any place where to put the microphone, and it'll catch the piano sound a lot. You can get either a very good one (which will probably look like this one), or some better-quality conference microphone (didn't find a good free image, just google "conference microphone"), which can do the job as well. Again, they are condensers, so they catch a lot of ambient sound.
I would not go for a lavalier (the one that goes on your shirt), I'm yet to see them produce reasonable output from singing.

Whatever you opt for (and especially if you stay with a standard dyna-mic), I recommend getting good monitoring of how it sounds, and as well getting a lot of practice with the setup before you go on air.
Comment: Why use an omni? Large-diaphragm cardioid is much better for voice _in particular_ when you want to sing from a bit further away.
Comment: @leftaroundabout That was indeed a mistake, I'm correcting it. Thanks for pointing out!
Answer: My tip - hope it's accurate as it seems to work for me
For dynamic mics go with a cardioid dynamic mic instead of a supercardioid mic - the reason is that supercardioid mics have a smaller pattern to pick up your voice which is great for a standing vocalist who wants to reject ambient noise and for feeback suppresion on stage. For a singing pianist who moves up and down the board, you will notice your voice is sometimes at different angles to the mic depending on where you are playing on the piano (it's just natural) so a cardioid has a wider pattern so it will pick up your voice slightly better as you shift while you are playing.  Just my 2 cents.
Answer: It's hard to put the condenser studio microphone (with stand) on a practical place.
If you have a acoustic piano, the best option is a dynamic microphone because the condenser microphone also picks up the sound of the piano.
Answer: The headset picks up all mouth sounds, including the ones you don't want people to hear, like a sneeze, a cough,  and the heavy breathing you didn't even know you make when you launch into a solo, burps, clearing the throat,  mumbles, and in my case sometimes the whiskers in my beard scratch the windscreen.  Other than that the headset follows well when you move around the keyboard, or lift your head and drop your head as you look back and forth from keys and controls to audience and sheets. I'm still looking for a mic that does not block my view...a keyboard player , not a guitar player nor a techie, needs to invent one.
Good luck.
Answer: For your singer, you ideally want to go condenser as they have better pickup in the lows and highs which give a very clean and "colourful" sound (I am going all in with the buzzwords). However, your big problem is the fact there is a piano blasting out sound right next to your singer, so go for a cardioid or other very directional microphone that is pointed directly at your singer. This should minimize noise pollution from the piano.


Chord III is rarely used, but Pachelbel's Canon in D has F#m

Question: I learned from a website https://www.mymusictheory.com/for-students/grade-6/170-a6-harmonizing-a-melody-i saying Chord III is rarely used.  But, does the well-known Canon in D use chord III as the progression is D → A → Bm → F#m → G → D → G → A?
Comment: In key D, F#m is labelled iii, rather than III - which is better labelled V/vi.
Comment: https://music.stackexchange.com/questions/127557/why-does-the-iii-chord-seem-to-be-usually-avoided-in-many-styles here is a similar question that discusses the scarcity of iii chords.
Comment: @gidds - V/vi key D would be the dominant of Bm, hence F#(maj). V by itself would be, as you say, chord A, but that's not what's quoted.
Comment: @Tim Isn't V/vi something slightly different? In this case, wouldn't it need an E? (I'm no expert, but it doesn't _sound_ like a type of A chord to me, and I can't see what function an A chord would fulfil there.)
Comment: "Rarely" is not the same as "never". Question closed. Next please.
Answer: Yes, it does. This sequence is one of the places where the III chord appears. Another place one might expect it is in consecutive first inversion chords.
For another example (but a debated one), see iii9 - I progression in Bach?
The website reads:

Chord III is rarely [emphasis original] used. It is possible (but not recommended) to use it in a major key (where it is a minor chord, e.g. E minor in the key of C major). It is NOT possible to use an augmented III in a minor key, (e.g. C-E-G# in the key of A minor), but sometimes a major chord III is possible (because it's the relative major chord).

In the context of explaining how to do an exam harmonization, this comes across as overstated. It's true that III is less common than other chords, and it's uncommon in harmonization exercises except when the exercise is intended to demonstrate a specific situation such as a sequence.
Aside from sequences, III will most often be found as a precursor to VI and occasionally as a substitute for I or as leading to II or IV.
But in general, it's a fair practice in harmonization exercises to make III the last chord you try.
There are lots of questions on this site regarding the III chord in various contexts, which you can find using the search "iii chord is:question".
Comment: I know what's intended, but it's odd that they use the phrase "It is NOT possible..." as if your instrument would break trying to play i → III+.  I suppose when I play Am followed by C+, I hear it as Am and E+... maybe it's not possible after all.
Answer: Yes, there is a iii chord in that Pachelbel's Canon progression.
It is a harmonic sequence called "falling thirds". It takes the two chord pattern I V and then sequences it by diatonically transposing it down a third to vi iii.
Some explanation of the "rare" label applied to iii should be given.
It is important to distinguish between the tonal chord I IV V and the modal chords ii iii vi and understand them in terms of basic harmonic function.

I is the tonic.
IV is the subdominant and ii is usually described as having subdominant or pre-dominant function.
V is the dominant and viio is usually described as have dominant function.

The list above covers chord I ii IV V viio and leaves out only iii and vi.
iii and vi are the principle modal chords and provide the major/minor flavor of a key.
iii and vi don't fulfill any of the functions: tonic, subdominant, dominant. We could say that the use of iii and vi is for modal color rather than harmonic function. vi is fairly common because of its use in deceptive progressions like V vi.
That leaves iii the odd chord out. That makes it sort of "rare." A likely time to hear iii is in a harmonic sequence, like the falling thirds in Pachelbel's Canon.
Don't misunderstand the general description of "rare" to mean "never used" or something like that.
Another way to think of the "rarity" is via the fundamental harmonic progression of roots by descending fifths.
We start with the roots by fifth descent to the tonic ii V I and add to that the two alternative chords (ii or IV) (V or viio) I, which gives us 5 of the 7 diatonic triads.
Add one more descending fifth to that... vi (ii or IV) (V or viio) I and we could say that vi is fairly "remote" from I.
Add one more descending fifth... iii vi (ii or IV) (V or viio) I and we could say that iii is the most "remote" from I.
Consider "remote" as synonymous with "rare" and this give us a sense of why iii is "rare."
Comment: You're the first I've heard describe I-IV-V as "tonal" chords and ii-iii-vi as "modal" chords. That's a really helpful distinction ... which I am now stealing.
Comment: "Don't misunderstand the general description of "rare" to mean "never used" or something like that."  A good point.  Teachers wouldn't call it "rare" if it were in fact never used, of course, but students somehow frequently confuse the two nonetheless.
Answer:
Chord III is rarely used. But, does the well-known Canon in D use chord III as the progression is D → A → Bm → F#m → G → D → G → A?

Well, yes, but only for part of the piece.  For much of the piece, the fourth chord in the progression isn't F♯m but rather D/F♯ (and in three instances it's arguably D7/F♯ (V[6/5]/IV) with a C natural passing tone from the D to the B of the next chord).  You might look at this as additional evidence in favor of the proposition that the iii chord is rare.
Because of this, iii appears in the piece with a frequency of around 1/16, with the full table of frequencies being roughly (combining I and V7/IV, and ignoring for now the difference between ii6 and IV because I haven't counted them yet):
I:   5/16
iii: 1/16
IV:  1/4
V:   1/4
vi:  1/8

So even in this unrepresentative sample, the iii chord is less prevalent than one would at first expect.


Find roots or splitting field of a polynomial given its Galois group

Question: A well known result from Galois theory is that the roots of a polynomial can be expressed by a formula using field operations and taking $k$-th roots if and only if the Galois group of the polynomial is solvable.
How would you actually find such a formula given a solution of the Galois group?
For example I tried to find a root of the polynomial $f(x) = x^3-x-1$ (I know that formulae exist for the roots of polynomials with degree $< 5$, but I am hoping for a more general approach).
Observing that $f$ is irreducible, and that $f(x)$ has only one real root, it is not difficult to show that $Gal(E/\mathbb{Q}) \simeq S_3$ (where $E$ is the splitting field of $f$ ), because it is a subgroup of $S_3$ and it has at subgroup of order 2 (complex conjugation) and it acts transitively on the set of roots. Since $S_3$ is solvable we know that $E$ is contained in a radical extension of $\mathbb{Q}$.
How would you go from here to find the roots? Is there a general approach or some tricks that can be used? I can't just follow the proof of the theorem that guarantees the existence of a radical extension, because i would need to know the automorphisms.
Answer: I seem to be giving lots of answers that depend on very special properties of the supplied example. Here's an argument, tailored to your polynomial $f(x)=x^3-x-1$. Not the general method you were hoping for at all.
First set $\alpha$ to ba a root of your polynomial, which we all know is irreducible over $\Bbb Q$. It's not too hard to calculate the discriminant of the ring $\Bbb Z[\alpha]$ as the norm down to $\Bbb Q$ of $f'(\alpha)=3\alpha^2-1$; this number is $23$, surprisingly small for a cubic extension. The fact that it's square-free implies that $\Bbb Z[\alpha]$ is the ring of integers in the field $k=\Bbb Q(\alpha)$.
Our field $k$ clearly is not totally real, since $f$ has only one real root. So in the jargon of algebraic number theory, $r_1=r_2=1$, one real and one (pair of) complex embedding(s). We can apply the Minkowski Bound
$$
M_k=\sqrt{|\Delta_k|}\left(\frac4\pi\right)^{r_2}\frac{n!}{n^n}\,,
$$
which for $n=3$ gives a bound less than $2$, so that $\Bbb Z[\alpha]$ is automatically a principal ideal domain.
Let's factor the number $23$ there: we certainly know that it's not prime, since $23$ is ramified.
Now, we already know a number of norm $23$, necessarily a prime divisor of the integer $23$, it's $3\alpha^2-1$, and indeed $23/(3\alpha^2-1)=4 + 9\alpha - 6\alpha^2$. But better than that, $23/(3\alpha^2-1)^2=3\alpha^2-4$. This number has norm $23$ (because the norm of $23$ itself is $23^3$). So we've found the complete factorization of $23$.
Now let's look more closely at $f(x)=(x-\alpha)g(x)$, for a polynomial $g$ that we can discover by Euclidean Division to be $g(x)=x^2+\alpha x+\alpha^2-1$. And the roots of $g$ are the other roots of $f$; the Quadratic Formula tells you what they are, and the discriminant of $g$ is $\alpha^2-4(\alpha^2-1)=4-3\alpha^2$. which we already know as $-23/(3\alpha^2-1)^2$. Going back to the Quadratic Formula, our other roots are
$$
\rho,\rho'=\frac{\alpha\pm\sqrt\delta}2\>,\>\delta=\frac{-23}{(3\alpha^2-1)^2}\>,\>\sqrt\delta=\frac{\sqrt{-23}}{3\alpha^2-1}\>.
$$
And that gives you your roots of this one very special cubic polynomial in terms of one root $\alpha$ and $\sqrt{-23}$.
Comment: I left out square root (of discriminant) in the fmla for Mink bound. Corrected
Answer: I also came across same question just few months before, and while going through books on Galois Theory, not clear answer found to me (at that time) except some simple illustrations made in the book Galois Theory- Ian Stewart. This may not be a full answer to your question, but the last paragraph quoted here would say this it may be difficult to obtain the roots by Galois Theory.

8.3 How to Use the Galois Group
As an example, consider the polynomial equation
  $f(t)=t^4−4t^2−5 = 0$ which ... factorizes as $(t^2 + 1)(t^2−5) = 0$, so there are four roots $t = i, −i, \sqrt{5}, -\sqrt{5}$.
Pretend for a moment that we don't know the explicit zeros $i, −i, \sqrt{5}, -\sqrt{5}$ but that we do know the Galois group G. In fact, consider any quartic polynomial $g(t)$ with the same Galois group as our example $f(t)$ above [isomorphic to $Z_2\times Z_2$]; that way we cannot possibly
  know the zeros explicitly.
Let them be $\alpha,\beta,\gamma,\delta$. Consider three subfields of $\mathbb{C}$  related to $\alpha,\beta,\gamma,\delta$, namely
  $$ \mathbb{Q} \subseteq \mathbb{Q}(\gamma,\delta) \subseteq \mathbb{Q}(\alpha,\beta,\gamma,\delta)$$
  Let $H = \{I, R=(\alpha \beta)(\gamma)(\delta)\} \subseteq G$. Assume that we also know the following two facts:
(1) The numbers fixed by H are precisely those in $\mathbb{Q}(\gamma,\delta)$.
(2) The numbers fixed by G are precisely those in $\mathbb{Q}$.
Then we can work out how to solve the quartic equation $g(t)=0$, as follows.
  The numbers $\alpha+\beta$ and $\alpha\beta$ are obviously both fixed by $H$. By fact (1) they lie in $\mathbb{Q}(\gamma,\delta)$. But since
  $$(t-\alpha)(t-\beta)=t^2-(\alpha+\beta)t+\alpha\beta,$$
  this means that $\alpha$ and $\beta$ satisfy a quadratic equation whose coefficients are in $\mathbb{Q}(\gamma,\delta)$. That is, we can use the formula for solving a quadratic to express $\alpha,\beta$
  in terms of rational functions of $\gamma,\delta$, together with nothing worse than square roots. Thus we obtain $\alpha$, $\beta$ as radical expressions in $\gamma,\delta$.
But we can repeat the trick to find $\gamma,\delta$. The numbers $\gamma+\delta$ and $\gamma\delta$ are fixed by the whole of $G$: they are clearly fixed by $R$, and also by $S=(\alpha)(\beta)(\gamma\delta)$, and these generate $G$. Therefore $\gamma+\delta$ and $\gamma\delta$ belong to $\mathbb{Q}$ by fact (2) above. Therefore $\gamma$ and $\delta$ satisfy
  a quadratic equation over $\mathbb{Q}$, so they are given by radical expressions in rational numbers. Plugging these into the formulas for $\alpha$ and $\gamma$ we find that all four zeros are radical expressions in rational numbers.
We have not found the formulas explicitly. But we have shown that certain information about the Galois group necessarily implies that they exist. Given more information, we can finish the job completely.


AWS EC2: (Connection refused) while connecting to upstream

Question: Error:

2022/02/25 05:25:23 [error] 16292#16292: *1 connect() failed (111:
Connection refused) while connecting to upstream, client: 172.31.9.17,
server: , request: "GET / HTTP/1.1", upstream:
"http://127.0.0.1:5000/", host: "172.21.11.88"

It's my first time uploading a fullstack JAR file in AWS EC2. Jar file contains Thymleaf web pages and the main java codes.
I've also done setting my RDS in AWS as well.I changed the security group to 'allow access' anywhere so I can connect to it on my local MySQL Workbench. By this, Im done setting up my SQL tables.
So I uploaded the JAR file. The status went from Healthy to Severe.
When I access the URL of my app I get this:

application.properties
<code>server.port=5000
</code>
AWS Security Group

Inbound Rules

Health Monitoring

UPDATE:
Here's where Im at

Is this what's causing my errors?
Comment: You have to verify that your application works on port 5000
Comment: do you happen to know where I could specify this port 5000?
Comment: @Marcin yes, nothing helps.Im new to AWS and for me this is basic stuff and people on SO dont seem to know about it which is funny because this is beginner level.
Answer: By default EB expects your app to listen on port 5000. From docs:

By default, Elastic Beanstalk configures the nginx proxy to forward requests to your application on port 5000. You can override the default port by setting the PORT environment property to the port on which your main application listens.
Comment: yeh I specifed my applicaiton.properties in springboot to use
server.port=5000 , but still doesnt work . . pls refer to updated question
Comment: @JoonaRitva Then you have to verify that you application is actually working. SSH to the EB instance and `curl` from localhost.
Comment: how do i ' SSH to the EB instance and curl from localhost'
Comment: I was reading the docs, do I need an EC2 key pair?
Comment: @JoonaRitva You can connect use AWS console with web ssh client.


Does there exist a complex function that takes one complex number to another?

Question: Is there any meaningful relationship between the values
$$z_1 = a \cos(x) + i b \sin(x), z_2 = b \cos(x) - i a \sin(x) $$
where $a,b,x$ are real numbers? Basically, $z_1$ lies on the ellipse $\frac{x^2}{a^2} + \frac{y^2}{b^2}  = 1$ while $z_2$ lies on the corresponding point of that ellipse turned 90 degrees. However, I don't know how to come up with a bijective function that turns $z_1$ in $z_2$.
Answer: Thre is no such relationship, at least not if $a, b, x$ are all allowed to vary simultaneously through all real values.
For example,
\begin{gather*}
\text{if } (a, b, x) = \left(1, 1, \frac{\pi}{4}\right), \text{ then } z_1 = \frac{1+i}{\sqrt{2}} \text{ and } z_2 = \frac{1-i}{\sqrt{2}}, \text{ but} \\
\text{if } (a, b, x) = \left(1, -1, -\frac{\pi}{4}\right), \text{ then } z_1 = \frac{1+i}{\sqrt{2}} \text{ and } z_2 = \frac{-1+i}{\sqrt{2}},
\end{gather*}
so there would have to be two different values of $z_2$ corresponding to the same value of $z_1$.
I'll see if I can add a counterexample where $a$ and $b$ are both strictly positive, which I imagine is what you had in mind.
I think this is OK:
\begin{gather*}
\text{if } (a, b, x) = \left(2, 1, \cos^{-1}\left(\frac{1}{\sqrt{5}}\right)\right), \text{ then } z_1 = \frac{2+2i}{\sqrt{5}} \text{ and } z_2 = \frac{1-4i}{\sqrt{5}}, \text{ but} \\
\text{if } (a, b, x) = \left(1, 2, \cos^{-1}\left(\frac{2}{\sqrt{5}}\right)\right), \text{ then } z_1 = \frac{2+2i}{\sqrt{5}} \text{ and } z_2 = \frac{4-i}{\sqrt{5}}.
\end{gather*}
Comment: Sorry for that. After I accepted it I reloaded the page, which didn't show the answer as accepted, so I clicked the tick again, which must have unaccepted the answer...
Comment: Yes, I am indeed looking for $a,b$ both strictly positive (in order for the ellipse to exist). The only correspondence I found is that if you fix $a,b$ and set $f(x) = a \cos(x) + ib\sin(x)$, then the other value is $ -if(\frac{\pi}{2} - x)$.
Comment: Sorry, I was only struck by a bolt of common sense after I had posted!
Comment: The revised answer was accepted, but then unaccepted - have I made a mistake?
Comment: Yes, I've often found the same thing: that when you reload a page, you get an older version of it. I'll never understand these new-fangled computer thingies. :)


How do you create an alias in Cocoa? Is a symlink good enough?

Question: I couldn't find a convenient way to create an alias, so I went with a symlink. I'm worried that that might not be good enough. Maybe the icon doesn't show on some versions of OS X or something like that.
[[NSFileManager defaultManager] createSymbolicLinkAtPath:aliasPath withDestinationPath:destPath error:nil];

Is this sort of thing the best I can do?
http://www.danandcheryl.com/2009/08/how-create-alias-programmatically
Answer: The answer depends on if you're using OS X 10.5 or 10.6. In 10.6, the old AliasManger has been replaced by NSURL's bookmark data. To create an alias, given an NSURL instance:
NSURL *url = [NSURL fileURLWithPath:pathToAliasTarget];
NSError *err = nil;
NSData *bookmarkData = [url bookmarkDataWithOptions: NSURLBookmarkCreationSuitableForBookmarkFile includingResourceValuesForKeys:nil relativeToURL:nil error:&err];

if(bookmarkData == nil) {
  //handle NSError in err
} else {
  if(![NSURL writeBookmarkData:bookmarkData toURL:aliasFileURL options:NSURLBookmarkCreationSuitableForBookmarkFile error:&err]) {
    //handle NSError in err
  }
}

As Peter Hosey points out, the bookmark data written using the NSURL API is not compatible with AliasManager routines. If you must support OS X < 10.6, you'll have to use the Carbon AliasManager API directly, or one of the Objective-C wrappers. I like Wolf Renstch's branch of BDAlias, available here.
Comment: Bookmark data is not an alias. If you pass that data or a bookmark file to the Alias Manager, the Alias Manager will turn up its nose at it.
Comment: (Which implies that if you take a bookmark file to a machine running Leopard or earlier, it won't work.)
Comment: @Peter, I wasn't aware that bookmark data wasn't interchangeable with AliasManager aliases. Thanks for the pointer. Feel free to edit the post appropriately. I guess this makes the case for `BDAlias` or something similar much stronger if you have to support OS X < 10.6.
Answer: I know it's too far now I'm posing this answer but it may help someone,
You can also do this like,
Note, it's creating hard link as @zekel commented
To create them, take a look at linkItemAtURL:toURL:error: and linkItemAtPath:toPath:error: in NSFileManager.
Comment: @zekel, Yeah! That's right! In my requirement, I'd to make hard link, I am removing it once my task gets done!
Comment: The docs say that will create a hard link which will behave much differently from an alias.
Answer: To create an alias, take a look at NDAlias, at http://www.cocoadev.com/index.pl?NDAlias
Comment: That looks good. Unfortunately, I can't use it for above me licensing reasons, but fortunately symlinks appear good enough for my case.
Answer: Hi You can using my NSTask, Example:
NSArray *arr = NSSearchPathForDirectoriesInDomains(NSDesktopDirectory, NSUserDomainMask, YES);
[NSTask launchedTaskWithLaunchPath:@"/bin/ln" arguments:[NSArray arrayWithObjects:@"-s", [[NSBundle mainBundle] bundlePath], [arr objectAtIndex:0], nil]];

Comment: Use the simpler `- [NSFileManager createSymbolicLinkAtPath:withDestinationPath:error:]` instead; there's no need to launch a separate executable just to create a symlink.


How to keep track of the return data from entry widgets in tkinter

Question: I create 2 entry boxes and user will type the data in. I bind the entry box with Tab key. After entry1 is filled then user presses Tab key to move to the next entry box (entry2). I want the data in entry1 will be checked against min and max those are set specifically for entry box 1 and 2 as soon as the Tab key is pressed. If entry1 is fail then the msg_box will be pop up. If all pass then the data will be sent to the database. How to determine that the data after Tab key is pressed is belong to which entry box so that it can be checked? cause user after press tab can go back to edit the data.
Here is my simple code:
import tkinter
from tkinter import StringVar

main_wd = tkinter.Tk()
my_var1 = StringVar()
my_var2 = StringVar()

def enter(event, var):
    print(var.get())

entry1 = tkinter.Entry(main_wd, textvariable = my_var1)
entry1.pack(padx = 5, pady = 5)
entry1.bind('<Tab>', lambda event: enter(event, var=my_var1))

entry2 = tkinter.Entry(main_wd, textvariable = my_var2)
entry2.pack(padx = 5, pady = 5)
entry2.bind('<Tab>', lambda event: enter(event, var=my_var2))
main_wd.mainloop()

Comment: I don't know data printed out belong to which entry box. In the code if you press Tab the data will be printed out. And you press Tab again the data from entry 2 will be printed out. That is easy. Now if you have the tolerance for entry 1 is +- 0.005 and entry 2 is +-0.003 So after entry 1 is filled user will press Tap key. The enter function will return the data for entry 1 and it will be checked against the tolerance 1. If pass data will change to green, fail red. The process will be the same for entry 2. So if after filling up two entry boxes the user goes back and edit entry 1 press Tab?
Comment: Let say they edit entry box 1 then press Tab. How can I get that data to check with tolerance 1?
Comment: Sorry cause the comment limit letters..
Comment: I don't understand what your end goal is? What is it about your code that does not work?
Comment: `Entry` widgets don't return the text you write in them. You have to either trace it, connect a variable, or manually retrieve it.
Comment: Whats wrong with the code you gave?
Comment: I don't know data printed out belong to which entry box. In the code if you press Tab the data will be printed out. And you press Tab again the data from entry 2 will be printed out. That is easy.
Comment: What else do you want?
Answer: You can pass the limits into your function the same way you pass the stringvar in.
import tkinter
from tkinter import StringVar

main_wd = tkinter.Tk()
my_var1 = StringVar()
my_var2 = StringVar()

def enter(event, var, start, end):
    print(var.get())
    if int(var.get()) > end:
        print('var is too big!')
    elif int(var.get()) < start:
        print('var is too small!')

entry1 = tkinter.Entry(main_wd, textvariable = my_var1)
entry1.pack(padx = 5, pady = 5)
entry1.bind('<Tab>', lambda event: enter(event, var=my_var1, start=5, end=10))

entry2 = tkinter.Entry(main_wd, textvariable = my_var2)
entry2.pack(padx = 5, pady = 5)
entry2.bind('<Tab>', lambda event: enter(event, var=my_var2, start=100, end=200))
main_wd.mainloop()

However this really sounds like a good place to use a subclass:
import tkinter

class VanN(tkinter.Entry):
    def __init__(self, master=None, start=None, end=None, **kwargs):
        self.start = start
        self.end = end
        super().__init__(master, **kwargs)
        self.var = tkinter.StringVar()
        self.config(textvariable=self.var)
        self.bind('<Tab>', self.enter)

    def enter(self, event=None):
        value = int(self.var.get())
        print(value)
        if self.end is not None and value > self.end:
            print('var is too big!')
        elif self.start is not None and value < self.start:
            print('var is too small!')

main_wd = tkinter.Tk()

entry1 = VanN(main_wd, start=5, end=10)
entry1.pack(padx = 5, pady = 5)

entry2 = VanN(main_wd, start=100, end=200)
entry2.pack(padx = 5, pady = 5)

main_wd.mainloop()

Comment: I think OP wants to set focus back to the wrong entry too.
Comment: Thank you so much Novel. That is what I need. Now I know where to set the data range (tolerance) in.
Comment: It is not clear to me why not using validate command when focusing out?
Comment: @FlavioMoraes the validate command would function differently than what OP described, not allowing the entry instead of pop up error. However it may work for OP so I encourage you to add an answer to show that.
Comment: Hi Novel, I really like the class that you've created. I can use a loop to create a series entry boxes easily. But if I want to delete all data in all entry boxes what parameters and how to pass them into the delete function. (let say I create a button RESET and a delete function). Thanks
Comment: I found  a solution. :)
Answer: As suggested by @Novel I'm adding a new answer to show you how to do the same thing using validatecommand instead of binding an event to the Entry. The tkinter Entry validatecommand attribute defines a method to call to check if content is valid. In your case we also want to define validate as focusout so the checking method will be called when you click outside the Entry or press TAB. It is important to know that the method must return True or False if you accept or reject the input.
Bellow is the same answer of Novel but using validatecommand instead. I also added a try/finally in case user leave the entry without type anything:
import tkinter
from tkinter import StringVar

main_wd = tkinter.Tk()
my_var1 = StringVar()
my_var2 = StringVar()

def enter(var, start, end):
    print(var.get())
    try:
        if int(var.get()) > end:
            print('var is too big!')
            return False
        elif int(var.get()) < start:
            print('var is too small!')
            return False
    finally:
        return True

entry1 = tkinter.Entry(main_wd, textvariable = my_var1, validate='focusout', validatecommand=lambda: enter(my_var1, 5, 10))
entry1.pack(padx = 5, pady = 5)

entry2 = tkinter.Entry(main_wd, textvariable = my_var2, validate='focusout', validatecommand=lambda: enter(my_var2, 100, 200))
entry2.pack(padx = 5, pady = 5)

main_wd.mainloop()


How to use Drupal in the cloud with on demand instances

Question: Services such as Rightscale do lots of things to help mange unpredictable traffic and bring more servers online when traffic spikes.
Is it possible to use Drupal with services such as this?
While Drupal can be set up for a number of configurations, is it possible to set it up so the configuration is flexible.
What do you need to do to make sure it works?
Assuming that you can bring on demand instances online, what do you need to do to make sure that Drupal will work in this situation. What do you have to do?
What is the optimal setup?
Once you have done what you have to do, what should you do to ensure that you can scale to more servers seamlessly. What is the best configuration in terms of number of servers. How many caching servers should you bring on line for each web server. Should you scale each tier independently?
edit
Edit to clarify that this is to do with the implications of on demand scaling for a Drupal site.
Comment: I would disagree, it is very Drupal specific.
Comment: this is probably a question better placed on serverfault
Answer: Rackspace put together a pretty decent start to this subject here which uses a couple of specific technologies which you might not want to use, but the principles are the same.
You might also need to look at Mysql clustering, but only really if you're hitting serious traffic levels
Comment: I have a webapp at Rackspace in development, and we are planning pretty much what you see in the figure from Ewan's link above. I have just started working on the scaling logic, and the biggest bang for the buck is having a dedicated DB server. We're also looking at Panethon, having had a beta peek: https://getpantheon.com/platform Panethon is a "managed scaling Drupal cloud infrastructure as a service".
Comment: @Ewan, the "here" link is not available anymore.
Answer: if the webservice supports php5 and mysql then there should be no problems with running drupal in the cloud. that said you may want to consider looking at the pressflow fork of drupal if you are looking for serious scaling
Comment: Running in the cloud is fine, it is on demand scaling that I am interested in, so adding new servers as demand rises.