One content type two different node--MYCONTENTTYPE.tpl.php for content style

Question: I've got one content type, in the teaser I've limited the chars lenght for title and body through a script in the file .tpl.php
<?php $limited_title = (substr($title,0,60));
    print $limited_title."..."; ?>

For the same content type I've got two views, both in "content" mode with a different filter criteria.
What I wanna do is to have one view showing 60 chars of the title and the other view showing 100 chars of the title. Is it possible to create two different node.tpl.php like we do with the view giving the name of the page? like node--mycontentType--page-1.tpl.php.
if it's not, what the best way to get the result I want?
No javascript please.
Thanks in advance.
Answer: I think the best way is to change this by clicking the title field in the views page and using the "Trim this field to a maximum length" option under "Rewrite results". You can set it to 60 for the first view and 100 for the other.
Comment: I'm not using a view with fields. I could change it from the content type page -> display fields, but it's going to affect both.


Problemas com data PHP

Question: Estou usando a seguinte função para me retornar a data corretamente do MySQL para o formato brasileiro:
function FormatBR($data){
    $date = date_create($data);
    $date = date_format($date, 'd/m/Y');
    return $date;
}

Mas o retorno está assim:

Alguem sabe o que está acontecendo? Ou se estou fazendo da forma errada?
Grato!
Onde crio o JSON:
 if (isset($_GET['id'])){
                $id = trim($_GET['id']);
                $sql = "SELECT p.sequencia       codigo,
                            p.nome_completo   nome,
                            c.cpf             cpf,
                            c.rg                 rg,
                            c.data_nascimento data,
                            t.celular_1       celular_1,
                            t.celular_2       celular_2,
                            t.celular_3       celular_3,
                            t.telefone_1      telefone_1,
                            t.telefone_2      telefone_2,
                            t.telefone_3      telefone_3,
                            t.status          status_telefone,
                            e.email_1         email_1,
                            e.email_2         email_2,
                            e.status          status_email,
                            d.cep             cep,
                            d.rua             endereco,
                            d.numero          numero,
                            d.bairro          bairro,
                            d.complemento     complemento,
                            d.cidade          cidade,
                            d.estado          estado,
                            d.status          status_end
                        FROM pessoas     p,
                            clientes     c,
                            telefones    t,
                            emails       e,
                            enderecos    d
                        WHERE t.cod_pessoa = p.sequencia
                        AND c.cod_pessoa = p.sequencia
                        AND e.cod_pessoa = p.sequencia
                        AND d.cod_pessoa = p.sequencia
                        AND p.sequencia = $id";
                $exec = mysqli_query($link, $sql);
                if ($exec){
                    while ($clientes = mysqli_fetch_assoc($exec)){
                        $convert = new convertData();
                        $data_nascimento = $convert->FormatBR($clientes['data']);
                        $vetor[] = array('Codigo' => $clientes['codigo'],
                                        'Nome' => $clientes['nome'],
                                        'CPF' => $clientes['cpf'],
                                        'RG' => $clientes['rg'],
                                        'Data_Nacimento' => $data_nascimento,
                                        'Celular_1' => $clientes['celular_1'],
                                        'Celular_2' => $clientes['celular_2'],
                                        'Celular_3' => $clientes['celular_3'],
                                        'Telefone_1' => $clientes['telefone_1'],
                                        'Telefone_2' => $clientes['telefone_2'],
                                        'Telefone_3' => $clientes['telefone_3'],
                                        'Status_telefone' => $clientes['status_telefone'],
                                        'email_1' => $clientes['email_1'],
                                        'email_2' => $clientes['email_2'],
                                        'status_email' => $clientes['status_email'],
                                        'cep' => $clientes['cep'],
                                        'endereco' => $clientes['endereco'],
                                        'numero' => $clientes['numero'],
                                        'bairro' => $clientes['bairro'],
                                        'complemento' => $clientes['complemento'],
                                        'estado' => $clientes['estado'],
                                        'status_end' => $clientes['status_end']);
                    }
                }
                echo(json_encode($vetor));

Comment: 1995-06-15 (formato US)
Comment: o problema é que ela está me retornando com duas barras \/ (simples e invertida) desta forma: (15\/06\/1995). Sim é um json o retorno. Espero a data no formato BR (15/06/1995)
Comment: Sei que existe a forma de converter isso direto no SQL, mas acaba deixando a instrução mais lenta..
Answer: Ele está retornando o formato "interpretado" pelo json, use o json_decode para manipular:
$data = ["Data_Nascimento" => "15/06/1995"];
$data = json_encode($data);
var_dump($data);  // Veja como fica como no exemplo que demonstrou
$dataCorreta = json_decode($data);
echo '
Data Formatada: '.$dataCorreta->Data_Nascimento;

Comment: Até deu certo, porem, eu estou usando JQUERY.. então no caso teria que usar o json.parse?
Comment: Isso mesmo use o JSON.parse($date).Data_Nascimento

Problemas com data PHP


Constructing confidence interval with limit result involving population parameter

Question: $X\sim B(n,p), \hat{p}_{n} = \frac{X}{n}$
I am trying to invert the following statement to obtain a confidence interval.
$P(-1.96 \leq \frac{\sqrt n(\hat{p}_n-p)}{\sqrt{p(1-p)}} \leq 1.96)=0.95$
Not sure how to center the following inequality at $p$, while making sure the bounds do not depend on $p$.
Help here would be appreciated.
Answer: You basically need to solve a quadratic for $p$:  let $$\frac{\sqrt{n}(\hat p_n - p)}{\sqrt{p(1-p)}} = z_{\alpha/2}.$$  Squaring everything gives $$\frac{n(\hat p_n - p)^2}{p(1-p)} = z_{\alpha/2}^2$$ and clearing denominators and collecting like terms in $p$ gives $$\begin{align}
0 &= n(\hat p_n - p)^2 - z_{\alpha/2}^2 p(1-p) \\
&= (n+z_{\alpha/2}^2)p^2 - (2n \hat p_n + z_{\alpha/2}^2) p + n\hat p_n^2.
\end{align}$$
Then the quadratic formula yields
$$\begin{align}p &= \frac{(2n\hat p_n + z_{\alpha/2}^2) + \sqrt{(2n \hat p_n + z_{\alpha/2}^2)^2 - 4(n + z_{\alpha/2}^2)(n \hat p_n^2)}}{2(n + z_{\alpha/2}^2)}  \\
&= \frac{1}{1+z_{\alpha/2}^2/n}\left( \hat p_n + \frac{z_{\alpha/2}^2}{2n} + z_{\alpha/2} \sqrt{\frac{\hat p_n (1 - \hat p_n)}{n} + \frac{z_{\alpha/2}^2}{4n^2} } \right)
\end{align}$$  This furnishes the upper bound of the confidence interval; the lower bound is the negative root of the quadratic since if we replace $z_{\alpha/2}$ with $-z_{\alpha/2}$, the only term that changes is the one with the square root.
The above is the derivation of the Wilson score interval for a binomial parameter.  The form written at the end is used to illustrate the differences from the Wald interval, $$\hat p_n \pm z_{\alpha/2} \sqrt{\frac{\hat p_n (1 - \hat p_n)}{n}},$$ which arises from the solution of the inequality $$-z_{\alpha/2} < \frac{\hat p_n - p}{\sqrt{\hat p_n (1 - \hat p_n)/n}} < z_{\alpha/2},$$ in which the denominator uses the point estimate $\hat p_n$ rather than the parameter $p$.
Comment: Ahh I see. Was caught up a bit with the interval notation and never set it equal to the z-score. I see it now though. Thank you!


Finding An Inverse Of K-Cycle

Question: To find an inverse of k-cycle for example $(1,2,4,6,3)$ we write it from right to left $(3,6,4,2,1)$ but is it the right or left inverse? as $S_n$ is not abelian  for $n\leq 3$
Comment: In every group, the right and left inverse are the same thing. This follows from associativity and the uniqueness of the identity.
Answer: $$(12463)(36421)=(1)(2)(3)(4)(5)(6)=I$$
$$(36421)(12463)=(1)(2)(3)(4)(5)(6)=I$$
These are the same and it is a right and left inverse. Note that if a group is not Abelian, it does not mean that $a\not=b\ \forall\ a,b\in S$. It just means that $a=b\ \forall\ a,b\in S$ is not true for some $a,b\in S$.
Comment: Well, since it is a group, the right inverse is the same as the left inverse.  The Symmetric Groups are well defined groups. For another algebraic structure, you could just see which value of $b$ solves $ab=e$ but does not solve $ba=e$.
Comment: I understand, so in this case we have left inverse=right inverse, so in general if I want the left inverse or the right inverse how do I find them?

Finding An Inverse Of K-Cycle


Elasticsearch high RSS memory consumption

Question: I am seeing too high memory consumption in my elasticsearch instance.
I set ES_HEAP_SIZE=4g.
The starting command for ES starts with:
/usr/lib/jvm/java-8-oracle/jre/bin/java -Xms4g -Xmx4g
So far so good.
But I am seeing more than 7GB RSS memory consumption.
Here is /proc/status output: http://pastebin.com/mXW6Vnfc
But when I run jstat -gc everything looks normal, I see around 3.7GB in OC and 270 MB in EC (http://pastebin.com/c84urvSM).
This is sorted pmap output: http://pastebin.com/GG92Ercr
Do you have any idea, why the memory consumption is so high?
Also, ES is run on virtual server under OpenVZ.
Comment: `I am seeing too high memory consumption in my elasticsearch instance` Why is it too high? What is normal? How do you know it is too high? Based on what documentation have you concluded that?
Comment: usually this is garbage collection issue https://www.elastic.co/guide/en/elasticsearch/guide/current/_don_8217_t_touch_these_settings.html
Comment: If I set the max consumption to 4GB of heap space, I expect, that in reality would be at most 5 GB of real memory. Reality is, that it is 7 GB and still going up.
Answer: The issue is probably in the JVM and if you launch multiple instances of ES, look into it with Java Mission Control http://www.oracle.com/technetwork/java/javaseproducts/mission-control/java-mission-control-1998576.html or jconsole https://docs.oracle.com/javase/8/docs/technotes/guides/management/jconsole.html. This will give you an idea why it's consuming so much memory.
Please keep in mind that the JVM uses GC and other proceses outside of the heap memory. Start ES with -xms 1024 then leave it grow. Also as far as I remember, java takes -xms,-xmx arguments as MB no as GB, just to be on the safe side convert everything to MB.
Answer: Use jvisualvm to see heap consumption (and much more), it's the official debugging and profiling tool for java, installed by default with java.
Attach it to the elasticsearch process, check that the -Xmx and -Xms flags have the right value and look at the graphs. It's very straightforward.
The java process should have 4 GB of heap at all times because you set both min and max heap. It should consume 4-4.5 GB on the system because there is some overhead to manage the heap that is not accounted as part of the heap.
Anyway, java doesn't allow the process to use more heap than configured (it would kill the process if it tried to). It's likely that there is something else using the memory on your computer. Use top or htop to have a look at other running processes.
Comment: When I looked into jvisualvm I only see, that the max heap size is 4GB, 3.5 GB is being used and that's all. There is like no explanation about other 3GBs used over that.
Comment: Also looks like mbeans might have some more info, will check into that when leak happens again.
Comment: Then it's not elasticsearch that is using the rest of the memory. There is something else.
Comment: The elasticsearch process is using 7GB, that's what every system tool says.
Answer: What you set with ES_HEAP_SIZE is the Java heap size available to the program being run on the JVM. On top of that JVM has its own overhead, there's overhead from the GC (its data is not accounted for as Java heap) and each running thread needs memory for its stack (how many threads do you have and what's the stack size?). ElasticSearch probably doesn't use off-heap storage itself, but it's always a thing to look out for.
I've heard of cases where changing the memory allocator helped reduce the total JVM footprint (jemalloc vs. glibc malloc). Finally I'd try a different (more recent?) JVM version or a different GC algorithm, if possible...


Formatting bible verse reference with regex in javascript

Question: I'm trying to monospace bibleverse references so that single digit chapters or verses have a leading space.
So "4:5" becomes " 4: 5" and "3:21" becomes " 3:21".
I'm really having problems writing the regex, please help.
I've tried many variations but they essentially boil down to (^\d|\d$), (^\d{1}|\d{1}$) and (^[^0-9]\d|[^0-9]\d$) and many combinations between them
    inRef = inChapter + ':' + inVerse;
    var inReg = /(^[0-9]{1}|[^0-9][0-9]{1}$)/g;
    inRef = inRef.replace(inReg," $1");
    console.log(inRef);

Alot of the results I'm getting from my efforts turn references like "6:15" into " 6: 1 5" or " 6:1 5"
Thank you in advance.
Answer: Why a regex at all? You've already got the chapter/verse as separate data BEFORE you combined them into the x:y format, so do the formatting there while they're still seperate strings:
if (inChapter.length == 1) { inChapter = ' ' + inChapter }
inRef = inChapter + ':' + inVerse;

Using a regex for this uber-simplistic transformation is akin to nuking a city to get some dust off a shelf instead of using a feather duster.
Comment: an if() test has essentially ZERO overhead compared to having to instantiate/parse/execute a regex.
Comment: It's part of a loop and it seemed like regex would be the better option than doing two ifs for each iteration (once for chapter and once for verse).
Answer: Given the strings inChapter and inVerse, you could do something like this:
inRef = ("  " + inChapter).slice(-2) + ":" + ("  " + inVerse).slice(-2)

Note there are two spaces there "  " and I'm assuming inChapter and inVerse are only ever 1 or 2 digits.
Edit: Since you need three digits and I assume you still want these to line up, you could do this:
var pad = "   ";   // this is now THREE spaces!
inRef = (pad + inChapter).slice(-pad.length) + ":" + (pad + inVerse).slice(-pad.length)

So now if you run all your inChapter and inVerse pairs through this, you should get strings that line up like this:
100:100
 20:100
  2:100
100: 10
100:  1
 10: 10
 10:  1
  1:  1

Comment: /facepalm (mine). Nope, Psalms has more than 100 chapters, and some chapters have more than 100 verses.
Comment: @user3917091: Well then, don't you need to line those up too? In that case just substitute 3 spaces instead of 2 in my answer. (or you could just create a separate variable to make this a little easier).
Comment: Thanks for the extra effort! I've been testing on Genesis so long and it's not a long book and no long chapters that I'd completely forgotten there was anything longer.


Como executar um programa em C no Visual Studio Code

Question: Eu estou tentando rodar um código (programa) em C no Visual Studio Code, mas não consigo achar as configurações necessárias.

Instalei a extensão C/C++ (Microsoft)

Estrutura do projeto:

.vscode
- c_cpp_properties.json
- tasks.json
main.c

Meu código:
- c_cpp_properties.json
{
    "configurations": [
        {
            "name": "Mac",
            "includePath": ["/usr/include"],
            "browse" : {
                "limitSymbolsToIncludedHeaders" : true,
                "databaseFilename" : ""
            }
        },
        {
            "name": "Linux",
            "includePath": ["/usr/include"],
            "browse" : {
                "limitSymbolsToIncludedHeaders" : true,
                "databaseFilename" : ""
            }
        },
        {
            "name": "Win32",
            "includePath": ["c:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/include"],
            "browse" : {
                "limitSymbolsToIncludedHeaders" : true,
                "databaseFilename" : ""
            }
        }
    ]
}
- tasks.json
{
    "version": "0.1.0",
    "command": "g++",
    "isShellCommand": true,
    "showOutput": "always",
    "args": ["-g", "main.c"]
}
- c program
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    printf("Hello World");
    return 0;
}

Link do pastebin
Answer: O VSCode, apesar de se um editor e não uma IDE, permite compilar código através de alguns plugins. No caso de compilar códigos C/C++, no Windows, achei ele um pouco "chato". Levei uma semana para configurar.
Mesmo tendo sido a pergunta feita a mais de 1 ano atrás, acredito que algumas pessoas possam encontrar isso e eu possa ter ajudado de alguma forma.
O que fiz para compilar o código em C foi instalar o plugin C/C++ da Microsoft
Depois de instalado o plugin, baixe e instale o MingGW com as funções de gcc para Windows.
No VSCode, crie ou edite o arquivo c_cpp_properties.json, para editar basta utilizar o atalho Ctrl+Shift+P e selecionar "C/Cpp: Edit Configurations".
Lembre-se de que a versão do arquivo citado abaixo pode mudar.
{
    "configurations": [
        {
            "name": "Win32",
            "intelliSenseMode": "clang-x64",
            "includePath": [
                "${workspaceRoot}",
                "C:/MinGW/lib/gcc/mingw32/6.3.0/include/c++",
                "C:/MinGW/lib/gcc/mingw32/6.3.0/include/c++/mingw32",
                "C:/MinGW/lib/gcc/mingw32/6.3.0/include/c++/backward",
                "C:/MinGW/lib/gcc/mingw32/6.3.0/include",
                "C:/MinGW/include",
                "C:/MinGW/lib/gcc/mingw32/6.3.0/include-fixed"
            ],
            "defines": [
                "_DEBUG",
                "UNICODE",
                "__GNUC__=6",
                "__cdecl=__attribute__((__cdecl__))"
            ],
            "browse": {
                "path": [
                    "C:/MinGW/lib/gcc/mingw32/6.3.0/include",
                    "C:/MinGW/lib/gcc/mingw32/6.3.0/include-fixed",
                    "C:/MinGW/include/*"
                ],
                "limitSymbolsToIncludedHeaders": true,
                "databaseFilename": ""
            }
        }
    ]
}

Para a linguagem C, não C++, basta remover algumas linhas, como abaixo:
{
    "configurations": [
        {
            "name": "Win32",
            "intelliSenseMode": "clang-x64",
            "includePath": [
                "${workspaceRoot}",
                "C:/MinGW/lib/gcc/mingw32/6.3.0/include",
                "C:/MinGW/include",
                "C:/MinGW/lib/gcc/mingw32/6.3.0/include-fixed"
            ],
            "defines": [
                "_DEBUG",
                "UNICODE",
                "__GNUC__=6",
                "__cdecl=__attribute__((__cdecl__))"
            ],
            "browse": {
                "path": [
                    "C:/MinGW/lib/gcc/mingw32/6.3.0/include",
                    "C:/MinGW/lib/gcc/mingw32/6.3.0/include-fixed",
                    "C:/MinGW/include/*"
                ],
                "limitSymbolsToIncludedHeaders": true,
                "databaseFilename": ""
            }
        }
    ]
}

Após realizar essa configuração, apenas adiciona "C_Cpp.intelliSenseEngine": "Default" nas suas configurações de usuário.
Depois basta escrever o código e rodar com o plugin Code Runner.
Fonte: GitHub da Microsoft
Answer: O Visual Studio Code é um editor de texto, não uma IDE, não possui compilador. Você pode compilar pelo terminal (se usar Linux ou Mac):
gcc -o executavel main.c

Comment: visual studio code compila até python amigos. e pelo que diz esse tutorial: https://code.visualstudio.com/docs/languages/cpp, c e c++ também, porem só não estou conseguindo configurar meus json corretamente.
Comment: O que significa essa flag `-o`, sempre tive curiosiddade de saber mai nuca perguntei ;) ?
Comment: `-o` vem de `-- output`, ou seja, saída, o arquivo de saída daquela compilação, logo após essa flag deve se indicar o nome do executavel que a compilação irá gerar.
Comment: Na verdade não precisa ser exatamente o mingw, comigo o cygwin também funcionou, também funciona com o cmake (apesar de não falar se é possível na página do plugin), precisei criar duas tarefas, uma pra o build do cmake e outra pro make, a Microsoft poderia simplificar o processo de preparação de ambiente do VS Code, como um wizard de projetos por exemplo.
Answer: Rapaz sofri demais para rodar C no Visual Studio (Windows), descobri na tentativa e erro e adicionei um script para facilitar o uso. Fiz assim:

Aperta CTRL+SHIFT+X no Visual Studio para Abrir as extensões e instale o C/C++ da Microsoft (para autocompletar os codigos) e o Code Runner (para Executar).
Baixe o compilador MinGW.
Instale o MinGw (anota o diretório onde instalou) e abra o MinGW Installer, vai em Basic Setup e marca o mingw32-base-bin, Installation -> Apply Changes.
Vai nas variáveis do ambiente no Windows -> Variaveis do Sistema -> Path, e adicione a pasta bin do MinGW que você instalou.
Volta no VS Code -> Botão Direito no Code Runner -> Configure Extension Settings. Aba User -> Extensions. Procura Code-runner: Executor Map e vai em Edit in settings.json (O caminho aqui fica em C:\Users\NomeUsuario\AppData\Roaming\Code\User\settings.json) e deixa assim:
{
"git.ignoreMissingGitWarning": true,
"explorer.confirmDragAndDrop": false,
"explorer.confirmDelete": false,
"editor.fontSize": 16,
"editor.accessibilitySupport": "on",
"editor.autoClosingBrackets": "always",
"editor.autoClosingQuotes": "always",
"terminal.integrated.rendererType": "dom",
"terminal.integrated.shell.windows": "C:\\WINDOWS\\System32\\cmd.exe",
"C_Cpp.updateChannel": "Insiders",
"extensions.ignoreRecommendations": false,
"code-runner.executorMap": {
"javascript": "node",
"php": "C:\\php\\php.exe",
"python": "python",
"perl": "perl",
"ruby": "C:\\Ruby23-x64\\bin\\ruby.exe",
"go": "go run",
"html": "\"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe\"",
"java": "cd $dir && javac $fileName && java $fileNameWithoutExt",
"c": "cd $dir && gcc $fileName -o $fileNameWithoutExt && start $fileNameWithoutExt.exe"
},
"code-runner.clearPreviousOutput": true,
"code-runner.runInTerminal": true,
"code-runner.saveFileBeforeRun": true
}

Só precisa editar ou adicionar a linha do "c" e as 3 últimas linhas, o resto é padrão.

Só escrever seu código, salvar na extensão .c e executá-lo com CTRL+ALT+N que tudo será feito no CMD do Windows ;-].

PS1: Se não funcionar, aperta CTRL+ALT+J no teu código e seleciona C.
PS: O anti-vírus aqui (KIS) fica bloqueando toda hora a execução mas é só permitir que abre normal.
Answer: Não precisa de todas essas configurações. Basta instalar o modulo C da Microsoft. CTRL+SHIFT+´ para abrir o terminal. Já abre na pasta do arquivo. Os comandos pra executar são:
$ g++ testeC.cpp -o testeC
$ ./testeC

Onde testeC.cpp é o nome do seu arquivo com extensão (em C seria: testeC.c)

PS.:
Minha opinião pessoal sobre programar em C,C++ o melhor a fazer é instalar o code::blocks (Windows, Linux ou Mac).
Comment: O melhor seria o visual studio por causa do MSVC e as ferramentas de depuração dele, achei estranho eles fazerem uma versão para o mac que é seu maior concorrente para computadores pessoais e não para o linux deixando apenas um conjunto de ferramentas para compilar programas linux no Windows, mas pessoalmente a code blocks, falcon ou devc++ não faz tanta diferença já que eles são só um editor, para mim o mais importante é o compilador que vai fazer a tarefa mais importante, a semelhança entre eles é que usam compiladores GNU.
Answer: Complementando a resposta do amigo acima, você pode usar esse código para executar múltiplos arquivos, basta colar ele no arquivo C:\Users\%username%\AppData\Roaming\Code\User\settings.json, mas antes é necessário instalar a extensão Code Runner:
{
"terminal.integrated.shell.windows": "C:\\Windows\\System32\\cmd.exe",
"code-runner.executorMap": {
    "c": "cls && gcc -g -o $fileNameWithoutExt *.c && $fileNameWithoutExt"
},
"code-runner.clearPreviousOutput": true,
"code-runner.runInTerminal": true,
}

Answer: Olá, esse é um problema que eu enfreitei, quando comecei a usar o VS.
Se você assim como eu, gostaria apenas de ver a saída no terminal, e não perder muito tempo configurando, e fazer só uma vez de forma rápida e simples.
Eu utilizei o MinGW com a extensão do VS, C/C++ Configurations.
Primeiro coloque o diretório bin do MinGW, como variável ambiente do Windows, junto ao PATH
Depois no VS, abra o C/C++ Configurations, (Ctrl+Shift+P ">C/C++:Edit Configurations (UI)")
coloque as seguintes configurações:
Caminho do compilador:
C:\MinGW\bin\g++.exe
                    Caso não seja este o local onde está o MinGw

Compiler arguments:
-g
-Wall
-o
${fileBasenameNoExtension}.exe
${filename}

Modo do Intellisense
gcc-x64

O resto mantenha, como está ou atualize para o mais recente, para compilador C ou C++
E então ele começará a gerar o seguinte arquivo c_cpp_properties.json
{
    "configurations": [
        {
            "name": "Win32",
            "includePath": [
                "${workspaceFolder}/**"
            ],
            "defines": [
                "_DEBUG",
                "UNICODE",
                "_UNICODE"
            ],
            "compilerPath": "C:\\MinGW\\bin\\g++.exe",
            "cStandard": "c11",
            "cppStandard": "c++20",
            "intelliSenseMode": "gcc-x64",
            "compilerArgs": [
                "-g",
                "-Wall",
                "-o",
                "${fileBasenameNoExtension}.exe",
                "${filename}"
            ]
        }
    ],
    "version": 4
}

Ctrl+Alt+N que começará a compilar e aparecer no terminal.
Caso contrário...
Answer: depois de instalado o plugin c/c++ intellisense da microsoft
depois de instalado o plugin code runner de jun han
tem que colocar .exe depois dessas palavras no arquivo settings.json
tanto em "c": quanto "cpp":
a localização do arquivo é o seguinte endereço:
C:\Users\seu_nome_de_usuario\AppData\Roaming\Code\User\settings.json

$fileNameWithoutExt
$dir$fileNameWithoutExt

mudando pra
$fileNameWithoutExt.exe
$dir$fileNameWithoutExt.exe

essa é uma solução para windows pois executáveis compilados para linux não possuem extensão


How to avoid null values in a FOR loop to handle list objects in R

Question: I want to produce summary statistics using a for loop in a batch.
#--Zone statistics
zone <- lapply(YieldPts, function(a){extract(NewDatasetRaster[[11]], a)})
# extract zone variable by points

summary(YieldPts)
 Length Class                  Mode
[1,] 8489   SpatialPointsDataFrame S4
[2,] 6300   SpatialPointsDataFrame S4
[3,] 7484   SpatialPointsDataFrame S4
[4,] 8583   SpatialPointsDataFrame S4
[5,] 6761   SpatialPointsDataFrame S4
[6,] 7244   SpatialPointsDataFrame S4

summary(zone)
     Length Class  Mode
[1,] 8489   -none- numeric
[2,] 6300   -none- numeric
[3,] 7484   -none- numeric
[4,] 8583   -none- numeric
[5,] 6761   -none- numeric
[6,] 7244   -none- numeric

YieldPts is a large list that contains spatial points data frame.
NewDatasetRaster is a raster stack.
I use lapply to extract data from a raster layer, which works fine.
But when I create an empty list called zone_stat, then use a for loop to produce summary statistics for each list, it outputs null values for the first five lists, which confuses me:
zone_stat <- list()
for (i in length(YieldPts)) {
zone_stat[[i]] <- aggregate(YieldPts[[i]]$yield,
                             by=list(zone[[i]]),
                             FUN=summary)
}

summary(zone_stat)
     Length Class      Mode
[1,] 0      -none-     NULL
[2,] 0      -none-     NULL
[3,] 0      -none-     NULL
[4,] 0      -none-     NULL
[5,] 0      -none-     NULL
[6,] 2      data.frame list

Then I actually checked each list individually and it worked fine:
zone_stat[[1]] <- aggregate(YieldPts[[1]]$yield,
                         by=list(zone[[1]]),
                         FUN=summary)

Please tell me what I do wrong so I can avoid this problem.
Answer: Your for loop executes only one time. for (i in length(YieldPts)) is running a for a single value, the length of YieldPts.
Use for (i in 1:length(YieldPts)) or for (i in seq_along(YieldPts)). The latter is preferred and considered a good practice (consider the case where the object has length zero to see why).


A basic question on commutative finite local rings

Question: Let $R$ be a commutative finite local ring of order $p^n$ ($p$ is a prime and $1\in R$). I'm struggling with the following two basic questions:
(a) Is it true that $x^n=0$ for every non-unit $x\in R$ ?
(b) Is there exists a nilpotent element $x\in R$ such that $x^{n-1}\neq0$ ?
My guess is that the answer to both questions is false, but unfortunately I can not find any appropriate counterexamples.
Comment: Have you investigated the ring $R=\mathbb{Z}/p^n\mathbb{Z}$? What are the answers to your questions for this $R$?
Comment: It seem to be true in this case: If $\bar{x}\in \mathbb{Z}/(p^n)$ is non-unit, then $p\mid x$, so $\bar{x}^n=\bar{0}$. conversely, $\bar{p}^{n-1}\neq \bar{0}$ in $ \mathbb{Z}/(p^n)$
Comment: Very well. How does the general case differ from this special case?
Comment: We can not say that $p\mid x$? does every non-unit of $R$ is of the form $py$ for some $y\in R$? it is not clear to me why $p^n=0$ in $R$
Comment: Thanks @kabenyuk. I will be appreciate if you can explain it to me. I have only basic knowledge in ring theory.
Comment: Another good example of a local ring of $q=p^n$ elements is the field $F_q$.
Comment: Since $R^{+}$ is abelian group of order $p^n$ we deduce that $p^n\bar{p}=0$, so $\bar{p}$ is non-unit. In addition, $\bar{p}R$ is an ideal in $R$. Is it maximal? If it does, then indeed every non-unit element is of the form $\bar{p}y$. Right?
Answer: I will try to answer your first question.
In any commutative local ring $R$ of order $p^n$ it is true that $x^n$=0
for every non-unit $x\in R$.
Let $R^* $ be the set of units of $R$ and
$M$ be the maximal ideal of $R$.
Then $|M|=p^k$ for some non-negative integer $k<n$
and $|R^*|=p^n-p^k=p^k(p^{n-k}-1)\geq p-1$.
Let $x\in M$. Let us prove that $x^n=0$.
Note first that if $x,\ldots,x^s$ are all nonzero, then
$$
a_1x+\ldots+a_sx^s=0,\ a_i\in R^*\cup\{0\}\ \Rightarrow\ a_1=\ldots=a_s=0.
$$
Indeed, if $a_1x+\ldots+a_sx^s=0$ and $a_1\neq0$, then
$x(a_1+\ldots+a_sx^{s-1})=0\ \Rightarrow\ x=0$.
It follows that elements of the form
$a_1x+\ldots+a_sx^s=0,\ a_i\in R^*\cup\{0\}$ are at least $p^s$.
So $s<n$, and then $x^n=0$.
Comment: thanks @kabenyuk. You claim that the set of elements $$\{a_1x+\ldots+a_sx^s:a_i\in R^{\ast}\cup\{0\}\}$$ are distinct? why?
Comment: what about the second question?
Comment: It is sufficient that the set of elements
$$
a_1x+\ldots+a_sx^s,\ a_i=t_i\cdot1,\ 0\leq t_i1$. It has no nilpotent elements with the property $x^{n-1}\neq0$.
Comment: thanks @kabenyk.


conversion of multiplication of int32 to int64

Question: I have following structure
struct {
    int myData;
    int myAnotherData;
}Value;

struct AnotherStructure {
    unsigned int uiLowData;
    unsigned int uiHighData;
};

AnotherStructure m_AnotherStructure;
Value val;
val.myData = 10;
#define MULTIPLY 36000000000

unsigned __int64 &internalStructure = *(unsigned __int64*)&m_AnotherStructure;
internalStructure  = 0;
internalStructure += ((unsigned __int64)val.myData * MULTIPLY );

My questions is there any overflow of data in above case as we are multiplying unsigned int with big value, is result stored in temp value of type unsigned int and then stored in int 64? If now how there won't be any overflow?
Thanks
Answer: val.myData is casted to unsigned __int64 before the multiplication, because you explicitly cast.
still overflows can occur, depending on the value stored in val.myData - the maximum int multiplied by 36000000000 wont fit into 64 bits.
and you loose your algebraic sign with the cast.
you should try this:
struct AnotherStructure {
    int64_t uiLowData;
    int64_t uiHighData;
};
// signed_128bit_integer: look into your compiler documentation
signed_128bit_integer &internalStructure = *(signed_128bit_integer*)&m_AnotherStructure;
internalStructure  = 0;
internalStructure += ((signed_128bit_integer)val.myData * MULTIPLY );


Pegar dados de duas tabelas ao mesmo tempo, logo quando inicia a sessão

Question: Estou tentando pegar dados de duas tabelas logo no inicio da sessão quando o usuário realiza o login, quando utilizo o

SELECT * FROM usuarios, orders WHERE email = '$login' and senha= '$senha'

Consigo realizar o login tranquilamente, até ai de boa, mais quando modifico o código para

$comando="SELECT * FROM usuarios INNER JOIN orders ON usuarios.id_usuario = orders.id_usuario WHERE email.usuarios='$login' and senha.usuarios='$senha'";

Ele só me deixa fazer login se o usuário já tiver algum orders (pedido). O que estou tentando fazer é assim que o usuário loga, mostre também os pedidos que ele já fez etc, que são dados que estão em outra tabela. Alguém consegue ver meu erro?
Answer: Ignorando outros possíveis problemas. O que você provavelmente quer fazer um LEFT JOIN e não um INNER JOIN.
Experimente usar o LEFT JOIN, ao invés do INNER JOIN:
SELECT * FROM usuarios LEFT JOIN orders ON usuarios.id_usuario = orders.id_usuario WHERE email.usuarios='$login' and senha.usuarios='$senha'

O LEFT JOIN deve obter todos os dados do usuarios e, se houver algum match ele irá pegar os orders. Existe esta resposta com uma comparação entre todos os JOIN. Note que está usando email.usuarios, talvez seja usuarios.email, mas apenas copiei como está na sua pergunta.
Comment: Pessoalmente, eu ainda preferiria fazer duas queries distintas, em funções distintas.
Comment: Agora não consigo pegar alguns dados da tabela como ID_usuario
Comment: Os usuarios que tem orders(pedidos) eu consigo pegar o id_usuario da tabela usuarios, mais aqueles que não tem orders, ele não me retornar o id_usuario
Comment: Isso é porque o `id_usuario` está presente nas duas tabelas,é ambíguo, então se tentar pegar `id_usuario` ele pegará de qualquer uma. Você tem que especificar `usuarios.id_usuario` (não uso mais PHP, não me lembro se era possível) ou selecionar com um alias (`SELECT *, usuarios.id_usuario as id_usuario FROM ....`), dessa forma você força que `id_usuario` seja o `usuarios.id_usuario`.
Comment: Então ficaria "SELECT usuarios.id_usuario as id_usuario * FROM usuarios LEFT JOIN orders ON usuarios.id_usuario = orders.id_usuario WHERE usuarios.email='$login' and usuarios.senha='$senha'"  ?
Comment: @Edvan, basicamente. Mas, o `*` tem que vim sempre antes (`SELECT *, usuarios.id_usuario as id_usuario FROM ...`) e não (`SELECT usuarios.id_usuario as id_usuario, * FROM ....`), ou substitua com as colunas que realmente está usando (o que é preferível).
Comment: Massa irmão que Deus o abençoe :)
Comment: Por exemplo se eu tiver 2 pedidos do mesmo ID_usuario, tem como fazer ele me retornar todos os pedidos feitos pelo mesmo ID_usuario, ou eu teria que usar uma nova query com WHILE?
Comment: Cada pedido será uma linha, você vai ter que acessar cada um usando o `mysqli_fetch` normalmente. Você pode fazer um `foreach(mysqli_fetch_array($con, $result) as $row) {
// var_dump($row);
}`
Comment: Tem como eu fazer isso usando os dados que já tenho da SESSION do usuário, ou vou ter que fazer uma nova consulta SQL
Comment: Perdoe-me se estou sendo incomodo, não tenho muita familiaridade com PHP


Angular2 Quick Start Error

Question: I want to use Angular2 so I started tutorial from official website https://angular.io/docs/ts/latest/quickstart.html
I just copy past the code
And at the end I run commands :
$ npm install
-> ok
$ npm start
> email@example.com start /home/pln/dev/myprojects/myprojects/myapp-front
> concurrent "npm run tsc:w" "npm run lite"

[0]
[0] > email@example.com tsc:w /home/pln/dev/myprojects/myprojects/myapp-front
[0] > tsc -w
[0]
[1]
[1] > firstname.lastname@example.com lite /home/pln/dev/myprojects/myprojects/myapp-front
[1] > lite-server
[1]
[1] [BS] Access URLs:
[1]  -------------------------------------
[1]        Local: http://localhost:3000
[1]     External: http://192.168.0.47:3000
[1]  -------------------------------------
[1]           UI: http://localhost:3001
[1]  UI External: http://192.168.0.47:3001
[1]  -------------------------------------
[1] [BS] Serving files from: ./
[1] [BS] Watching files...
[0] 09:04:01 - Compilation complete. Watching for file changes.
[1] [BS] File changed: app/app.component.js
[1] [BS] File changed: app/boot.js
[1] events.js:85
[1]       throw er; // Unhandled 'error' event
[1]             ^
[1] Error: watch ENOSPC
[1]     at exports._errnoException (util.js:746:11)
[1]     at FSWatcher.start (fs.js:1172:11)
[1]     at Object.fs.watch (fs.js:1198:11)
[1]     at createFsWatchInstance (/home/pln/dev/myprojects/myprojects/myapp-front/node_modules/lite-server/node_modules/browser-sync/node_modules/chokidar/lib/nodefs-handler.js:37:15)
[1]     at setFsWatchListener (/home/pln/dev/myprojects/myprojects/myapp-front/node_modules/lite-server/node_modules/browser-sync/node_modules/chokidar/lib/nodefs-handler.js:80:15)
[1]     at FSWatcher.NodeFsHandler._watchWithNodeFs (/home/pln/dev/myprojects/myprojects/myapp-front/node_modules/lite-server/node_modules/browser-sync/node_modules/chokidar/lib/nodefs-handler.js:228:14)
[1]     at FSWatcher.NodeFsHandler._handleFile (/home/pln/dev/myprojects/myprojects/myapp-front/node_modules/lite-server/node_modules/browser-sync/node_modules/chokidar/lib/nodefs-handler.js:255:21)
[1]     at FSWatcher.<anonymous> (/home/pln/dev/myprojects/myprojects/myapp-front/node_modules/lite-server/node_modules/browser-sync/node_modules/chokidar/lib/nodefs-handler.js:473:21)
[1]     at FSReqWrap.oncomplete (fs.js:95:15)
[1]
[1] npm
[1]
[1] ERR!
[1]  Linux 3.16.0-56-generic
[1] npm
[1]  ERR! argv "/usr/bin/node" "/usr/bin/npm" "run" "lite"
[1] npm ERR! node
[1]  v0.12.9
[1] npm ERR! npm
[1]  v2.14.9
[1] npm
[1]  ERR! code ELIFECYCLE
[1] npm
[1] ERR! firstname.lastname@example.com lite: `lite-server`
[1] npm
[1] ERR! Exit status 1
[1] npm
[1]  ERR!
[1] npm
[1]  ERR!
[1]  Failed at the firstname.lastname@example.com lite script 'lite-server'.
[1] npm ERR! This is most likely a problem with the myapp-front package,
[1] npm ERR! not with npm itself.
[1] npm ERR! Tell the author that this fails on your system:
[1] npm ERR!     lite-server
[1] npm ERR! You can get their info via:
[1] npm ERR!     npm owner ls myapp-front
[1] npm ERR!
[1]  There is likely additional logging output above.
[1]
[1] npm ERR! Please include the following file with any support request:
[1] npm
[1] ERR!     /home/pln/dev/myprojects/myprojects/myapp-front/npm-debug.log
[1] npm run lite exited with code 1

What can I do ?
Answer: Well, a quick Google will lead you here, or any number of other places that will tell you that ENOSPC means that there is not enough space to install what you're trying to install on the drive you're trying to install it to.... so free some space and run it again.
Comment: It works : echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p
Comment: @Maryo that worked for me as well..what exactly does that do?
Answer: Refer the below code to avoid ENOSPC
echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p

Answer: Do npm clean. Then do npm install, npm start.

Angular2 Quick Start Error


Semitones in tremolo harmonica

Question: I looked all the internet to get this question answered, but it's hopeless. How can I play notes with accidentals – sharp, flats/bemol – in my 24-hole tremolo harmonica, I want to play this, How can I play the semitones?
Answer: It looks like this particular harmonica is a simply diatonic one, giving available notes in C major of C D E F G A and B, in various octaves.
To be able to play the 'black keys' - # and b, you really need a chromatic harmonica, aka chromonica. This has a button on the right, which when pressed, will sharpen any note you play, blow or draw.
It is actually possible, drawing especially, to bend notes downwards. So you could possibly find the notes you need this way.Can't access the dots, so don't know if some of the accidental notes are blown. If so, it's not going to be easy without that chromonica.
Comment: Bending on the blow isn't much harder than bending on the draw, but both are much harder, bordering on impossible, on a tremolo harp. A diatonic blues harp has access to most of the notes of the chromatic scale.
Comment: @ToddWilcox - but, I forgot to say, keeping those bent notes in good tune/pitch isn't easy, on any harp.  Incidentally, congrats on attaining 3rd position in the votes cast table. Slim had retained it for a very long time.

Semitones in tremolo harmonica


install gem in local machine

Question:
I am using pry gem for debugging my rails application. So I have
  specified it in my Gemfile and using it. But I dont need to push the
  Gemfile with pry gem specified. So everytime I need to revert it to
  original Gemfile and push it to remote repo.
I was wondering is there any way where I can install pry gem in my
  local machine and use it in my rails app globally so that I dont have
  to specify that gem in Gemfile.??

I tried to do
gem install pry

But when I use binding.pry in my rails controller, it says
undefined method `pry' for #<Binding:0x0000000619398>

Answer: With bundler you can create groups according to your environments.
You can intall your gem only for the development group.
Put the line below in your gemfile.
gem 'pry', :group => :development

Comment: @
Nitin Satish Salunke I agree that we can create groups per environment. But this does not solve my problem since I will be pushing the Gemfile to remote repo and I will have to revert it. So is there any way without specifying it in Gemfile.
Comment: @rubyist I guess there is no such option to achieve to what you want.
Only the gems that you specify in your gemfile are included in your environment.

install gem in local machine


Buttons in PyQT5 using python

Question: I created a back button in new window and next button in main window. After I clicked the next button to show a new window, it was successfully hides the current main window but when I clicked back button on the new window, the application automatically closes itself. Any idea?
The code in first mainWindow.py file:
from PyQt5 import QtCore, QtGui, QtWidgets

try:
    from secondWindow import Ui_SecondWindow
except:
    import secondWindow

class Ui_firstWindow(object):
        def secondWindow(self):
            self.window = QtWidgets.QMainWindow()
            self.ui = Ui_SecondWindow()
            self.ui.setupUi(self.window)
            self.window.show()
            if self.window.show():
                self.hide

        def setupUi(self, firstWindow):
            firstWindow.setObjectName("firstWindow")
            firstWindow.resize(800, 600)
            self.centralwidget = QtWidgets.QWidget(firstWindow)
            self.centralwidget.setObjectName("centralwidget")
            self.btn_next = QtWidgets.QPushButton(self.centralwidget)
            self.btn_next.setGeometry(QtCore.QRect(160, 100, 521, 291))
            self.btn_next.setObjectName("btn_next")

            ######To Open second window###########
            self.btn_next.clicked.connect(self.secondWindow)

            self.label = QtWidgets.QLabel(self.centralwidget)
            self.label.setGeometry(QtCore.QRect(360, 420, 151, 16))
            self.label.setStyleSheet("font: 11pt \"MS Shell Dlg 2\";")
            self.label.setObjectName("label")
            firstWindow.setCentralWidget(self.centralwidget)
            self.menubar = QtWidgets.QMenuBar(firstWindow)
            self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
            self.menubar.setObjectName("menubar")
            firstWindow.setMenuBar(self.menubar)
            self.statusbar = QtWidgets.QStatusBar(firstWindow)
            self.statusbar.setObjectName("statusbar")
            firstWindow.setStatusBar(self.statusbar)

            self.retranslateUi(firstWindow)
            QtCore.QMetaObject.connectSlotsByName(firstWindow)

        def retranslateUi(self, firstWindow):
            _translate = QtCore.QCoreApplication.translate
            firstWindow.setWindowTitle(_translate("firstWindow", "MainWindow"))
            self.btn_next.setText(_translate("firstWindow", "Next"))
            self.label.setText(_translate("firstWindow", "First Window"))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    firstWindow = QtWidgets.QMainWindow()
    ui = Ui_firstWindow()
    ui.setupUi(firstWindow)
    firstWindow.show()
    sys.exit(app.exec_())

The codes in second secondWindow.py file:
from PyQt5 import QtCore, QtGui, QtWidgets

try:
    from mainWindow import Ui_firstWindow
except:
    import mainWindow
class Ui_SecondWindow(object):
        ###function to go back the first window######
        # @pyqtSlot()
        def openBackFirstWindow(self):
            self.window = QtWidgets.QMainWindow()
            self.ui = Ui_firstWindow()
            self.ui.setupUi(self.window)
            self.window.show()
            if self.window.show():
                self.hide

        def setupUi(self, SecondWindow):
            SecondWindow.setObjectName("SecondWindow")
            SecondWindow.resize(800, 600)
            self.centralwidget = QtWidgets.QWidget(SecondWindow)
            self.centralwidget.setObjectName("centralwidget")
            self.btn_back = QtWidgets.QPushButton(self.centralwidget)
            self.btn_back.setGeometry(QtCore.QRect(220, 100, 401, 281))
            self.btn_back.setObjectName("btn_back")

            ###To go back to first windo######
            self.btn_back.clicked.connect(self.openBackFirstWindow)

            self.label = QtWidgets.QLabel(self.centralwidget)
            self.label.setGeometry(QtCore.QRect(370, 440, 151, 16))
            self.label.setStyleSheet("font: 11pt \"MS Shell Dlg 2\";")
            self.label.setObjectName("label")
            SecondWindow.setCentralWidget(self.centralwidget)
            self.menubar = QtWidgets.QMenuBar(SecondWindow)
            self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
            self.menubar.setObjectName("menubar")
            SecondWindow.setMenuBar(self.menubar)
            self.statusbar = QtWidgets.QStatusBar(SecondWindow)
            self.statusbar.setObjectName("statusbar")
            SecondWindow.setStatusBar(self.statusbar)

            self.retranslateUi(SecondWindow)
            QtCore.QMetaObject.connectSlotsByName(SecondWindow)

        def retranslateUi(self, SecondWindow):
            _translate = QtCore.QCoreApplication.translate
            SecondWindow.setWindowTitle(_translate("SecondWindow", "MainWindow"))
            self.btn_back.setText(_translate("SecondWindow", "Back"))
            self.label.setText(_translate("SecondWindow", "Second Window"))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    SecondWindow = QtWidgets.QMainWindow()
    ui = Ui_SecondWindow()
    ui.setupUi(SecondWindow)
    SecondWindow.show()
    sys.exit(app.exec_())

When i clicked the back button in second window, the application stopped working and exits itself. Any idea?
Comment: Please provide a [minimal, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example).
Comment: @musicmante already updated, appreciate if you could solve out..
Answer: Do not modify the code generated by Qt Designer but create another class that inherits
from the appropriate widget and use the initial class to fill it.
from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_firstWindow(object):
        def setupUi(self, firstWindow):
            firstWindow.setObjectName("firstWindow")
            firstWindow.resize(800, 600)
            self.centralwidget = QtWidgets.QWidget(firstWindow)
            self.centralwidget.setObjectName("centralwidget")
            self.btn_next = QtWidgets.QPushButton(self.centralwidget)
            self.btn_next.setGeometry(QtCore.QRect(160, 100, 521, 291))
            self.btn_next.setObjectName("btn_next")

#            ######To Open second window###########
#            self.btn_next.clicked.connect(self.secondWindow)

            self.label = QtWidgets.QLabel(self.centralwidget)
            self.label.setGeometry(QtCore.QRect(360, 420, 151, 16))
            self.label.setStyleSheet("font: 11pt \"MS Shell Dlg 2\";")
            self.label.setObjectName("label")
            firstWindow.setCentralWidget(self.centralwidget)
            self.menubar = QtWidgets.QMenuBar(firstWindow)
            self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
            self.menubar.setObjectName("menubar")
            firstWindow.setMenuBar(self.menubar)
            self.statusbar = QtWidgets.QStatusBar(firstWindow)
            self.statusbar.setObjectName("statusbar")
            firstWindow.setStatusBar(self.statusbar)

            self.retranslateUi(firstWindow)
            QtCore.QMetaObject.connectSlotsByName(firstWindow)

        def retranslateUi(self, firstWindow):
            _translate = QtCore.QCoreApplication.translate
            firstWindow.setWindowTitle(_translate("firstWindow", "MainWindow"))
            self.btn_next.setText(_translate("firstWindow", "Next"))
            self.label.setText(_translate("firstWindow", "First Window"))

class Ui_SecondWindow(object):
        def setupUi(self, SecondWindow):
            SecondWindow.setObjectName("SecondWindow")
            SecondWindow.resize(800, 600)
            self.centralwidget = QtWidgets.QWidget(SecondWindow)
            self.centralwidget.setObjectName("centralwidget")
            self.btn_back = QtWidgets.QPushButton(self.centralwidget)
            self.btn_back.setGeometry(QtCore.QRect(220, 100, 401, 281))
            self.btn_back.setObjectName("btn_back")

#            ###To go back to first windo######
#            self.btn_back.clicked.connect(self.openBackFirstWindow)

            self.label = QtWidgets.QLabel(self.centralwidget)
            self.label.setGeometry(QtCore.QRect(370, 440, 151, 16))
            self.label.setStyleSheet("font: 11pt \"MS Shell Dlg 2\";")
            self.label.setObjectName("label")
            SecondWindow.setCentralWidget(self.centralwidget)
            self.menubar = QtWidgets.QMenuBar(SecondWindow)
            self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
            self.menubar.setObjectName("menubar")
            SecondWindow.setMenuBar(self.menubar)
            self.statusbar = QtWidgets.QStatusBar(SecondWindow)
            self.statusbar.setObjectName("statusbar")
            SecondWindow.setStatusBar(self.statusbar)

            self.retranslateUi(SecondWindow)
            QtCore.QMetaObject.connectSlotsByName(SecondWindow)

        def retranslateUi(self, SecondWindow):
            _translate = QtCore.QCoreApplication.translate
            SecondWindow.setWindowTitle(_translate("SecondWindow", "MainWindow"))
            self.btn_back.setText(_translate("SecondWindow", "Back"))
            self.label.setText(_translate("SecondWindow", "Second Window"))

class SecondWindow(QtWidgets.QMainWindow, Ui_SecondWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

class MainWindow(QtWidgets.QMainWindow, Ui_firstWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        ######To Open second window###########
        self.btn_next.clicked.connect(self.secondWindow)

    def secondWindow(self):
        self.window = SecondWindow()
        ###To go back to first windo######
        self.window.btn_back.clicked.connect(self.openBackFirstWindow)
        self.window.show()
        self.hide()

    ###function to go back the first window######
    def openBackFirstWindow(self):
        self.show()
        self.window.hide()

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    app.setStyle('Fusion')
    firstWindow = MainWindow()
    firstWindow.show()
    sys.exit(app.exec_())

Comment: @UtayaSurian As already pointed out by S. Nick, you should *not* modify the code generated from `pyuic`. To know more about the correct way to use those files, read about [using Designer](https://www.riverbankcomputing.com/static/Docs/PyQt5/designer.html).

Buttons in PyQT5 using python


Website Reviews - Dynamically Displaying an image of the front of other websites

Question: I've been building a website page that reviews other pages and with the review it would be great to also show an image of the front of the site as it currently looks.
eg: Review 1
Website Name & Domain name
Review Text
Image of front of page.
I know I can get the images of the fronts of pages manually and add them in as STD HTML  etc tags.
But I wanted to ask if there was a way to do this dynamically so it would always be current.
Is this possible?
Are there any issues with doing this?
thx
Answer: Have you tried squeezeFrame?
Shrinking contents is sometimes not the easiest thing to do but the plugin comes pretty darn close to the best thing for your situation.
http://futtta.be/squeezeFrame/


Qual a diferença entre extensão e biblioteca no PHP?

Question: No PHP existem algumas extensões dentro da linguagem. Por exemplo, a SPL, a PHAR e a PDO são algumas dessas extensões.
Basicamente, as minhas dúvidas são as seguintes:

Qual a diferença de uma extensão para uma biblioteca?
Seria ou não correto chamá-las de bibliotecas por serem um conjunto de classes?

PS: Quando me refiro a extensão, quero dizer extensões da linguagem e não de formatos de arquivo e coisas do tipo.
Comment: Extensão é aquilo que estende uma funcionalidade da linguagem, no PHP geralmente (se não sempre) são escritas em C. Uma biblioteca é um conjunto de estruturas, não necessariamente classes, que auxiliam na resolução de um problema.
Comment: Relacionada: [Qual é a diferença de API, biblioteca e Framework?](https://pt.stackoverflow.com/q/17501/28595)
Answer: O que é o PHAR em PHP
Primeiramente quero deixar claro que arquivos PHAR não são extensões, são "pacotes" que podem conter uma aplicação inteira (e geralmente contêm) para facilitar a instalação e distribuição, ou seja, ele agrupa uma série de arquivos em um único arquivo .phar que pode ser executado inteiramente ou parcialmente usando o protocolo phar:// dentro de outros scripts php, exemplo para acessar um arquivo especifico:
include 'phar:///caminho/para/meuarquivo.phar/olamundo.php';

Isto não quer dizer que o phar não possa ser tratado com uma biblioteca, ou um Framework, mas de qualquer forma o que basicamente vai definir isto é o seu conteúdo e como um .phar especifico foi projetado para ser usado, ou seja o desenvolvedor define isto.
Resumindo, um .phar em si não se caracteriza como uma biblioteca, por padrão ele é um pacote de qualquer coisa com uma série de arquivos compactados, que podem ou não ser executados separadamente (via include) ou como uma aplicação inteira, vagamente assemelhando-se ao .jar usado em ambientes Java, que podem funcionar como pacotes de funções ou até como aplicações inteiras.
O que é uma biblioteca
Sobre bibliotecas você pode já ter a resposta aqui Qual é a diferença de API, biblioteca e Framework?, mas para dar um exemplo mais claro e bem simplório em PHP, uma biblioteca poderia ser um conjunto de funções e/ou classes definidos para um ou mais usos que geralmente visa facilitar uma tarefa, ou seja você não precisa ter um conhecimento do funcionamento, só precisa saber como usa-las em sua aplicação final, claro que isso é bem vago da forma que expliquei, mas creio que até aqui seja o suficiente para entender.
Extensões em PHP
Em php especificamente temos pelo entendimento comum que extensões são as .dll ou .so (em ambientes unix-like) como sendo binários contendo bibliotecas ou até frameworks inteiros que estendem as funcionalidades básicas do PHP que geralmente (depende um pouco de como você vai compilar) a maior parte das APIs internas do PHP são extensões que são ativadas ou desativadas no php.ini através dos parametros:
extension=xyz.dll

xyz.dll é apenas um exemplo

Ou até mesmo o caminho completo:
extension=C:\foo\bar\xyz.dll

Claro que não basta criar um arquivo .c e compilar no MingW para conseguir criar uma extensão para o PHP, a .dll tem que ser compilada pelo mesmo tipo de compilador que foi compilado o PHP de sua máquina ou servidor, ou seja não é tão simples, e fora isto precisa entender como fazer a dll se "comunicar com o php" que pode acompanhar aqui:

http://php.net/manual/en/internals2.structure.php

Agora alguns detalhes:

Uma extensão para php pode ser uma biblioteca
Uma extensão para php pode ser um framework
Uma extensão para php pode não fornecer nenhuma função para o programador mas pode fazer coisas automaticamente, como XCache ou Opcache (duas extensões para PHP), que fazem os scripts .php em um servidor executarem mais rápido devido a uma especie de "compilação" (bytecode, cada um a sua maneira) e que também ajuda a reduzir em muito o consumo de memória

claro que ambas .dll/.so de cache fornecem algumas funções especificas, mas poderiam não fornecer, o que não faria elas deixarem de ser extensões

Como disse, uma extensão é escrita em c (mas existem meios alternativos não oficiais em C++), um exemplo da estrutura de uma extensão não compilada seria algo como (conforme o link que já mencionei acima):
ext/
 └─── foobar/
       ├─── config.m4
       ├─── config.w32
       ├─── foobar_util.h
       ├─── foobar_util.c
       ├─── php_foobar.h
       ├─── foobar.c
       ├─── package.xml
       ├─── CREDITS
       └─── tests/
             ├─── critical_function_001.phpt
             ├─── critical_function_002.phpt
             ├─── optional_function_001.phpt
             └─── optional_function_002.phpt

A pasta tests são apenas testes que você escreve semelhante aos testes unitários.

config.m4 é a configuração do sistema de compilação para UNIX-like (veja o link para mais detalhes https://www.php.net/manual/en/internals2.buildsys.configunix.php)

config.w32 é a configuração do sistema de compilação para Windows (veja o link para mais detalhes https://www.php.net/manual/en/internals2.buildsys.configwin.php)

php_foobar.h
Ao construir uma extensão como módulo estático no "binário PHP", o sistema de construção espera um arquivo de cabeçalho com php_ como prefixo do nome da extensão, que inclui uma declaração para um ponteiro para a estrutura do módulo da extensão. Este arquivo geralmente contém macros, protótipos e globais adicionais, assim como qualquer cabeçalho.

foobar.c
Principal arquivo fonte da extensão. Por convenção, o nome deste arquivo é o nome da extensão, mas isso não é um requisito. Este arquivo contém a declaração da estrutura do módulo, entradas INI, funções de gerenciamento, funções de espaço do usuário e outros requisitos de uma extensão.

Os outros arquivos .h no exemplo são apenas "separações" que você pode ou não fazer e depois usar com #include.
Termo extensão
Agora só sobre o termo extensão, mesmo em PHP, ou falando só sobre isso, extensão poderia facilmente ser um termo usado para diferentes situações, fora as extensões já citadas antes, isto eu me refiro ao nível da linguagem e não ao nivel do "PHP interpretador" (o executável php.exe em windows por exemplo).
Por exemplo, você tem uma aplicação php que é um site, então você cria um script PHP que adiciona alguma rotina especifica para o teu site, daria para chamar de extensão, é o termo mais adequado? Creio que não, ainda mais que causaria confusão.
Agora sobre classes em PHP, quando se cria algo assim:
class Foo {}

class Bar extends Foo {}

A classe Bar estende (ou não) os métodos e/ou propriedades da classe Foo, então possivelmente Bar vai ser uma extensão para Foo, mas claro que sair chamando de extensão vai confundir um pouco, creio que seja mais fácil dizer claramente o que é, Bar é uma "classe estendida"

Diferença do PHAR e de uma extensão (.dll/.so)
Phar são pacotes e podem ser executados diretamente, até via linha de comando, já as .dlls são executadas a partir do momento que um servidor PHP é iniciado ou no momento que o PHP é executado (startup), ou seja é como se o PHAR fosse a parte do PHP e já as dlls estão sendo executadas a todo momento, claro que ambos podem conter coisas semelhantes, mas basicamente executam em tempos diferentes.

Respondendo ao questionário

Qual a diferença de uma extensão para uma biblioteca?

Creio que já respondi acima, mas resumidamente extensões do PHP pode ter bibliotecas e/ou funções ou não ter nada além de uma rotina automática (como um sistema para gerar bytecode de scripts PHP para melhorar a performance das aplicações PHP) e a biblioteca pode ir dentro disto, ou não.

Seria ou não correto chamá-las de bibliotecas por serem um conjunto de classes?

PHAR ou extensões não são bibliotecas, mas podem ser, dependendo do que tiver dentro, podem também não conter nada mesmo e ainda serão um extensões e arquivos .phar


Drush does not acknowledge release of new core update

Question: I am trying to update my drupal 7.31 core to 7.32 via Drush.
I ran the following commands
$ drush pm-releases
Project  Release  Date         Status
drupal   7.x-dev  2014-Oct-15  Development
drupal   7.32     2014-Oct-15  Supported, Recommended, Security
drupal   7.31     2014-Aug-06  Security

After the above command i ran the following:
$ drush pm-update drupal
Update information last refreshed: Thu, 10/16/2014 - 07:33
 Name    Installed Version  Proposed version  Message
 Drupal  7.31               7.31              Unknown

No code updates available.

so i ran the following command:
$ drush pm-update drupal-7.32
Update information last refreshed: Thu, 10/16/2014 - 07:33
 Name         Installed Version  Proposed version  Message
 drupal-7.32  Unknown            Unknown           Specified version not found

No code updates available.

Here are the versions for drush and composer. Both are to the latest versions.
$ drush version
 Drush Version   :  7.0-dev

Composer version 1.0-dev
Comment: Just for kicks, restart MySQL and then try. That worked for me with a similar issue.
Answer: drush rf
will refresh the available releases and at that point you should be able to run
drush up
or
drush up drupal.
Comment: Does not work ....

drupal
Update information last refreshed: Thu, 10/16/2014 - 08:29

 drupal  Unknown            Unknown           Specified project not found

No code updates available.
Comment: Works like a charm!
Comment: Why on earth is this the last listed answer, with the highest upvotes, and the author has the highest reputation? Despite all these years using `drush` never heard of `pm-refresh` Works as expected. Thanks!
Answer: I have the same problem. Can't get to update list of modules and core.  Tried CC, cache_update truncate. Well everything I could come up with and still nothing.
What is strange is that on localhost is where I get this, on remote server it is ok.
So I fixed it somehow with disabling and uninstaling update manager and installing it again.
Comment: Same problem, none of the solutions that I found online worked, except for this one :)
Answer: In addition to all the great answers above, be sure to do a double check for possible [facepalm] brain-fail issues:

are you logged in to the right server?
the right drupal site path on that server?
did you mess with your /etc/hosts file and forget?
is www and non-www pointed to the same place?
are you looking at a local or dev copy in your browser?

If you run drush status and it has the updated version but you still see the update alerts in the GUI Reports > Available Updates page then you might be a total f#¢&ing idiot like me and be looking at different copies of the site.
If you've already tried drush rf and you compare drush status and it has the same current version number you get when you run drush pm-releases drupal then you definitely have an issue other than drush not working properly.
Comment: Haha this was just me!
Answer: I also had the same problem.
Restarting MySQL server didn't work for me.
Disabling update manager, uninstalling it and then re-enabling it worked for me.
$ drush -y dis update
$ drush -y pm-uninstall update
$ drush -y en update

Comment: @pachabhaiya's commands worked verbatim for me, when restarting MySQL didn't solve it, after running into this exact same issue.
Comment: Didnt I just said that above?
Comment: Yes, you did. Tried everybody's solution. Just wanted to let others know what worked for me. Luckily your solution worked for me.
Answer: The solution offered by Danny Englander worked.
Restarting mysql server did the trick.
Thanks Danny.
Answer: First of all execute:
drush pm-releases drupal

Then you should see all tag names like this:
 Project  Release  Date         Status
  drupal   7.38     2015-Jun-17  Supported, Recommended, Security, Installed
  drupal   7.x-dev  2015-Jun-17  Development

Now you can get Project name and Release number like this 'drupal-7.38' and execute this to force update to that release:
drush dl drupal-7.38

You can even choose a development version of update by write the development release number.
This also work with update modules. If you need to force update for a module like ctools for a dev release you can execute:
drush dl ctools-7.x-1.x-dev

Enjoy drush <3
Answer: I had the same problem, the command
drush up drupal

was not finding the new drupal version. Even the update module, from the admin interface, was not showing the new drupal core release.
I've managed truncating the cache_update table
TRUNCATE TABLE  cache_update

For what I've seen, the update module caches the new release informations in this table, for some strange reasons the drush cc all command was not cleaning this table so the new drupal core release colund't be found.
Answer: All the answers here and no one suggested the simplest one which works every time for me:
drush cc drush

drush cc all clears all the Drupal caches, but does not clear the drush cache.
Answer: It is an old question, but I will share my recent experience regardless. For me, it was just a silly problem with drush not being able to access the internet (as I am behind a proxy).
The solution was to set HTTP_PROXY and HTTPS_PROXY (and their lower-case versions) env variables to the proper values.


How can I design an XSD which restricts the usage of elements based on other elements

Question: I am making an XSD file to validate that an IO definition for a system does not contain any "bad" configurations.
In this environment I have a set of different hardware boards, each with a different number of output pins, some of which use additional hardware to extend them.
However, when using certain hardware extensions, certain pins on each board become occupied by the hardware extension and are no longer there for normal use: When we are using an Arduino with a MUX II shield, for instance, pins 17, 18, and 19 are used by the shield.
I want to make my XSD such that the following sequence validates:
...
<ArduinoDuo name="dev1">
    <pin1 name="bLed1" type="output" voltage="5"/>
    ...
    <pin17 name="bSwitchA" type="output" voltage="5"/>
</ArduinoDuo>

as well as
...
<ArduinoDuo name="dev2">
    <pin1 name="bLedXYZ" type="output" voltage="5"/>
    ...
    <pin16 name="bToggleC" type="input" voltage="5"/>
    <MuxII name="LEDExtenderA>
        <pin1 name="bToggleABC" type="input" voltage="25">
    </MuxII>
</ArduinoDuo>

but where the following does NOT validate:
...
<ArduinoDuo name="dev1">
    <pin1 name="bLed1" type="output" voltage="5"/>
    ...
    <pin17 name="bSwitchA" type="output" voltage="5"/>
    <MuxII name="LEDExtenderA>
        <pin1 name="bToggleABC" type="input" voltage="25">
    </MuxII>
</ArduinoDuo>

Ultimately, I would like it so that the use of individual pins is optional, but to restrict their use when the Elements which declare extensions are present.
Answer: If it were only this case, you could define a content model
pin1? pin2? ,,,, pin16?, ((pin17?, pin18?, pin19) | MuxII)

using "," for sequence, "?" for optionality, and "|" for choice.
But if there lots of things like MuxII that require certain pins to be absent then this becomes impossible, or at any rate, hopelessly unwieldy.
You need XSD 1.1 with assertions. Then you can write things like
<xs:assert test="not(MuxII) or not(pin17 | pin18 | pin19)"/>

to indicate that either MuxII must be absent, or pins 17, 18, and 19 must be absent.
Comment: **This is a good answer to my question** as well, but `` most easily resolves my particular issue. Thanks for your help!
Answer: This is only a sketch of your  XSD Schema:
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:complexType name="pininfo">
        <xs:attribute name="name" type="xs:string"/>
        <xs:attribute name="type" type="xs:string"/>
        <xs:attribute name="voltage" type="xs:string"/>
    </xs:complexType>

    <xs:complexType name="MuxIIinfo">
        <xs:sequence>
            <xs:element name="pin1" type="pininfo"/>
        </xs:sequence>
        <xs:attribute name="name" type="xs:string"/>
    </xs:complexType>

    <xs:complexType name="ArduinoDuoInfo">
        <xs:sequence>
            <xs:element name="pin1" type="pininfo"/>
            <xs:element name="pin16" type="pininfo"/>
            <xs:choice>
                <xs:sequence>
                    <xs:element name="pin17" type="pininfo" maxOccurs="1" minOccurs="0"/>
                    <xs:element name="pin18" type="pininfo" maxOccurs="1" minOccurs="0"/>
                    <xs:element name="pin19" type="pininfo" maxOccurs="1" minOccurs="0"/>
                </xs:sequence>
                <xs:element name="MuxII" type="MuxIIinfo"/>
            </xs:choice>
        </xs:sequence>
        <xs:attribute name="name" type="xs:string"/>
    </xs:complexType>

    <xs:element name="ArduinoDuo" type="ArduinoDuoInfo"/>

</xs:schema>

The interesting part is the <xs:choice>, which makes mutual exclusive the sequence pin17, pin18, pin19 with the presence of tag MuxII. Note that I have used minOccurs and maxOccurs to make pinXX tags optional.
Comment: This is exactly what I was looking for, the ability to define a choice between mutually exclusive element sequences. Thanks for your help.


Square root fraction confusion

Question: I was doing math for school and got to something that really confused me. With having the rule $\frac{2}{4} = \frac{4}{8}$ (or some simular fraction equation) in mind, I got to the following confusing equation:
$$\frac{\sqrt 3}{3} = \frac{(\sqrt{3})^2}{3^2} = \frac{3}{9} = \frac{1}{3}$$
This is really confusing me since $\frac{\sqrt{3}}{3}$  can never equal $\frac{1}{3}$. Where am I going wrong?
Answer: It is incorrect that $\frac{\sqrt3}3=\frac{\sqrt3^2}{3^2}$. A simple way of seeing this is because you can multiply both the top and the bottom of a fraction by the same number, but in this case, you are multiplying $\sqrt3$ to the top, and $3$ to the bottom, but $\sqrt3\ne3$, so they are different numbers. What you proved, instead, is that $\big(\frac{\sqrt3}3\big)^2=\frac13$, which is true.
Answer: $$\frac{\sqrt 3}{3} \ne \frac{(\sqrt{3})^2}{3^2}$$
In general $\dfrac a b \ne \dfrac{a^2}{b^2}$.  You can multiply both the numerator and the denominator by the same number, but not by different numbers.

Square root fraction confusion


NodeJS: How to fix different node module version?

Question: I'm trying to start a nodeJS application, but I do get the error
Error: The module '/Users/api/node_modules/bcrypt/lib/binding/bcrypt_lib.node'
was compiled against a different Node.js version using
NODE_MODULE_VERSION 46. This version of Node.js requires
NODE_MODULE_VERSION 57. Please try re-compiling or re-installing
the module (for instance, using `npm rebuild` or `npm install`).

I already run npm install and npm rebuild. But still the same error...
Comment: check a list of npm commands. Try npm update modulename
Comment: Please note that the answer here by robertklep is a much better answer than the one on the duplicate redirection page which suggests that you delete the entire node_module folder.
Answer: The bcrypt package needs to be rebuild, because it was initially installed with another version of Node.js.
Try this:
npm rebuild bcrypt --update-binary

for yarn users:
yarn add bcrypt --force

Comment: Tried this, didn't work. Still having warn `NODE_MODULE_VERSION 48. This version of Node.js requires
NODE_MODULE_VERSION 57`
Comment: @spaceman try reinstalling `bcrypt` in that case (or first uninstall, then install again).
Comment: If you use node nightly, it's not enough to copy the `node` binary to `/usr/local/bin/node`, but you need also to copy `lib/node_modules` and `include/node` to `/usr/local/lib/node_modules` and `/usr/local/include/node` respectively, where later is most important as its sets the new NODE_MODULE_VERSION when you build packages locally. After copying the files, make sure to wipe your node_modules from your project and reinstall _everything_.
Comment: @robertklep How to reinstall `bcrypt`? Doing `npm install bcrypt --save` does not help.
Comment: @SuhailGupta you have to be more specific, or perhaps even create a new question about the specific problem you're having.
Comment: Great working for me this solution.
Comment: If this fails, you can always do (the classic) `rm -f /node_modules && rm -f package-lock.json && npm i`. Bit of a sledgehammer to crack a nut, but it works.
Comment: I tried everything for this problem, completely wiping my node_modules and reinstalling, running `npm rebuild` multiple times, changing Node versions. Nothing worked, until I ran `npm rebuild my_module_name --update-binary`. So glad I found this answer!


Computationally complex irrational numbers

Question: Are there irrational numbers for which we know that computing its nth digit would take (at least) linear/polynomial/exponential/superexponential time (wrt to length of n and with "big enough" n)?
Answer: Sure there is. Just define an irrational number $x=0.r_1r_2r_3\ldots$ where $r_i$ is an integer computed in linear/polynomial/exponential/superexponential time (i.e. asymptotic to $O(i),O(i^n) $ etc).
For example, you can set $r_i$ is the number of subsets of $\{1,2,\ldots,i\}$ whose members sum to a prime number. (I have no idea what the time complexity of this is but I guess with a naive algorithm it would be $O(2^i)$). Then computing $n$ digits of $x$ is done in exponential time. Note that even if $r_i>9$ then just stick $r_i$ onto the end of the decimal expansion of $x$.
In order to make computing $n$ digits of $x$ exactly exponential time, you can change the previous definition to $r_i$ is the number of subsets of $\{1,2,\ldots,i\}$ whose members sum to a prime number, mod $10$. Then I'm pretty sure that as long as you're using the naive algorithm, the calculation is in exponential time.
Similar methods can be used to find irrational numbers that are calculated in any other time complexity.
Comment: Even before you get to that, you don't know that computation of $r_i$ is intractable, but you could probably work around that by choosing a known-intractable problem.  But to show irrationality requires only showing that $r_i$ is non-periodic, which might not be hard at all.
Comment: This is non-rigorous, but it would have to be a HUGE coincidence for my choice of $r_i$ to turn out to create a rational $x$. In any case, without a closed form solution for $r_i$ (I don't know if it is possible or not), one can never know if $x$ is rational or not. But looking at it, there seems to be nothing there that would cause periodicity.
Comment: I have no idea and in this particular case I'm pretty sure it won't be elementary. It may be more fruitful to find a better definition of $r_i$, which is clearly irrational and exponentially complex. I'm sure it won't be too hard. This example served more as an intuitive and off-the-top-of-my-head example.
Comment: @rank I don't quite understand what you mean. You are assuming that we may know that $\{r_i\}$ is periodic? Clearly, if we know that then $x$ is rational, but how can we tell for a sequence of exponential complexity whether or not it is periodic?
Comment: @rank Now I see what you mean. If we know that a problem is periodic, it is guaranteed to be computable in constant time (maybe a little worse if you need modulo). I guess what I meant is that in the answer that I gave, on would have to make sure that it is in fact non-periodic, both in order for $x$ to be irrational and for its decimal expansion to actually be complex enough.
Answer: I don't have a complete answer. But we should note first that there are irrational numbers for which computing the $n$th digit is impossible! See Wikipedia's Computable Numbers page.
We can prove this simply by counting. There are only a countable number of Turing Machines, thus a countable number of algorithms for computing irrational numbers. But there are an uncountable number of irrational numbers. So we cannot compute them all.
An example of an uncomputable number is Chaitin's constant.
But I don't have many good examples of irrational numbers along with time to compute them. There is a formula for the $n$th digit of pi but I'm not sure of the exact running time (edit: see Micah's comment below)~. That page also has similar formulae for e.g. $\ln(2)$.
Comment: The [irrationality measure](http://mathworld.wolfram.com/IrrationalityMeasure.html) of $\pi$ is bounded above by $8$, meaning that -- in the very worst possible case -- you only need to compute $8$ times as many digits as you already have to know what to do about rounding.


Azure Data flow new branch how data flow

Question: I have a source1 in the image below, i am creating a branch from the source1 and then in that I am doing join and then sink to skin1. my question is how the flow will work first it will completer the flow from sources1 to sink1 then it jumps to NewBrach"Source1" then join and skin, or it will run parallel
Run Sequential
Will it flow like 1->2>3->4->5>6
or
Run Parallel
Answer: It depends :)
It is non-deterministic and depends on whether ADF needs to block, waiting for any computation to complete in the other streams.
We are also working on adding UI gestures to control ordering.
For now, execute the data flow in a pipeline debug, then look at the execution plan using the eyeglasses icon to get a better idea of your parallelism.
Comment: Thanks Mark  :)  :)
Answer: Just an Update if someone following this post-Microsoft has released the custom Sink feature.
Thanks @Mark
please check the Link
https://learn.microsoft.com/en-us/azure/data-factory/data-flow-sink


What are in C++ types that cannot be copied?

Question: In the book "C++ Programming language" by Bjarne Stroustrup when talking about exceptions it says the following:

An exception is object thrown to represent the occurrance of an error.
  It can be of any type that can be copied but it is strongly
  recommended to use only user-defined types specifically defined for
  that purpose.

Reasoning about it I cannot immediately think of objects that cannot be copied.
What are types that cannot be copied in C++?
Comment: @user463035818 the context in which the question is asked doesn't make it a duplicate.
Comment: Possible duplicate: https://stackoverflow.com/questions/2173746/how-do-i-make-this-c-object-non-copyable
Comment: Types who's copy constructor has been deleted?
Comment: take iostreams as an example. It just does not make sense to copy an iostream, hence they are built such that you cannot
Comment: if you're looking for examples in the standard there's things like `std::unique_ptr`, `std::mutex` and `std::thread` are non-copyable.
Answer: To be copyable an object must define at least one of two possible ways of being copied:

copy assignment T& operator=(const T&)
copy constructor T(const T&)

If no one of these is defined or it has been explicitly deleted (= delete) then you can't copy the object.
The requirement arises from the fact that exception handling must be able to copy the exception object itself somewhere for proper management.
Comment: deleted or declared private (the only method in C++98)
Comment: @FrancescoBoi: refer to this for general behavior https://stackoverflow.com/questions/33096653/make-a-class-non-copyable-and-non-movable, you need to delete both operators to make it uncopyable and being movable is a different concept.
Comment: So I can use `delete` to delete the default copy constructor? Syntax is like this: `T(const T&) = delete;`? Do I have also to delete the copy assignment?
Comment: These must be done for both copy assignment and copy constructor or just one? What about C++11 move operators?
Comment: @Clifford: yes, actually making it private doesn't make it uncopyable. It makes the object uncopyable from outside code, but you're still allowed to copy it, eg: https://ideone.com/HpazXw
Comment: @Jack : Yes - good point; it is not semantically identical.  However it renders it uncopyable for the purposes of exception handling since it is not copyable by any means the exception handling will be aware of.  I think the Stroustrup text predates C++98 let alone C++11 when deleting member functions was not a thing in C++, so private membership would have been the method at the time.  Often code lasts longer than C++ standards, so I make the point only because the technique may bee seen in maintenance or written by dinosaurs like me who often see little reason to change.
Comment: I kind of take that back - the text in the pre-C++11 third edition does not mention the copyability of an exception object.  So the author will have had member deletion in mind perhaps.


How can I put my searchbox in to the top right corner?

Question: Hey I try to create a search function where I search to find my products in the list but now I have a little problem and that is that searchBox is not in the top of the corner right. I tried a lot of things but nothing happens. In the left corner there is my logo and I tried to put this to the right corner.
This is my search function:
function Navbar() {
  const [inputText, setInputText] = useState("");
  let inputHandler = (e) => {
    //convert input text to lower case
    var lowerCase = e.target.value.toLowerCase();
    setInputText(lowerCase);
  };
  return (

Shop

        <Product input={inputText} />
        <TextField
          id="outlined-basic"
          onChange={inputHandler}
          variant="outlined"
          label="Search"
        ></TextField>

  );
}

export default Navbar;

This is my css to this :
.navbar {
  width: 100%;
  height: 50px;
  background-color: rgb(32, 32, 32);

  .logo {
    color: aqua;
    font-size: 1.8rem;
    font-family: "Orbitron", sans-serif;
    line-height: 40px;
    margin-left: 20px;
  }

   .searchBox {
    color: aqua;
    font-size: 1.8rem;
    height: 1%;
    width: 100%;
    font-family: "Orbitron", sans-serif;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}

Comment: I will try it, I've never done it before @LeoDog896
Comment: @boredProjects I will check now
Comment: Can you try making a minimum reproducible example using StackOverflow snippets?
Comment: I didn't look too hard at your code but try something like

.searchBox{
  width:80%
}

Also try to put your code into https://codesandbox.io/ its a lot easier to help if you do.
Comment: @boredProjects it changes something but it did not set the search box to the corner..
Comment: @bull19 check out this https://codesandbox.io/s/stupefied-resonance-7klrr1?file=/src/styles.css. Set your position to relative and enter either an amount of px you want from the left or a percent you want from the center. I found setting left to 30% gave me pretty close to the top right.
Comment: @LeoDog896 I combined now my navbar.js with my search.js but it doesn´t change anything my searchBox is somewhere in the middle and the logo is in the corner left but I can´t put my searchBox into the right corner ...
Comment: @boredProjects look at my css code I changed it this way but now my logo is gone :)
Comment: Well, that's not valid CSS ([yet](https://caniuse.com/css-nesting)), so there's that...
Comment: Move `display: flex` down from `.searchBox` to `.navbar`
Answer: Maybe try display: flex, justify-content: space-between and width 100% on .navbar. Also remove width: 100% from .searchBox
Comment: Did this end up resolving the issue?
Answer: Try this!
.navbar {
      width: 100%;
      height: 50px;
      background-color: rgb(32, 32, 32);
      display: flex;
      align-items: center;
      justify-content: space-between;

      .logo {
        color: aqua;
        font-size: 1.8rem;
        font-family: "Orbitron", sans-serif;
        line-height: 40px;
        margin-left: 20px;
      }

       .searchBox {
        color: aqua;
        font-size: 1.8rem;
        height: 1%;
        font-family: "Orbitron", sans-serif;
        display: flex;
        align-items: center;
      }
    }


EdgeSync service cannot connect to this subscription because of error "The LDAP server is unavailable."

Question: I am in the middle of migrating Exchange 2010 to 2016.I've installed two Edge transport 2016 server in coexistence with 2010 one.Running Test-EdgeSynchronization after running New-edgesubscription command in Mailbox 2016 encounters EdgeSync service cannot connect to this subscription because of error "The LDAP server is unavailable.".Also event id 1024 appears in the event viewers.
Answer: My problem solved by adding an A record of edge server name (edg) in the forest primary domain dns server which its suffix also is my SMTP domain and the certificate for smtp in edge server is issued to edg.domain.com .As the mailbox server is located in a child domain (mailbox.child.domain.com) rather than forest primary domain (domain.com) it could not resolve edge.domain.com. Actually we need A record of edg in both domain.com and child.domain.com
Answer: Use following steps to resolve "LDAP server is unavailable" error:

Disable the Windows Firewall temporarily.
Use the "nslookup" command to verify DNS resolution and fix any discrepancies.
Make sure that all prerequisites for CU are installed or configured before starting the upgrade.
Test the connectivity to the AD Domain Controller using tools like AD Explorer or LDP.exe.
Enable GC on the LDAP or AD LDS server.
Hope it will fix the issue, Also refer this link for more information about LDAP Server is unavailable error.


Diophantine equation of $a^2+b^2=c^2+d^2$

Question: Is there a known solution to:
$$a^2+b^2=c^2+d^2$$
Hopefully the question is clear, if not I do apologize.
Comment: You can easily find all rational solutions using stereographic projection around an existing solution. It is far more difficult to write all primitive integer quadruples
Comment: $a=c$, $b=d$, or $a=d$, $b=c$. I'm sure I forget some other solutions :-J
Answer: There is a wonderful theorem concerning these kind of numbers:
If $a^2 + b^2 = c^2 +d^2 = E$, then there exist numbers $f,g,h,k$ such that $E= (f^2+g^2)(h^2+k^2)$.
There is a wonderful geometric proof of this. For example:
$$
50= 7^2 + 1^2 = (1^2+1^2)(3^2+4^2)
$$
I will not go into the details, but this equation was resoundingly solved by Ramanujan and other mathematicians, by using what are called the q-series, and not the diophantine equation itself. Hence I recommend you to look at these two pages:
1) http://mathworld.wolfram.com/SumofSquaresFunction.html (As a reference)
2)http://www.rowan.edu/colleges/csm/departments/math/facultystaff/osler/110%20SUM%20OF%20TWO%20SQUARES%20IN%20MORE%20THAN%20ONE%20WAY%20MACE%20Small%20changes%20Oct%2008%20%20Submission.pdf (Contains the geometric proof)
Comment: Solutions a parametized by $(a,b,c,d) = (p r + q s , q r - p s , p r - q s , p s + q r),$.
Answer: There are lots of solutions. One of them is $1^2+8^2=65=4^2+7^2$.
Comment: Thank you everyone for answers.However one last question, pie do you have any formula to come up with that you provided, 65, or is it a kinda a guess. I'm amateur so somehow cant grasp the theorems. You provided 1^2+8^2 and then the second part which is 4^2 +7^2. How would it work if i wanted to find 1^2 +9^2 = ????
Comment: I do not have a formula, but I am certain that there is one. EDIT: Check the other answer.


How to dynamically set selector to image in android?

Question: Hi i want to set selector to image through code. I have a selector which diff images for diff image view state . There is a way to set selector through xml file but i want to set it on button click .
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:state_pressed="false" android:drawable="@drawable/kanal_bogen_rund" />
<item android:state_focused="true" android:state_pressed="true" android:drawable="@drawable/kanal_bogen_rund_rollover" />
<item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/kanal_bogen_rund_rollover" />
<item android:drawable="@drawable/kanal_bogen_rund" />
</selector>

My Code is :-
img.setImageResource(R.layout.my_button);

Or there is any way to change image on focus/hover in android?
Please suggest me usable link or sample code.
Comment: http://stackoverflow.com/a/8518266/1012284
Answer: This selector depends on view's state.
For example set this view focused:
myView.requestFocusFromTouch();

and the first item with state_focused="true" will be used.
If you want to switch drawables programmaticaly then use Level List:
http://developer.android.com/guide/topics/resources/drawable-resource.html#LevelList


Android - Qual a diferença entre Bitmap e Drawable?

Question: Eu estou desenvolvendo um aplicativo que faz um CRUD para preencher informações na tela. Uma dessas informações são fotos.
Eu gostaria de saber melhor a diferença entre esses dois objetos para descobrir qual seria o mais correto a ser aplicado.
Comment: Relacionado: [Toda imagem no android deve ser tratada como um bitmap](https://pt.stackoverflow.com/q/145796/2541)
Answer: Drawable é algo que pode ser desenhado. Por exemplo. layout, imagem vetorial (linha, círculo), fonte, imagem e assim por diante
Bitmap - é um tipo específico de Drawable que é imagem, como: PNG, JPEG ou mais
Comment: Acredito que os Bitmaps do Android não sejam compactados. Eles podem vir de arquivos .jpeg ou .png mas seu formato na memória é o de "matriz de bits" descompactada.


Latin Hypercube around set points

Question: Is there a method for constructing a LHC around set points? For example, I want to test a component in a system and I have enough time to run 20 conditions. I expect that in the system, the component will experience conditions different 5 conditions (correlating to set points 1-5) the majority of the time. This leaves me with 15 points remaining which I would like to use as a LHC around points 1-5 to give me an idea of how it would operate.
I'm aware that I could ignore the 5 set points and run a LHC with the 15 samples points and accept that these won't be significantly different from the set points but this isn't particularly efficient. Is there a way to run a LHC around the 5 set points I have to test?
Thanks!
Answer: Yes. One method is outlined in a vignette for the R-package lhs. The example starts out with a Latin hypercube design and then augments the design with new points, but the same procedure would also work with an arbitrary set of points. Depending on where the original points are, you may or may not end up with a Latin hypercube overall.

Latin Hypercube around set points


Embedding Johnson Graph in $\mathbb{R}^2$

Question: Consider a Johnson graph $J(n,k)$ and denote its set of vertices by $V$ and its set of edges by $E$. Let $\bar{n}_k=\binom{n}{k}$. I am wondering whether there is a labeling $\{0,...,\bar{n}_k-1\}$ of its vertex set $V=\{v_0,...,v_{\bar{n}_k-1}\}$ such that when embedding the vertices at positions $v_l=(\cos(2\pi l\bar{n}_k^{-1}),\sin(2\pi l\bar{n}_k^{-1}))$ in $\mathbb{R}^2$ the set
$$C=\{x\in \mathbb{R}^2| x = t(\cos(2\pi l\bar{n}_k^{-1}),\sin(2\pi l\bar{n}_k^{-1}))+(1-t)(\cos(2\pi l'\bar{n}_k^{-1}),\sin(2\pi l'\bar{n}_k^{-1}))\text{ with }\langle v_l,v_{l'}\rangle\in E, t\in[0,1]\}$$
is invariant under rotations of degrees being multiples of $2\pi \bar{n}_k^{-1}$. The set $C$ is the circular layout used for example by the python networkx package to draw graphs.
Since Johnson graphs are distance transitive I should be able accomplish this but this is just an intuition. I thought about drawing it and I started by drawing a cycle with $n$ vertices and then tried to fill in the remaining edges to get a Johnson graph. Unfortunately this didn't give me an idea on how to approach the problem or even if it is always correct. In the end I want to know if there is always a rotation invariant layout for Johnson Graphs in $\mathbb{R}^2$ as shown on the wikipedia page (https://en.wikipedia.org/wiki/Johnson_graph) .
Any help is highly appreciated!
Comment: Oh, yes. Sorry, I adjust the post.
Answer: This is almost always impossible. (Some exceptions: $J(n,1)$ is just the complete graph $K_n$, so of course it has such an embedding.)
If you were able to do what you want, then a rotation of the diagram by $2\pi / \binom nk$ would be an automorphism of the Johnson graph $J(n,k)$. Because we can repeat this rotation $\binom nk$ times before getting back to where we started, this is an element of order $\binom nk$ in the automorphism group.
But the automorphism group is $S_n$ in most cases ($S_n$ acts on the vertices, which are $k$-subsets of $\{1, 2,\dots, n\}$) except when $n=2k$ (in which case taking the complement is another possible automorphism). For most values of $n$ and $k$, $S_n$ doesn't have an element of order $\binom nk$. (Moreover, the subgroup generated by this element must act transitively on the vertices, which is even harder.)
(Even the diagram of $J(5,2)$ you see on Wikipedia doesn't have $10$-fold rotational symmetry! This would be impossible, since $S_5$ has no elements of order $10$. Instead, the symmetry is only $5$-fold.)
You can get some amount of symmetry. For example, if $n$ is prime, we can always get $n$-fold symmetry. To do this:

Partition the $\binom nk$ points around the circle into parts of size $n$ so that each part is the vertex set of a regular $n$-gon.
Let $\sigma \in S_n$ be the permutation which maps $i$ to $i+1$ for $i<n$, and maps $n$ to $1$. If this acts on the vertices of $J(n,k)$ (which are subsets of $\{1,2,\dots,n\}$ by permuting the elements of $\{1,2,\dots,n\}$, then it's an automorphism of $J(n,k)$.
When $n$ is prime, for any vertex $v$ of $J(n,k)$, the orbit $\{v, \sigma v, \sigma^2 v, \dots, \sigma^{n-1}v\}$ has size $n$, and these orbits partition $V(J(n,k))$. So just put each such orbit on the vertices of one of the regular $n$-gon we found in step $1$, in clockwise order.

When we've done this, $\sigma$ acts on $J(n,k)$ by rotating the diagram we get by $\frac{2\pi}{n}$, so the diagram has $n$-fold symmetry.
(When $n$ is not prime, this fails because not all orbits have size $n$. For example, if $n=6$ and $k=2$, the vertex $\{1,4\}$ is part of an orbit $\{\{1,4\}, \{2,5\}, \{3,6\}\}$ with only $3$ elements. Of course, when $n=6$ and $k=2$, we can't possibly hope for $6$-fold symmetry, since there are $15$ points.)
Comment: Thank you, indeed the image on the Wikipedia page does not even satisfy what I was looking for.


Github - Allow Users To Open A Issue From My Github Page?

Question: How do I go about letting users open an issues from my Github page itself?
So I want it to work like users goes on my site http://example.github.io/ and click a button that says something like "Open an Issue" and have it take them to a form well sill on my site and once they submit it, it opens a issues with the info they entered.
Comment: SO is about people with problem with code
Comment: I want to know if somehow I can do this with somehow with code?
Comment: Unless you've already made an attempt to implement this yourself (and have a [mcve] of any problem code you're running into), this is probably more suited as a question for GitHub support instead.
Answer: One approach, described here, is to:

redirect the user to a Google Form
use App Script automation
call in that script the GitHub API to create an issue (POST /repos/:owner/:repo/issues)

For instance:
function onFormSubmit(e) {

  var itemResponses = e.response.getItemResponses();
  var item1 = itemResponses[1].getResponse();
  var item2 = itemResponses[2].getResponse();
  var item3 = itemResponses[3].getResponse();
  var item4 = itemResponses[4].getResponse();
  var item5 = itemResponses[5].getResponse();
  var item6 = itemResponses[6].getResponse();
  var item7 = itemResponses[7].getResponse();
  var item8 = itemResponses[8].getResponse();

  var title = "Bug: " + item2;

  var body =
      "Submitted By: " + item1 +
        "\nurl: " + item3 +
        "\ndevice: " + item4 +
        "\nbrowser: " + item5 +
        "\nexpected behavior: " + item6 +
        "\nactual behavior: " + item7 +
        "\nsteps to reproduce: " + item8;

  var payload = {
    "title": title,
    "body": body
  };

  var options = {
    "method": "POST",
    "contentType": "application/json",
    "payload": JSON.stringify(payload)
  };

  var response = UrlFetchApp.fetch("https://api.github.com/repos/EXAMPLE?access_token="+ghToken, options);
}


Flag count is incrementing only after page reload

Question: I have a views with like and unlike flag. When I click on like flag the count not increments. But when I reload the page, then only like's count will change. How can I solve this issue?
Note: I have already enabled ajax for my views.
Comment: The count going up on reload sounds like that is the views count incrementing from the statistics module. When you say Flag, are you referring to a specific module? A custom form?
Comment: Yes..Am using flag module in drupal8.
Comment: Do you have any suggestions to solve this issue?
Comment: Do you have ajax enabled?
Comment: yes..I have enabled in my view.
Answer: I had the same problem, and find how to solve it. The Views Flag Refresh module is only available for Drupal 7, but someone ported it to work on Drupal 8, here is the download link.
I find it in this issue comment by WalkingDexter.
In my case I need it to work on Drupal 9, so it is necessary to change a line in a file in the downloaded custom module as Akash_Daimari explains in this comment.
The module would go in /modules/custom/
In the view you have to use Ajax and add the flag in 'Flag refresh' options.
As a note, in the View preview the count does not update, but on the page it does.