If $x, y \in \mathbb{N^{*}}$, such that $\frac{x}{y}+\frac{y}{x} \in \mathbb{N}$, show that $x=y$.

Question: If $x, y \in \mathbb{N^{*}}$, such that $\frac{x}{y}+\frac{y}{x} \in \mathbb{N}$, show that $x=y$.
My try: If $x$ is a multiple of $y$, such that $x \neq y$, $\frac{x}{y}$ would be greater than $1$, and natural, while $\frac{y}{x}$ would be less than $1$, so not a natural number. Same if we swap $x$ with $y$. So, in those two cases, the given sum can't be natural.
I don't know how to continue it from here. Can you help me, please? Thanks!
Comment: @InterstellarProbe $2|4^2$ and $4|2^2$ but $4=2 ?$
Comment: @dezdichado, yes for $gcd(x, y) \neq 1$ it is false.
Answer: Let $q=\frac{x}{y}$, we want $q+\frac{1}{q}=n$ for some natural number $n$, or in other words $q$ is a rational root of $p(x)=x^2-nx+1$. Now by Rational root theorem, only possible values are $q=\pm 1$. Now it cannot be $-1$ since originally $x,y>0$. So we have $q=1$ and so $x=y$.
Answer: We have $$\frac{x}{y} + \frac{y}{x} = \frac{(x+y)^2}{xy} - 2 \in \mathbb{N} \iff \frac{(x+y)^2}{xy} \in \mathbb{N}.$$  Now, let $p$ be a prime dividing $x$, then $p | (x+y) \implies p \mid y$.  By symmetry, $x$ and $y$ share the same prime factors.  Now prove by contradiction that the primes occur to the same powers in $x$ and $y$...
Comment: @IulianOleniuc $p \mid x$ and $xy \mid (x+y)^2$ implies $p \mid (x+y)^2$ implies $p \mid x+y $ implies $p \mid y.$
Answer: Below is a solution by what is called the Vieta Jumping .
Assume $x>y$ and that $(x,y)$ is the pair such that $x+y$ is minimal. Then,  $x = yr+s, 0\leq s <y$ and
$$\frac xy+\frac yx = r+\frac sy +\frac{y}{yr+s} <r+1+1=r+2.$$
So it must follow that $\dfrac{s}{y}+\dfrac{y}{yr+s} = 1.\implies s^2+y^2+yrs = y^2r+ys\implies r = \dfrac{s^2-ys+y^2}{y^2-ys}=1+\dfrac{s^2}{y^2-ys}.$
Let $y=s+t.\implies ty|(y-t)^2\implies ty|y^2+t^2\implies \dfrac{t}{y}+\dfrac{y}{t}$ is integer and $t+y<2y<x+y$, a contradiction.
Comment: Did you want to write $\frac{s}{y}$ instead of $\frac{s}{r}$?
Comment: @IulianOleniuc yes that was a mistake, so I edited the solution.
Answer: There's lots of ways to prove it, but your approach works if you continue it.

If $x$ is a multiple of $y$

That's one case.  The other case you next have to check if $x$ is not a multiple of $y$.
Without loss of generality we can assume $x > y$ so $x/y = n + f$ for some natural number $n$ and fraction $0 < f < 1$.
$$n + f + \frac1{n + f} \in \mathbb N \iff f + \frac1{n + f} \in \mathbb N$$
Since both terms are less than $1$, it is to find:
$$f + \frac1{n + f} = 1$$
$$f = \frac{\pm \sqrt{n^2 + 2n - 3} - (n - 1)}{2}$$
Nothing that $\sqrt{\mathbb N}$ must either be a natural number or irrational
$$\sqrt{n^2 + 2n - 3} \in \mathbb N$$
but $n^2 < n^2 + 2n - 3 < (n+1)^2$ for $n > \frac 32$, so $n=1, f =0$ is the only solution.
Answer: $$\frac xy +\frac yx \to \frac{x^2+y^2}{xy}$$ which is only an integer when $x=y$
Comment: You still need to show that $\frac{x^2 + y^2}{xy}$ is only integer when $x = y$.


Pegar somente o trecho final após a barra com expressão regular

Question: Dei uma procurada geral aqui e no Google e cheguei a achar alguma coisa que funcionou parcialmente.
Possuo o seguinte padrão de texto:
030.000.208   OUTRA COISA
001.005.001   ALGUMA / COISA AQUI COM - TAMBÉM / GERAL.ASSINADA-COISA
040.001.218   OUTRA COISA / AQUI OUTRA/COISA GERAL
000.000.003   ALGUMA / COISA AQUI COM - TAMBÉM

Em resumo, o texto possui um padrão onde começa com uma sequência de números, três espaços em branco, um texto (que pode possuir pontuações), um espaço em branco, uma barra e um espaço em branco, outro texto (que pode possuir pontuações) etc.
O que preciso é que SOMENTE seja selecionado o texto que vem no final, após a última ocorrência do espaço-barra-espaço.
Seguindo o exemplo acima, o retorno para cada linha seria:
OUTRA COISA
GERAL.ASSINADA-COISA
AQUI OUTRA/COISA GERAL
COISA AQUI COM - TAMBÉM

Estou usando a seguinte expressão regular: \/ ([^\/]*)$
Ela está retornando isso:
GERAL.ASSINADA-COISA
COISA AQUI COM - TAMBÉM

Estou apanhando muito e não encontro solução, alguém pode dar uma luz?
Vou utilizar a expressão regular no Google Sheets.
Comment: Bom, sua primeira linha não tem o caractere / portanto não atende a expressão regular, e não entendi porque em sua terceira linha você espera "OUTRA/COISA GERAL" e não "AQUI OUTRA/COISA GERAL".
Comment: Corrigi o resultado esperado. foi erro de digitação.
Answer: Você disse que está usando o Google Sheets, mas não disse se o texto todo está na mesma célula. Na solução abaixo, estou assumindo que cada linha está em uma célula diferente (isso torna a solução mais simples, inclusive).

Uma alternativa é usar esta regex:
 ^\d{3}\.\d{3}\.\d{3}\s{3}(?:.*/ )?(.+)$

Os marcadores ^ e $ são, respectivamente, o início e fim da string. Assim eu garanto que só vou tratar as strings que seguem rigidamente este formato.
Depois temos \d{3}, que significa "3 dígitos" (o atalho \d corresponde a um dígito de 0 a 9, e o quantificador {3} significa "3 ocorrências"), seguido de \. (o caractere ponto). Como o ponto por padrão possui significado especial em regex (corresponde a qualquer caractere - exceto quebras de linha), ele precisa ser escapado com \ para que seja interpretado como um caractere comum.
Depois temos mais 3 dígitos, outro ponto e mais 3 dígitos, seguidos de \s{3} (3 espaços).
Depois disso temos (?:.*/ )?. Os parênteses com (?: formam um grupo de não-captura (e posteriormente entenderemos o motivo de usá-lo). O grupo todo é (?:.*/ ), que é .* (zero ou mais caracteres), seguido de barra, seguido de espaço (repare que há um espaço antes do )). E o ? logo depois torna todo este trecho opcional.
Ou seja, eu posso ter vários caracteres seguidos de barra + espaço, ou não. Isso serve tanto para o primeiro caso (que não tem nenhuma barra), quanto para os demais. E também me aproveito do fato do quantificador * ser ganancioso e tentar pegar o máximo possível de caracteres. Isso significa que a expressão acaba pegando até a última barra que seja seguida de espaço (que é exatamente o que queremos).
Em seguida temos (.+), que é .+ (um ou mais caracteres), dentro de parênteses, o que forma um grupo de captura.
A expressão completa que usei no Google Sheets é:
=REGEXREPLACE(A1, "^\d{3}\.\d{3}\.\d{3}\s{3}(?:.*/ )?(.+)$", "$1")

A função REGEXREPLACE pega o valor de uma célula (no exemplo acima é "A1"), aplica a regex e faz a substituição. No terceiro parâmetro, que indica a substituição a ser feita, eu usei a variável especial $1, que corresponde ao primeiro grupo de captura (no caso, o (.+)).
É por isso que usei um grupo de não-captura no trecho anterior, pois aí a regex não cria um grupo à toa (já que este não é usado na substituição).
O resultado é:
String original                                                       | Após REGEXREPLACE
----------------------------------------------------------------------|-------------------------
030.000.208   OUTRA COISA                                             | OUTRA COISA
001.005.001   ALGUMA / COISA AQUI COM - TAMBÉM / GERAL.ASSINADA-COISA | GERAL.ASSINADA-COISA
040.001.218   OUTRA COISA / AQUI OUTRA/COISA GERAL                    | AQUI OUTRA/COISA GERAL
000.000.003   ALGUMA / COISA AQUI COM - TAMBÉM                        | COISA AQUI COM - TAMBÉM

Você pode ver a planilha aqui, e a regex em funcionamento aqui.

Um detalhe é que o \s corresponde a vários caracteres, como espaço, TAB e quebras de linha (a lista exata pode variar de acordo com a linguagem/ferramenta - no caso do Google Docs, ele usa a engine RE2, cuja sintaxe pode ser consultada aqui). Se quiser que a regex considere somente espaços, pode mudar para:
=REGEXREPLACE(A1, "^\d{3}\.\d{3}\.\d{3} {3}(?:.*/ )?(.+)$", "$1")
                    tem um espaço aqui ^

Repare que agora, em vez de \s, há um espaço em branco antes do {3}.
Comment: Perfeito... funcionou exatamente como precisava... e as explicações de como está sendo tratado a expressão ficaram muito claras. Me ajudou muito e ainda aprendi mais sobre esse mundo de expressões regulares que eu apanho pra caramba pra entender...

Valeu!!!!
Answer: Boa tarde @ludo Man, vc precisa seguir exatamente esse regra?
"O que preciso é que SOMENTE seja selecionado o texto que vem no final, após a última ocorrência do espaço-barra-espaço"
se a resposta for sim essa regexp Que voce mostrou funciona " / ([^/]*)$ "
O seu exemplo esperado esta assim:
030.000.208   OUTRA COISA
001.005.001   ALGUMA / COISA AQUI COM - TAMBÉM / GERAL.ASSINADA-COISA
040.001.218   OUTRA COISA / AQUI OUTRA/COISA GERAL
000.000.003   ALGUMA / COISA AQUI COM - TAMBÉM
Mas para que a expressão funcione como quer o exemplo deveria estar assim:
030.000.208   / OUTRA COISA
001.005.001   ALGUMA / COISA AQUI COM - TAMBÉM / GERAL.ASSINADA-COISA
040.001.218   OUTRA COISA / AQUI OUTRA / COISA GERAL
000.000.003   ALGUMA / COISA AQUI COM - TAMBÉM
Pode verificar nesse link : https://regex101.com/r/7dtEZK/1
Comment: Obrigado pela resposta.... mas é exatamente este o problema.
Não consigo modificar a fonte, mas preciso que o resultado exibido seja o que exemplifiquei.


ng-click ou alternativa em jquery

Question: Preciso que, ao clicar na imagem thumb, escreva a imagem clicada na div .currentImage

Script

    .directive('galeria',function() {
return {
    templateUrl:'scripts/directives/galeria/galeria.html',
    restrict: 'E',
    scope:{
        'pasta':'@',
        'restrito':'@',
    },
    controller: function($scope,$http){
        // INICIAR CAROUSEL DA HOME
        $(".thumbsGaleria").owlCarousel({
            autoPlay:true,
            jsonPath: "api/galeria.php?id="+$scope.pasta,
            jsonSuccess: customDataSucesso,
            afterAction: afterFunction
        })
        function customDataSucesso(data){
            var content = "";
            for(var i in data){
                   var img = data[i];
                content += ''
             }
            $(".thumbsGaleria").html(content);
        }
        // FIM CAROUSEL

        function afterFunction(elem){
            var current = this.currentItem;
            var src = elem.find(".owl-item").eq(current).find("img").attr('src');
            $(".currentImage").html("");
        }

        $scope.currentClick = function(imgCurrent){
            $(".currentImage").html("");
        }

    }
}  });

HTML

Porém o NG-CLICK não funciona, ao clicar no item, não acontece nada.
tentei colocar um ONCLICK ao clicar o console retorna que a função especificada não existe.
Comment: @WilsonLavrador Quando você acha uma solução, coloque como resposta e aceite ela. Não coloque a resposta como parte da pergunta. Veja o [tour].
Comment: Qual é o problema?
Comment: Onde está o ng-click?
Comment: Alí na função customDataSucesso(data)
na var content
Comment: A sim, não havia notado.. Se você der um 'Inspect' no elemento depois da  página ter sido carregada, o ngClick aparece no elemento?
Comment: sim, aparece. porém, ao clicar não executa a função.
Comment: Acho que você não está passando o destino correto dentro do ngClick ou não está propagando a mudança. Verifique pelo inspect qual o src que é atribuído ao "currentImg" após o clique. Se houver alteração no src, verifique se está no destino correto
Comment: A questão não é que não está executando a função ao clicar no item com ng-click ...
Answer: PROBLEMA SOLUCIONADO
substitui a $scope.currentClick pelo script abaixo.
        $(".thumbsGaleria").on("click", ".owl-item", function(e){
            var imagem = $(this).find('img').attr('src');
            $(".currentImage").html("");
        });

Obrigado aos que deram atenção.

ng-click ou alternativa em jquery


Writing a specific dataframe column to a dictionary value without the associated index

Question: Edit: I found my answer here
python pandas dataframe columns convert to dict key and value
Original post:
I am attempting to write a specific dataframe column to a dictionary, yet I am also writing the index at the same time which I do not want. How do I do this the right way so I don't also include the index?
vi_dict = {}

vi_table_rvi = VI_table['RVI'].unique()

for d in vi_table_rvi:
    vi_dict[f'{d}'] = VI_table['AMT'].loc[(VI_table['RVI'] == d) & (VI_table['CD'] == 102)]

My dictionary output reads something like:
key: index   value
rather than
key: value
Thanks for any help.
Answer: You are storing a pandas series in that case, in which you have the index. If you want to store the values only, use the to_numpyfunction. It will store a numpy array with the values of the series.
vi_dict[f'{d}'] = VI_table['AMT'].loc[(VI_table['RVI'] == d) & (VI_table['CD'] == 102)].to_numpy()

Comment: Thanks for the teaching. I didn't realize this was a series until investigating with type(). I did find the answer I was looking for in this post though, which involves the dict() and zip() methods https://stackoverflow.com/questions/18012505/python-pandas-dataframe-columns-convert-to-dict-key-and-value
Comment: Perfect. Then I suggest that you edit your question to mention that you found the answer.


Keyboard + laptop or synthesizer?

Question: I am on a budget of about £150 and need a portable keyboard to take to gigs with both realistic-ish piano sounds and some synth sounds too.
I have a laptop but no keyboard, would it be best to get a midi/usb keyboard or some sort of synthesizer?
I would much prefer if the keys had some weight to them, because I am used to playing a real piano. Would this be possible on a budget?
Comment: Purely opinion-based, but keyboard & laptop, for me; as you then have a home studio when you're not on the road, with sequencer & sample library.
Comment: The M-Audio Keystation is semi-weighted and goes for about $200 US.
Comment: That's what I've got. logic for in the studio, Mainstage for live keyboards. It's a great setup!
Comment: My first thought is it depends on the kind of gig. Laptop and controller is flexible and powerful but I've played some gigs in beer soaked bars where I wouldn't want my laptop within five miles. If you have little to no setup time, no time for sound check, punk guitarists jumping around onstage, a crazy drummer, and/or lots of alcohol involved, I'd be looking more for a cheap synth with a decent piano sound.
Answer: Based on your question I'd recommend a keyboard controller and a midi-connected laptop.
You can choose the key action you prefer and you can achieve many different sounds via software.
Regarding keyboard action;  I'm more concerned with good dynamic detection and snap-back but you may be most interested in key weight.  I've played a lot of piano but piano action is often a bit sluggish for my taste.
Also consider that you'll need to protect the laptop and give some thought to how you'll set everything up so that you'll be less likely to knock it over.  Sounds obvious, but very important.
Answer: Look for a second-hand electric piano with some other sounds.  A laptop is nothing but a nuisance on a gig.
Answer: SP5500. Branded under at least 4 different names, Thomann sell it. 88 note, not too bad action, loads of sounds. More than £150, I'm afraid, but probably the cheapest half decent 'board for the money. Try Ebay.

Keyboard + laptop or synthesizer?


How to stop responding the intent filter in Android

Question: I have added intent-filter in AndroidManifest.xml file in the following way,
<intent-filter>
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />
    <data
       android:scheme="upi"
       android:host="pay" />
</intent-filter>

And suppose the intent call initiated from the merchant end and I want, this mobile app should not be listed from the installed apps list for the below scenario:

The customer not registered and just downloaded app from the playstore.

So, please suggest me how shall I add above intent filter dynamically from android activity?
Answer: Assuming it's an activity which has the intent filter: You can enable or disable the activity:
You can disable it by default in the manifest:
<activity
    android:enabled="false"
    ...>
    <intent-filter ... />
</activity>

To enable it programmatically:
val componentName = ComponentName(context.applicationContext, MyActivity::class.java)
context.packageManager.setComponentEnabledSetting(
        componentName,
        PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
        PackageManager.DONT_KILL_APP)

To disable it programmatically:
context.packageManager.setComponentEnabledSetting(
        componentName,
        PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
        PackageManager.DONT_KILL_APP)

Reference: setComponentEnabledSetting documentation: https://developer.android.com/reference/android/content/pm/PackageManager.html#setComponentEnabledSetting(android.content.ComponentName,%20int,%20int)


KineticJS Example Needed: Gradient Fill with Rect?

Question: I haven't gotten gradient fill working with KineticJS rect objects yet. Here's my code:
var width = 500;
var height = 20;
y = y + 20;
var rect = new Kinetic.Rect({
    x: centerOfCanvasX - (width / 2),
    y: y,
    stroke: '#000',
    strokeWidth: 1,
    fill: '#fff',
    width: width,
    height: height,
    fillLinearGradientStartPoint: [10, 0],
    fillLinearGradientEndPoint: [400, 0],
    fillLinearGradientColorStops: [0, 'red', 300, 'yellow']
});
mainLayer.add(rect);

What am I missing?
Thanks very much in advance to all for any info!
Answer: Looks like problem is here:
fillLinearGradientColorStops: [0, 'red', 300, 'yellow']

Values shoud be from 0 to 1.
fillLinearGradientColorStops: [0, 'red', 1, 'yellow']

example: http://jsfiddle.net/lavrton/DVzeE/


Most number of drivers penalised prior to a race starting

Question: At the 2022 Italian GP at Monza, 9 racing drivers (Verstappen, Perez, Ocon, Bottas, Magnussen, Schumacher, Sainz, Hamilton, Tsunoda) were issued with grid penalties, to varying degrees, altering the starting grid for the race.
Is this the most amount of penalised drivers on a starting grid?
For clarification, I am looking for the number of drivers penalised, not the total number of penalties applied (e.g. Tsunoda had three separate penalties applied at this race weekend).
Answer: Couldn't find a race with more grid penalties, but found another race that matched the number of penalised drivers (9):
2017 Italian Grand-Prix: 9 grid penalties were awarded in total:

Max Verstappen
Daniel Ricciardo
Stoffel Vandoorne
Sergio Pérez
Nico Hülkenberg
Fernando Alonso
Carlos Sainz Jr.
Jolyon Palmer
Romain Grosjean

So I think it's safe to say that 9 grid penalties is the maximum number of grid penalties in a single race, especially given they have only become relevant since the start of the turbo hybrid era in 2014 (despite being around since 2004), so the time window within which many grid penalties could have been handed out is quite small.
An interesting record though for the driver with the most penalties is Jenson Button who got a 70-place grid penalty at the 2015 Mexican Grand-Prix, back when changing each engine component gave a set amount of grid place penalties, whereas today it's just a "back of the grid" penalty for a full engine change.


Exact value of a sum involving harmonic numbers

Question: Could somebody tell me the exact value of this series?
$$
\sum_{k=1}^{\infty} (-1)^k\frac{H_k^{(5)}}{k}
$$
where
$$
H_k^{(n)}=\sum_{i=1}^{k}\frac{1}{i^n}
$$
Thanks!
Answer: Hint. You may write
$$
\sum_{k=1}^{\infty} (-1)^k\frac{H_k^{(5)}}{k}=\sum_{k=1}^{\infty} (-1)^k\frac{H_{k-1}^{(5)}}{k}+\sum_{k=1}^{\infty} \frac{(-1)^k}{k^6}=\zeta(\bar{1},5)-\frac{31 \pi ^6}{30240}.
$$
I am not sure the Multi Zeta Values $\zeta(\bar{1},5)$ has a closed form in terms of known constants.
Answer: Denote ${\bf H}^{(q)}_n(t) := \sum\limits_{m=1}^\infty H_m^{(q)}/m^n \cdot t^m$. By using the formula on the bottom of the answer to Calculating alternating Euler sums of odd powers we have:
\begin{equation}
{\bf H}^{(5)}_1(t) = Li_6(t) + Li_1(t) Li_5(t) - Li_2(t) Li_4(t) + \frac{1}{2} [Li_3(t)]^2
\end{equation}
Since $Li_n(-1) = (1-2^{n-1})/2^{n-1} \zeta(n)$ the result is expressed through zeta functions only.


Quando devo inativar ou excluir um registro? Boas práticas de banco de dados

Question: Estou com a seguinte dúvida:
Quando devo inativar um registro?
Quando devo excluir um registro?
No caso gostaria de uma dica de boas práticas, em quais tabelas compensa eu criar uma coluna STATUS? Sendo as tabelas que tiver essa coluna STATUS irei fazer um UPDATE para alterar a situação para ativo ou inativo e as que não tiverem essa coluna eu utilizarei o DELETE para deletar.
Tabelas que contém o meu banco mysql:
USUARIO, CLIENTE, COLABORADOR, FORNECEDOR, ORCAMENTO, ORDEM DE SERVICO, PEDIDO DE VENDA, PRODUTO, SERVICO.
Comment: Não existe boa prática, depende do que é relevante para o seu cliente. Se pra ele é importante manter um rastro ou histórico de itens removidos, nunca apague nada de nenhuma tabela.
Comment: Entendi. Obrigado pela explicação.
Answer: Remover Dados não é uma Prática Recomendada
A remoção de uma linha ou uma entidade raramente é simples. A operação afeta não somente os dados do modelo mas também a sua forma. É por isso que utilizamos chaves estrangeiras, para garantir que os itens de uma OrdemDeCompra não fiquem sem uma OrdemDeCompra associada. E esse é o caso mais simples. …
Quando trabalhamos com remoções lógicas, é fácil chegar em situações onde temos dados corrompidos já que a UltimaOrdem de um Cliente (uma simples otimização) poderá apontar para uma OrdemDeCompra que foi removida logicamente.
Digamos que nosso departamento de marketing decide remover um Produto do catálogo. Devemos então remover todas as Ordens de Compra que contém esse Produto? Devemos também remover todas as Faturas relacionadas a essas ordens? Indo mais além, devemos recalcular os lucros da empresa?
Que ninguém deixe ele fazer isso.
Na verdade, 'remover'' um Produto significa que ele será descontinuado. Nós não queremos mais vender essa linha de Produtos. Nós queremos nos livrar do estoque que temos e nunca mais comprar de nosso fornecedor. O produto não deverá aparecer em pesquisas de usuários, mas o pessoal do almoxarifado ainda tem que gerenciar esses itens. De qualquer forma é muito mais fácil dizer apenas 'remover'.
Ordens de compra não são removidas - elas são canceladas. Pode haver inclusive a incidência de alguma taxa se a ordem for cancelada muito tarde.
Colaboradores não são removidos - eles são demitidos (ou se aposentam). A rescisão também poderá ser tratada no sistema.
Vagas não são removidas - elas são preenchidas.
Em todos os casos devemos focar na tarefa que o usuário deseja executar ao invés da ação técnica que deverá ser executada em uma entidade. Em quase todas as situações, mais de uma entidade será levada em consideração.
O mais correto em todos os casos é a criação de um campo que permita saber em que estado a informação atual está, assim nunca será perdido nenhum dado, permitindo em um futuro ser analisado para alguma possível tomada de decisão.
Dados são de extremo valor em qualquer negócio, principalmente os relacionados com TI, sempre os mantenha guardado.
Comment: A não ser que você precise cumprir com políticas de segurança e privacidade de dados e seja obrigado por lei ou contrato a remover determinadas informações quando o usuário desejar. :S
Comment: Sim, nesses casos não há o que fazer e a deleção é a única alternativa.
Answer: Para complementar o tema, gostaria de apontar algumas razões para se decidir por remover os dados do banco ao invés de desativar os respectivos registros:

Um sistema onde os dados históricos representariam um volume inaceitável em termos de espaço ou desempenho e, portanto, precisam ser expurgados da tabela. Uma alternativa nesse caso é manter tabelas históricas ou mesmo confiar no backup.
Evitar mais um nível de complexidade nos relacionamentos, pois é um custo adicional escrever em cada query ou junção uma cláusula para testar o estado do registro, fora o risco de se esquecer de fazer isso. Além disso, se a ideia é não permitir a perda de dados, as alterações no banco de dados também deveriam sempre gerar novos registros. Alguns cenários que lidam com dados históricos dessa natureza são bem complexos, tais como quando você precisa consultar registros e seus os relacionamentos em diferentes momentos.
Segurança e privacidade muitas vezes exercem um papel importante sobre essa questão. Em muitos casos o usuário precisa ter uma função para expurgar definitivamente informações sigilosas, ou mesmo porque ele tem o direito de fazer isso. Nem sempre é uma funcionalidade disponibilizada diretamente para o usuário, mas muitas empresas tem inevitavelmente que implementar algum mecanismo para lidar com essa situação. Aqui no SO mesmo algumas vezes os usuários postam dados como senhas ou chaves privadas e os desenvolvedores precisam deletar a informação, algo que não é disponível para os usuários normais nem para os moderadores.

Concluindo, embora fosse ideal sempre manter todo o histórico dos dados, nem sempre isso é viável. Mesmo quando alguma implementação é feita via sistema, é sempre bom ter um sistema de backups confiável.


Fetching distinct rows from multiple joins SQL

Question: I have one main table called deliveries and it has one to many relationship with deliveries_languages as dl, deliveries_markets dm and deliveries_tags dt having delivery_id as foreign key. These 3 tables have one to one relation with languages , markets and tags respectively.  Additionaly, deliveries, table have one to one relation with companies and have company_is as foreign key. Following is a query that I have written:
SELECT deliveries.*, languages.display_name, markets.default_name, tags.default_name, companies.name
FROM deliveries
JOIN deliveries_languages dl ON dl.delivery_id = deliveries.id
JOIN deliveries_markets dm ON dm.delivery_id = deliveries.id
JOIN deliveries_tags dt ON dt.delivery_id = deliveries.id
JOIN languages ON languages.id = dl.language_id
JOIN markets ON markets.id = dm.market_id
JOIN tags ON tags.id = dt.tag_id
JOIN companies ON companies.id = deliveries.company_id
WHERE
deliveries.name ILIKE '%new%' AND
deliveries.created_by = '5f331347-fb58-4f63-bcf0-702f132f97c5' AND
deliveries.deleted_at IS NULL
LIMIT 10

Here I am getting redundant delivery_ids because for each delivery_id there are multiple languages, markets and tags. I want to use limit on distinct delivery_ids. So, limit 10 should not give me 10 records from above join query but 10 records where there is distinct delivery_id (deliveries.id). I probably can use derived table concept here but I am not sure how can I do that. Can someone please help me to resolve this issue.
Comment: Which dbms are you using?
Comment: How to chose these 10 rows per delivery_id? (Keeping several languages seems a bit odd.)
Comment: I am using postgreSQL
Comment: Basically I want to do group by on deliveries.id. It is possible using subquery but I dont know how can i do that
Answer: In Postgres, you can use distinct on:
SELECT DISTINCT ON (d.id) d.*, l.display_name, m.default_name, t.default_name, c.name
FROM deliveries d JOIN
     deliveries_languages dl
     ON dl.delivery_id = d.id JOIN
     deliveries_markets dm
     ON dm.delivery_id = d.id JOIN
     deliveries_tags dt
     ON dt.delivery_id = d.id JOIN
     languages l
     ON l.id = dl.language_id JOIN
     markets m
     ON m.id = dm.market_id JOIN
     tags
     ON t.id = dt.tag_id JOIN
     companies c
     ON  c.id = d.company_id
WHERE d.name ILIKE '%new%' AND
      d.created_by = '5f331347-fb58-4f63-bcf0-702f132f97c5' AND
      d.deleted_at IS NULL
ORDER BY d.id
LIMIT 10;

For larger amounts of data, this can be very inefficient.  Multiple junction tables result in Cartesian products when used like this.  However, for a smallish amount of data, this should solve your problem.
Comment: This is working for me. But you said performance would hamper. Is it because of multiple joins or because of DISTINCT ON clause? Also, is it more efficient than using subquery?
Comment: @NilakshiNaphade . . . It is because the joins are producing a Cartesian product across different dimensions . . . for a given delivery, the intermediate results is the number of languages times the number of markets times the number of tags.


Simplify formula $e^{-i0.5t}+e^{i0.5t}$

Question: I want to ask, how can I simplify this formula ?
$ e^{-i0.5t}+e^{i0.5t} $
I know that it can be simplify to $\cos(0.5t)$, but I don't know how :/
Comment: $\exp(\pm it)=\cos\;t\pm i\sin\;t$
Comment: In view of my answer below, note that $\cos(-x)=\cos(x)$ and $\sin(-x) = - \sin(x)$.
Answer: Use $e^{ia}  = \cos a + i\sin a$, and find that the answer is slightly different from what you wrote.
Answer: By the Euler's formula
$$e^{ix}=\cos x+i\sin x$$
for $x=-0.5t$ , we obtain
$$e^{-0.5t}=e^{i\left( -0.5t\right) }=\cos \left( -0.5t\right) +i\sin \left(
-0.5t\right) $$
and for $x=0.5t$,
$$e^{0.5t}=\cos \left( 0.5t\right) +i\sin \left( 0.5t\right) .$$
Since $\cos$ is an even function and $\sin$ an odd function, we obtain
$$\begin{eqnarray*}
e^{-0.5t}+e^{0.5t} &=&\cos \left( -0.5t\right) +i\sin \left( -0.5t\right)
+\cos \left( 0.5t\right) +i\sin \left( 0.5t\right)  \\
&=&\left( \cos \left( -0.5t\right) +\cos \left( 0.5t\right) \right) +i\left(
\sin \left( -0.5t\right) +\sin \left( 0.5t\right) \right)  \\
&=&\left( \cos \left( 0.5t\right) +\cos \left( 0.5t\right) \right) +i\left(
-\sin \left( 0.5t\right) +\sin \left( 0.5t\right) \right)  \\
&=&2\cos \left( 0.5t\right) +i\cdot 0 \\
&=&2\cos \left( 0.5t\right)
\end{eqnarray*}$$
Answer: The more general answer to that is:
\begin{align}
\forall x \in \mathbb{R},\  \cos(x) & = \frac{e^{ix} + e^{-ix}}{2} \\\\
\sin(x) & = \frac{e^{ix} - e^{-ix}}{2i}
\end{align}
These equations can in turn be obtained by summing and subtracting the following two equations:
\begin{align}
\forall x \in \mathbb{R},\  e^{ix} & = \cos(x) + i\sin(x) \\\\
e^{-ix} & = \cos(x) - i\sin(x) \\\\
\end{align}

Simplify formula $e^{-i0.5t}+e^{i0.5t}$


Prove that the following formula is true for $n \geq 1$ by induction

Question: Prove that the following formula is true for $n \geq 1$ by induction.
$a_{n} = a_{n-1} + 4n - 3 \\ a_{n} = 2n^{2} - n + 1 \\ a_{1} = 2$
My attempt follows below. I almost succeed in proving the formula for $n \geq 2$, but I fail (more specifically, I fail when I try to prove the formula for $n = k + 1$ and also, I do not know how to prove it for $n \geq 2$. Here is my attempt:

Let $n = 2 \\ 2 + 2*4 - 3 = 7 (a) \\ 2*2^{2} - 2 + 1 = 7 (b) \\ (a) = (b) \space QED$
Suppose the formula is true for $n = k$, which gives us:
$ \\ a_{k-1} + 4k - 3 = 2k^{2} - k +1 \\$ This leads to the formula being true for $n = k + 1$: $a_{k+1-1} + 4(k+1) -3 = 2(k+1)^{2} - (k+1) + 2$

$ RHS = a_k + 4k -2 \\ LHS = 2(k^2 + 2k + 1) - k - 1 + 1 = 2k^2 +4k+2-k=(2k^2 - k +1) + 4k +1 =^{*} a_{k-1} + 4k -3 +4k+1 = a_{k-1} + 8k -2  $
From the above you see that RHS is not equal to LHS... What am I doing wrong? And when it has been shown that RHS = LHS, how does one continue to show that the formula is true not only for $n \geq 2$ but also for $n \geq 1$?
*is where I use the assumption from (2)
Answer: For $n=1$
$2(1)^2-1+1=2=a_1$.
Assume this holds for $k$, that is $a_k=2k^2-k+1$
Now,
$a_{n+1}=a_{n}+4(n+1)-3$
$=2n^2-n+1+4(n+1)-3$
$=2n^2+4n+2 -n$
$=2(n+1)^2-n$
$=2(n+1)^2-(n+1)+1$
The argument follows by induction.
QED.
Answer: I find working with $n$ is better with $k$. So: $$a_n = a_{n-1} + 4n-3=2(n-1)^2-(n-1)+1+4n-3=2n^2-4n+2-n+2+4n-3=2n^2-n+1$$.


Trying to to display form in template

Question: I'm trying to display a form in a template (not my first choice, but I'm restricted in what I can do here) and I'm having some trouble figuring out how to do it.
I'm trying to tie into the Ubercart Addresses module to allow the user to select from one of the countries available to them.
I believe this information is located in uc_addresses_get_address_form
What I'm trying to do is as follows:
<?php  print render(drupal_get_form('uc_addresses_get_address_form'))?>

But this doesn't seem to add the form information I want.
How do I get this information into a template file?
Answer: Something like the following should work:
drupal_render(drupal_get_form('uc_addresses_get_address_form'))

Check Render form in template
Comment: Isn't render() just a wrapper for drupal_render()?
Comment: And no, putting this in my template.php did not work.
Comment: What is it giving you? Have you included the file with the form?

Trying to to display form in template


How to create a priority queue of pairs in c++. Which pops the element with min value. The default one pops max

Question: priority_queue < pair < long long int,pair <long long int ,long long int > > > pq;

In this line of code, I want to form a priority_queue on the basis of the first long long int.
The queue pops the min. element.
Comment: `std::priority_queue, std::vector>, std::greater>>`
Answer: The std::priority_queue template allows you to specify a type that meets the compare requirement:
typedef mypair pair<long long int, pair<long long int, long long int> >;
std::priority_queue<mypair,
                    std::vector<mypair>,
                    std::greater<mypair> > pq;

If all you need is to reverse the order you can std::greater rather than the default std::less. In cases that require a more complex compare function you can implement your own.


Which correlation test should I use? ANOVA? PCA? Other?

Question: I have the following problem and some help would be wonderful.
I have 50 origins for tree seeds. Each origin has several recorded climate variables like average temperature, precipitaion, wind etc.
After a few years of experienting I have an averaged "bud break"-point in time like "day 109.87" for each origin group.
Now I would like to know if there are any correlations between these bud break points and any of the associated climate variables.
Hopefully I was able to name all the relevant aspects of this problem.
Which test should I use for this? Can anyone help me out?
Answer: If you expect that at least some of those climatic variables are driving differences bud break time, why not do a regression analysis with bud break time as the response?
Answer: Linear Models (or Generalized Linear Models, depending on the distribution of your variable Point in time) with Point in time as predicted variable and your different climatic variables (quantitative and qualitative) as predictors would be a good start I believe. It will allow you to determine which climatic variable has an effect on the bud break and how much this bud break depends on the predictors.


Java - parseInt()

Question: public void OK(View v)
{
    EditText editTextView = (EditText) findViewById(R.id.editTextView);
    String myEditValue = editTextView.getText().toString();
    int equação = Integer.parseInt(myEditValue);
    editTextView.setText(equação + "CERTO!");}

Dá erro quando existem caracteres do tipo "(" ou "+" etc. Existe alguma forma de os reconhecer?
Comment: Vc está dizendo que dá erro dentro do setText?
Comment: O erro é esse `;` ai depois que fecha o parênteses, não precisa dele
Comment: Tem que ficar assim `editTextView.setText(equação + "CERTO!") `
Comment: Amigo o erro ocorre porque se ter um ( ou então + ou qualquer outro caracter não reconhecerá como um inteiro, na conversão
Comment: Anderson Henrique , há então alguma maneira de reconhecer por exemplo isto " (6*2)+7+5 " tudo como um int ?
Comment: Não. Tem de fazer split e parse de de cada parcela individualmente e fazer as operações entre cada coisa. Ou utilizar uma biblioteca para o efeito
Comment: Você está tentando implementar uma "Calculadora de String". Isto não é suportado diretamente pela linguagem e, como o Isac disse, você terá de efetuar todo o parsing da String manualmente e, após, efetuar os cálculos, considerando precedência de operadores e etc. Você pode procurar algo pronto ou pesquisar tutoriais na Internet, já que este é um 'exercício' comum.
Comment: Vou tentar procurar a ver se consigo o efeito que desejo. Eu inicialmente achei que era bastante simples, bastava o parsing de toda a string, mas depois deparei me com esse erro. No resto do meu código existe uma série de equações que utilizam esses caracteres e não tive problema nenhum, isto porque sempre trabalhei com int's. Assim ou arranjo outro método pra obter as equações ou tenho q fazer como vocês disseram.
Vou experimentar a ver
Obrigado pela ajuda
Answer: Ache isso no fórum, e achei interessante!
Não sei se vai funcionar, mas não custa você tentar aí!
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;

ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String infix = "3+2*(4+5)";
System.out.println(engine.eval(infix));

Espero que ajude! :D
Link da solução
Comment: @Eduardo Brito, apenas tome cuidado onde vai usar isso, pois é extremamente inseguro. Ele pode executar também qualquer função que o Java consiga, como ler e escrever em arquivos na máquina.
Comment: Eu simplesmente não consigo importar... Mas penso que essa seria mesmo a solução
Answer: Há três formas bem simples de resolver:
1) Adicione o atributo abaixo em seu EditText e evite caracteres indesejados:
android:inputType="number"

2) Utilize os métodos da própria classe String:
EditText editTextView = (EditText) findViewById(R.id.editTextView);
String myEditValue = editTextView.getText().toString();

//Removendo caracteres indesejados
myEditValue.replace("(", "");
myEditValue.replace("+", "");

int equação = Integer.parseInt(myEditValue);
editTextView.setText(equação + "CERTO!");

3) Pesquise um pouco sobre Regex, que é uma String utilizada para validar outras Strings e se o usuário inserir um caractere indesejado, mostre uma mensagem a ele. Existe o método da classe String mEditValue.replaceAll(String regex, String substituta), que com o Regex evita que você use o passo 2 para todos os casos.
Boa Sorte.
Comment: isto não vai funcionar simplesmente  :/ mas obrigado pela ajuda na mesma

Java - parseInt()


htaccess settings to allow access to special non-drupal page

Question: I have a properly working Drupal 6 site, at the webroot of my server, which can be accessed by www.mysite.com or by mysite.com. I have some special html files (not part of Drupal) that can be currently accessed by going to mysite.com/special and that works fine.
I would prefer that people just go to special.mysite.com to get to the html files in that directory (instead of mysite.com/special).   I just had the DNS set up so that special.mysite.com now points to the webroot, and Drupal currently handles it the same as www.mysite.com.
However, I would like it if people coming to special.mysite.com arrive at the index file within the "special" folder on mysite.com. I bet I can do something to the .htaccess file that Drupal uses in the webroot directory - but I don't know what? Any advice? Thanks a ton.
Answer: add in your .htaccess.

RewriteCond %{HTTP_HOST} ^special.mysite.com$
RewriteRule ^/?$ "http\:\/\/mysite\.com\/special" [R=301,L]
Comment: find in your Drupal htaccess the place to put this after RewriteEngine on. Remember that little bad changes in your .htaccess will pull down your site.
Comment: That worked OH SO perfectly. Thanks a ton for your help.


Where does the delta method's name come from?

Question: Where does the delta method's name come from?
I don't see anything related to "$\epsilon$-$\delta$", nor Dirac delta for example.
Comment: https://www.merriam-webster.com/dictionary/delta
Comment: Delta-method is closely related (sometimes synonym) to the concept of propagation of error, e.g. see [this](http://math.arizona.edu/~jwatkins/K2_clt.pdf). The name follows probably from the fact that $\delta$ and $\Delta$ are used to denote error in calculus.
Comment: @Francis So does it come from Taylor series? Since it has that error term?
Comment: @mavavilj: could be, but I haven't found a source to confirm this.
Comment: @Francis Indeed, Taylor series, see my answer edit.
Answer: The name "Delta" is from the symbol $\Delta$ for "change" which is used in limit expressions like let $\Delta X_i\rightarrow 0$, where $\Delta X_i=X_{i+1}-X_i$, and also $\Delta$ or lower case "δ" refers to an inexact, non-zero differential equation (i.e., before limits are taken) which reduces in the limits to a differential equation the latter using infinitesimals. For example, $\Delta f(x)= f(x+\Delta x)-f(x)$, which reduces to $\partial f$, a vanishingly small differential, for $\Delta x$ sufficiently small. Now sometimes we want to manipulate equations so that we are not dividing or multiplying by zeros, and in that case, we might use the $\Delta $ notation.
The name delta method, is probably only used by statisticians. In other contexts, e.g., engineering, physics, it would be more commonly referred to as propagation of error. To see how the error propagation includes the $\Delta$ symbol, see propagation of error.
<code> Edit
</code>
Error propagation is from Taylor series, useful examples. Indeed, when extended to the first two derivatives of Taylor series, i.e., $\mathbf{Var}[Y]\approx(g'(\mu_X))^2\sigma_{X}^{2}+g'(\mu_X)g''(\mu_X)\mu_3+\frac{1}{4}(g''(\mu_X))^2(\mu_4-\sigma_{X}^{4})$, it becomes more accurate, and I would venture that that is needed when the solution space curvature is of greater magnitude.
BTW, in ancient Greek the letter $\Delta$ was pronounced as a "d" sound and in modern Greek this is a hybrid "d" and "th" sound. The etymology is purported to be as follows,
c. 1200, Greek letter shaped like a triangle, equivalent to our "D," the name from Phoenician daleth "tent door." Herodotus used it of the mouth of the Nile, and it was so used in English from 1550s; applied to other river mouths from 1790.


SQL to Linq query with multiple left outer joins

Question: I'm trying to convert an SQL query to Linq containing several left outer joins, but I'm encountering an odd situation.
The relevant part of my SQL is:
SELECT * FROM dbo.SessionDetails as sd
    left outer join dbo.VoipDetails as vd on vd.SessionIdTime = sd.SessionIdTime and vd.SessionIdSeq = sd.SessionIdSeq
    left outer join dbo.Gateways as fgw on vd.FromGatewayId = fgw.GatewayId

My Linq query so far is:
var query = from sd in dbo.SessionDetails
    join vd in dbo.VoipDetails on new { sd.SessionIdTime, sd.SessionIdSeq } equals new { vd.SessionIdTime, vd.SessionIdSeq } into sdvd
    from v in sdvd.DefaultIfEmpty()
         join fgw  in dbo.Gateways on vd.FromGatewayId equals fgw.GatewayId   into sdgw
         from g in sdvd.DefaultIfEmpty()
             select sd;

I'm getting an error mark on vd.FromGatewayId telling me that The name 'vd' is not in scope on the left side of 'equals'.  Consider swapping the expressions on either side of 'equals'.
However, if I do swap sides with gw.GatewayId then  I get the same error message for both vd and gw.
Can someone suggest the correct syntax here?
Please bear in mind I have several more left-joins to add after I get the basic syntax down.
Answer: I believe the issue is that you are trying to access a value that has no scope in the query.  I believe the reason for this is that you specify the relation ship and then assign these values to a collection called sdvd at this point you can't get to vd.  That said, you then do from v in sdvd.DefaultIfEmpty() by doing so you have access to the rows in sdvd which are the same values that are in what you think vd holds.  You should be able to use v instead of vd.  I had to mock something up to test so I couldn't test out exactly this query, but the following should run.
var query = from sd in dbo.SessionDetails
    join vd in dbo.VoipDetails on new { sd.SessionIdTime, sd.SessionIdSeq } equals new { vd.SessionIdTime, vd.SessionIdSeq } into sdvd
    from v in sdvd.DefaultIfEmpty()
        join fgw  in dbo.Gateways on v.FromGatewayId equals fgw.GatewayId   into sdgw
        from g in sdvd.DefaultIfEmpty()
            select sd;

EDIT 2014/12/08
In order to see how the linq statement translates to sql, I would suggest you install https://www.linqpad.net/.  You can set up a connection and test out your queries there and see the sql in the results view.
As i don't have the data structure for the question this will be hard. That said I mocked up something:
from sd in  Employees
    join vd in TimeEntries on new { sd.EmployeeID } equals new { vd.EmployeeID } into sdvd
    from v in sdvd.DefaultIfEmpty()
        join fgw  in EmployeeGroupDetails on v.EmployeeID equals fgw.EmployeeID   into sdgw
        from g in sdgw.DefaultIfEmpty()
            select  sd

This YIELDS:
SELECT [t0].*
FROM [Employee] AS [t0]
LEFT OUTER JOIN [TimeEntry] AS [t1] ON [t0].[EmployeeID] = [t1].[EmployeeID]
LEFT OUTER JOIN [EmployeeGroupDetail] AS [t2] ON [t1].[EmployeeID] = [t2].[EmployeeID]

It does come back with the right joins.
Comment: I might well be misunderstanding, but in order to continue to make left-outer-joins, shouldn't that be `on v.FromGatewayId equals fgw.GatewayId   into sdgw from g in sdgw.DefaultIfEmpty()` rather than `sdvd.DefaultIfEmpty()` again?


Cloud.orbit.exception.UncheckedException: Don't know how to handle state

Question: What is kotlin equivalent of this java class?
public class StatefulActor extends AbstractActor<StatefulActor.State> implements Some
{
    public static class State
    {
        String lastMessage;
    }
}

I tried:
class HelloActor: AbstractActor<HelloActor.State>(), Hello
{
    inner class State {
        var lastMessage: String? = null
    }

but results in Cloud.orbit.exception.UncheckedException: Don't know how to handle state
Answer:
What is kotlin equivalent of this java class?

Your Kotlin and Java code differs in two ways, the relationship of the State to StatefulActor and the ability of State to allow subclassing.
For State what you want is a Nested class not an Inner class in Kotlin terms. The former corresponds to static modifier in Java whereas the latter is like an inner class without the static modifier.
So for equivalence with the Java code you gave, you should drop the inner keyword.

Cloud.orbit.exception.UncheckedException: Don't know how to handle state

As for your Orbit problem you can try the following. This will also explain why subclassing is an issue:
// compile and run with cloud.orbit:orbit-runtime:1.2.0

import cloud.orbit.actors.runtime.AbstractActor
import cloud.orbit.actors.Actor
import cloud.orbit.actors.Stage
import cloud.orbit.concurrent.Task

class HelloActor: AbstractActor<HelloActor.ActorState>(), Hello
{
    override fun sayHello(greeting: String): Task<String> {
        val lastMessage = state().lastMessage
        state().lastMessage = greeting

        return Task.fromValue(lastMessage)
    }

    class ActorState {
        var lastMessage: String? = null
    }
}

interface Hello : Actor {
    fun sayHello(greeting: String): Task<String>
}

fun main(args : Array<String>) {
    val stage = Stage.Builder().clusterName("orbit-helloworld-cluster").build()
    stage.start().join()
    stage.bind()

    val helloActor = Actor.getReference(Hello::class.java, "0");

    var response = helloActor
            .sayHello("Welcome to orbit 1").join()

    println(response) // should print null

    response = helloActor
            .sayHello("Welcome to orbit 2").join()

    println(response) // should print "Welcome to orbit 1"

    stage.stop().join()
}

Notice that the Actor's nested class is called ActorState and not State as in your question. When I named the Actor's state class State I got a similar error:
cloud.orbit.exception.UncheckedException: Don't know how to handle state: HelloActor$State...
Caused by: cloud.orbit.exception.UncheckedException: cloud.orbit.exception.UncheckedException: Don't know how to handle state: HelloActor$State
Caused by: cloud.orbit.exception.UncheckedException: Don't know how to handle state: HelloActor$State
Caused by: cloud.orbit.exception.UncheckedException: java.lang.ClassNotFoundException: HelloActor$ActorState

But when I used the nested class name HelloActor.ActorState instead it works.
This is because by default all classes in Kotlin are closed (i.e. final in Java terms).

By default, all classes in Kotlin are final, which corresponds to Effective Java, Item 17: Design and document for inheritance or else prohibit it.

While in orbit 1.2.0 the code (if you do not use the special name ActorState) tries to subclass your State class and then instantiate it. This will not work if you go with the closed Kotlin default extensibility.
If you wish to use your own name for the Actor's state class you must declare it as open. e.g.
class HelloActor: AbstractActor<HelloActor.State>(), Hello
{
    override fun sayHello(greeting: String): Task<String> {
        val lastMessage = state().lastMessage
        state().lastMessage = greeting

        return Task.fromValue(lastMessage)
    }

    open class State {
        var lastMessage: String? = null
    }
}

Comment: Same exception. Nothing changed
Comment: Try this full runnable example, it works for me. There seems to be some issue naming the Actor's State class `State` but `ActorState` works.
Comment: Why extend `Actor` in HelloActor?
Comment: It is not necessary. I left it in by accident. I've removed it now.


Erro método main

Question: Alguem pode me dizer uq esta dando errado ? diz que esta faltando o metodo main, mais nao era pra acontecer isso
public class PilhaEstatica {

            String vet[];
            int topo;

            PilhaEstatica(int tamanho) {    // Criar uma pilha vazia
                vet = new String[tamanho];  // Cria a pilha com um tamanho
                topo = 0;                   // Topo 0 significa pilha vazia
            }

        boolean vazia() {               // Verifica se a pilha está vazia
            return topo == 0;           // Se topo for 0, pilha está vazia
        }

        boolean cheia() {               // Verifica se a pilha está cheia
            return vet.length == topo;  // Se o topo é igual ao tamanho da pilha
        }

        boolean inserir(String valor) { // Inserir um novo elemento na pilha
            if (cheia()) {              // Se a pilha está cheia retorna falso
                return false;
            }
            vet[topo] = valor;          // Coloca a informação no topo
            topo++;                     // O topo agora é mais em cima da pilha
            return true;                // Se conseguiu excluir, retorna verdadeiro
        }

        String retirar() {              // Retira o elemento do topo da pilha
            if (vazia()) {              // Se a pilha está vazia, retorna nulo
                return null;
            }
            topo--;                     // Agora o topo vai descer pra tirar o elemento do topo
            return vet[topo];           // Retorna o elemento que estava no topo
        }
       }

Comment: "isso" o quê ? Qual o problema ? Qual o erro ?
Comment: Por favor, esclareça seu problema ou forneça detalhes adicionais a fim de destacar exatamente o que você precisa. Da forma como está escrito atualmente é difícil dizer com exatidão o que você está perguntando.
Answer: Para rodar um código Java, você precisa criar uma classe com um método main. O método main é o ponto de entrada do programa e é nele que o código é executado.
No seu código, você criou uma classe chamada PilhaEstatica, mas não criou um método main. Você precisa adicionar um método main à sua classe para poder rodar o programa.
Aqui está como o código poderia ficar com o método main adicionado:
public class PilhaEstatica {

    String vet[];
    int topo;

    PilhaEstatica(int tamanho) {    // Criar uma pilha vazia
        vet = new String[tamanho];  // Cria a pilha com um tamanho
        topo = 0;                   // Topo 0 significa pilha vazia
    }

    boolean vazia() {               // Verifica se a pilha está vazia
        return topo == 0;           // Se topo for 0, pilha está vazia
    }

    boolean cheia() {               // Verifica se a pilha está cheia
        return vet.length == topo;  // Se o topo é igual ao tamanho da pilha
    }

    boolean inserir(String valor) { // Inserir um novo elemento na pilha
        if (cheia()) {              // Se a pilha está cheia retorna falso
            return false;
        }
        vet[topo] = valor;          // Coloca a informação no topo
        topo++;                     // O topo agora é mais em cima da pilha
        return true;                // Se conseguiu excluir, retorna verdadeiro
    }

    String retirar() {              // Retira o elemento do topo da pilha
        if (vazia()) {              // Se a pilha está vazia, retorna nulo
            return null;
        }
        topo--;                     // Agora o topo vai descer pra tirar o elemento do topo
        return vet[topo];           // Retorna o elemento que estava no topo
    }

    public static void main(String[] args) {
        // Aqui você pode colocar o código que quer rodar quando o programa for executado
    }
}

Espero ter ajudado! Se você ainda tiver dúvidas ou precisar de mais informações, basta me perguntar

Erro método main


Can't get observation-wise factor scores from psych package

Question: After R reads the data, say-
v1 <- c(1,1,1,1,1,1,1,1,1,1,3,3,3,3,3,4,5,6)
v2 <- c(1,2,1,1,1,1,2,1,2,1,3,4,3,3,3,4,6,5)
v3 <- c(3,3,3,3,3,1,1,1,1,1,1,1,1,1,1,5,4,6)
v4 <- c(3,3,4,3,3,1,1,2,1,1,1,1,2,1,1,5,6,4)
v5 <- c(1,1,1,1,1,3,3,3,3,3,1,1,1,1,1,6,4,5)
v6 <- c(1,1,1,2,1,3,3,3,4,3,1,1,1,2,1,6,5,4)
m1 <- cbind(v1,v2,v3,v4,v5,v6)

if I run-
factanal(~v1+v2+v3+v4+v5+v6, factors = 3, scores = "Bartlett")$scores

I can get observation-wise factor scores. But when I do this-
r<-cor(m1)
library(psych)
fa<-fac(r,nfactors=3,rotate="varimax", scores="Bartlett")
fa$score

I can't get individual-wise factor scores. Is it possible to get individual-wise factor scores using psych? Actually I need to use psych, because I need to put spearman's rank correlation matrix as the starting point for factor analysis. Kindly suggest me.
Thank You
Comment: You'll probably need to provide raw data, and not just a correlation matrix, if you want to compute regression scores. Try this instead: `fac(data.frame(v1,v2,v3,v4,v5,v6), nfactors=3, rotate="varimax", scores="Bartlett")$scores`.
Answer: Blain, I'm not R user so can't be an expert. Anyway... What I see from your code is that you input correlation matrix in place of initial case-wise data into fac. This way you can't hope to obtain case-wise factor scores! What you can obtain at best is the matrix of regressional coefficients by which the scores can be computed.
A separate concern is you plan to base your future factor analysis on Spearman correlation. I don't know psych and its options but I suspect that the package just will process such matrix as if it were Pearson correlation. Linear factor analysis is mathematically based on Pearson correlations (or on covariances or cosines or sum-of-squares-and-cross-products, or on inferred Pearson correlations such as tetrachoric ones) and is not meant for rank correlations. The only justification to use Spearman instead of Pearson in the analysis would be your belief that the former reflects underlying linear relationships more accurately than the observed Pearson coefficient. But whence can you get this certainty?
Comment: (+1) I can confirm that Pearson correlations are used, by default. (With raw data, pairwise correlations are computed.) The 6 by 3 matrix of beta weights is returned as `fa$weights`, in the present case.


Lasso with constraint on some coefficients (not all)

Question: I would like to run a lasso regression (L1 penalisation) with a twist: there are different constraints on my problem.
The coefficients for my features (predictors) are $\beta_i$.
I want to find the $\beta_i$ such that
$\sum_{i = 1}^n X_i \beta_i = Y + \epsilon$
under the constraints:

$\beta_i \ge 0$  $\forall i$
$\sum_{i=1}^K \beta_i = 1$
$\sum_{i = K+1}^n \beta_i \le c$

How can I achieve this? I am using python2.7, so any solution using sckit-learn or scipy would be greatly appreciated!
Comment: Asking for code is off-topic, but I'm pretty sure this is a linear program.
Answer: I don't see anything in the documentation of scikit learn that could help you doing this:
<code> class sklearn.linear_model.Lasso(alpha=1.0, fit_intercept=True,
     normalize=False, precompute=False, copy_X=True, max_iter=1000, tol=0.0001,
     warm_start=False, positive=False, random_state=None, selection='cyclic')
</code>
However, CVXOPT would be a perfect starting point for writing this specific optimization problem. Here is an example with regularized least square: RLS.
Comment: (+1) The problem is simply a quadratic program--an interior point method will work. Of course, another method could be faster.
Answer: You can initialize the model parameters randomly to fit the constraints, and then run a form of gradient descent where you project the resulting coefficients onto the nearest plane that satisfies the constraints, as well. Since this is done with smaller steps at a time (ideally smaller steps as the number of iterations grows), it should converge.
A simpler(?) solution would be to construct a "wall" function that heavily penalizes constraint violations, and then project the final solution onto the constraints if you need an exact match.
I would recommend theano for this, since it makes iterative models relatively easy and compiles the code in C for faster performance.
Note that projecting on a convex hull is a bit more complicated than just a plane, but this paper outlines the algorithm.  Because your constraints are a bit different than the one in the paper, I would impose the constraints on the two cutoff points ( i < K, i >= K) separately. The second constraint is not exact, so I think you can just omit points from the algorithm that already satisfy the constraints. Someone please correct me if I am wrong on this.


How to breakup URL to keyvalue pair

Question: I am looking to breaking up a URL to key value pair in PHP
for example
/name/foo/location/bar/account/3449

Result would be something like this
array(name => "foo", location => "bar", account => "3449");

Current solution:
$urlPieces = explode('/', $_GET['q']);
$results = array();
$count = 0;
$keyName = "";
foreach ($urlPieces as $key=>$value) {
    if($count % 2 != 0){
       $results[$keyName] = $urlPieces[$count++];
    }else{
       $keyName = $value;
       $count++;
    }
}

Comment: `$_GET['q']` is going to be nothing because you don't have any query strings on that URL.
Answer: As I mentioned in the comments - $_GET['q'] does not exist because you don't have any query strings on that URL. Try this:
$url = strtok($_SERVER["REQUEST_URI"],'?'); //get the URL and remove query strings
$urlPieces = explode('/', $url); //create array from that URL
$count = 0;
$results = array();
foreach ($urlPieces as $key=>$value) {
    if($count % 2 != 0){
       $results[$urlPieces[$key]] = $urlPieces[$count+1];
        //new array key is the current $key (aka $urlPieces[$key])
        //new array value is the value of the next key (aka $urlPieces[$count+1])
    }
    $count++;
}

The resulting array is $results. Note that this will only work properly if you have an even number of URI segments.

How to breakup URL to keyvalue pair


Unix to execute program on WAN IP update

Question: How do I access the current IP address? Is there a way to execute a program every time it changes? I want to make a program that whenever my IP changes, it will use the Amazon Route 53 API and update a record set with its current IP address. Basically, whenever my IP changes, it will tell amazon where its at so that traffic can be directed to it. I have done some perl, python, go, and bash scripting. Though I'd be most comfortable with python or bash.
Answer: You can check your current IP with the ifconfig command. However, if you're behind a NAT that won't show you much.
The best you can do is poll something external that will tell you what your translated IP address is. WhatIsMyIP.com provides a service for doing this. See their IP Automation Rules.
Poll both Route 53 and WhatIsMyIP no more frequently than every 300 seconds. If they are different then update Route 53.


Typescript switch/case on string not maching when it should

Question: I have a strange behavior on a switch statement that is supposed to check for possible values of a string.
I'm trying to develop a little parser and using TDD I managed to write (and test) a function that parses a single line at a time, resulting in the expected result for all my cases.
Now I'm developing a bigger function that parses a bunch of lines at once so what it does is essentially split these lines and call the function that parses one line at a time.
The strange behaviour happens when I'm checking a value:
parseLine(terrainLine: string): Terrain | Tile[] | Adventurer {
    const [lineType, ...lineData] = terrainLine.trim().split(' - ');

    switch (lineType) {
      case 'C':
        return Terrain.parseTerrain(lineData);

      case 'T':
        return Terrain.parseTreasures(lineData);

      case 'M':
        return [Terrain.parseMountain(lineData)];

      case 'A':
        return Terrain.parseAdventurer(lineData);

      default: {
        throw new TerrainError(
          `Unable to parse terrain tile with data: "${terrainLine}"`,
        );
      }
    }
  }

This function is tested and should be working properly with strings like 'C - 3 - 4' (this input was tested and passed) but when the following function makes a call, it does not work anymore and instead it triggers the default statement:
parse(terrainString: stirng): Terrain {
  const linesToParse = terrainString
      .split('\n')
      .map((_) => _.trim()) // Get rid of spaces before and after interesting data
      .filter((_) => _.length && !_.startsWith('#')); // Get rid of empty lines && comments lines

  linesToParse.forEach((line) => {
      const parsed = Terrain.parseLine(line);
      // [...]
  }

  // [...]
}

For reference, here are the tests I use:
// This one passes
it('should parse terrain lines right', () => {
  const terrainLine = 'C - 3 - 4';
  const expectedTerrain = new Terrain(3, 4);
  const parsed = parseLine(terrainLine);

  expect(parsed).toBeInstanceOf(Terrain);
  expect(parsed).toStrictEqual(expectedTerrain);
});

// This one doesn't
it('should accept valid terrains', () => {
  const terrainString = 'C - 3 - 4\nM - 1 - 0\nM - 2 - 1\nT - 0 - 3 - 2\nT - 1 - 3 - 3\nA - Lara - 1 - 1 - S - AADADAGGA\n';

  expect(() => {
    Terrain.parse(terrainString);
  }).not.toThrow();
});

Comment: Oh...you actually have [the most evil character](https://stackoverflow.com/questions/2973698/whats-html-character-code-8203) - it's a zero width space. It's a *space* but it literally cannot be seen at all. It has no width when printed. It's still a character in the string, however. It's a VERY annoying one, as it bypasses some of the withespace checks and it's incredibly hard to find normally.
Comment: Are you sure the string is `"C"` and not `"C "` with an extra space for example? Is that a capital Latin "C" character, char code 67 or is it a different character?
Comment: It seems that you are right: the charcodes are matching but for some reason `lineType` has length `2` and `lineType.charAt(1)` gives me `8203`. I don't know why though
Comment: You probably have some invisible characters in your string.
Comment: I tried debugging it and I got a really strange behaviour where `lineType` (from the first code snippet) is `'C'` and it still goes to the `default` statement.

Moreover, I tried `lineType === 'C'` and `lineType == 'C'` which both gave me `false`
Comment: Yes. Thanks for your help
Answer: As pointed out by @VLAZ, I had an invisible character of zero width when printed in my string which was causing this bug.
Simply removing this character in the first place solved the problem.


Is the number of voices determined relative to the bar or to the phrase?

Question: The direction of a note's stem is based on the number of voices in its context. If there is one voice, notes written above the middle staff line (B in G-Clef) are down-stem, whereas notes written below the middle staff line are up-stem. If there are two voices, the upper voice takes up-stem notes, and the lower voice takes down-stem notes. It is therefore important to determine how many voices there are.
Consider a phrase with two voices, spreading over multiple bars. In one of the bars, the upper voice is silent, so in fact, the bar consists only of the lower voice. Do we consider this bar to contain only one voice, since the upper voice is silent, and then the notes should be noted based on the one voice rules, or we consider it to contain two voices, and the notes should be down-stem (with a full bar rest for the upper voice)? In other words, is the number of voices determined relative to the bar or to the phrase?
To illustrate, option #1:

Option #2:
Comment: Note that none of the default behaviors in any scoring software should be interpreted as correct notation. They *might* be correct 95% of the time, or they might be the best way to typeset things on the first pass, or they might be that way because of difficulties in one or more algorithms. The point being, you can't trust the software to get it right for you.
Comment: Your second picture is wrong no matter which standard gets used - there is no upper voice in Bar 48 there, and the C octave is down-stem when it should be up-stem like the others.
Comment: @Dekkadeci - Interesting. This is the default behavior I get from MuseScore. Maybe the rules for octave stems are different?
Answer: The standard I'm used to seeing is that, if there is a rest in one temporary voice (i.e. you're not writing a fugue or anything polyphonic, so you have no obligation to provide whole-bar rests for voices), you omit the rest for that measure and notate that measure as if that voice is missing. It doesn't matter if that rest occurs in the middle of a phrase.
Comment: This is the correct answer. In looking through some scores to find examples for my answer, they seem to follow the pattern you describe: A Bach fugue (e.g., WTC II, Eb major) maintains the stemming (and rests) even when a voice drops out for several measures; but an arrangement of Gershwin's piano solo arrangement "An American in Paris" only maintains the stemming during the measure that explicitly contains multiple voices.
Comment: @Sipo Because my post only accommodated one way of handling the situation, and to expand it would have duplicated what Dekkadeci wrote here without really adding anything. Examples could just as easily be added here. Though if Dekkadeci isn't so inclined (are you?), I could rework my original one as a supplement to this one.
Comment: So now I have two conflicting answers and I don't know what to do :(
Comment: @Sipo I've deleted my answer. This is the correct one.
Comment: @Aaron - Thanks. Just to be sure I understand, you found examples of both patterns?
Comment: @Sipo Yes. I found examples consistent with what's described in this answer. In your specific example, I personally find it easier to read if you maintain the stemming as in your first option, but this answer is correct in terms of the overall practice.
Comment: @Aaron, so if you found examples for both patterns, why did you say that you were wrong?
Comment: @Aaron, well, I actually really prefer your approach, so I think people should know that is valid too...


Adicionar e editar elemento AJAX

Question: Boas,
Quero editar um trdepois de criá-lo e adĩcionado por AJAX.

Quando eu clico no criar 'Marca':
$('#confirmCreateBrand').click(function(){
brand = $('#createbrand_name').val();
advertiser = $(this).attr('advertiser-id');
user = $(this).attr('user-id');

if(brand == ""){
  $('#createbrand_name').css('border','1px solid red');
  $('#createbrand_name_error').show();
  return false;
}

 var brand = {
        advertiser_id: advertiser,
        name: brand,
        user : user,
        _token :"{{ csrf_token() }}",
      };

  $.ajax({
    url: '{{ URL::to('brand/store/') }}',
    type: 'POST',
    dataType: 'JSON',
    data: brand,
    success: function(brand) {
    $('#brandsTable').find('tbody:last-child').append('
'+brand.name+'	 <button brand-id="'+brand.id+'" brand-name="'+brand.name+'" brand-advertiser="'+{{$advertiser->id}}+'" tabindex="-1" role="dialog" data-toggle="modal" data-target="#editBrandModal" class="editBrandBtn"></button> <button brand-id="'+brand.id+'" brand-name="'+brand.name+'"  tabindex="-1" role="dialog" data-toggle="modal" data-target="#deleteBrandModal" class="deleteBrandBtn"></button>
');

        $('#createBrand').modal('hide');

      $('#createBrand input').val('');
    }
  });

})
Esta função adiciona-me um tr com os botoes editar e apagar.
mas quando clico no editar num elemento depois de o adiciona, nao me entra nesta função.
Se fizer refresh à página já entra.
$('.editBrandBtn').click(function(){
name = $(this).attr('brand-name');
brand_id = $(this).attr('brand-id');
alert(brand_id);
$('#editbrand_name').val(name);
$('#confirmEditBrand').attr('brand-id',brand_id);

});

podem-me ajudar, sff?
Comment: Este é o site do stackoverflow em português, traduza sua pergunta ou faça a pergunta no site em inglês
Comment: Por favor em Português...
Comment: Traduzido, peço desculpa.
Answer: Já resolvi esta questão...
coloquei todo o meu JS dentro de:
$(document).bind('ready ajaxComplete', function(){
  //TodoJSdesteFicheiro
});

Como o elemento é adicionado depois do AJAX correr e as funções do Editar e Apagar só estavam disponiveis no document ready, é necessário fazer esta alteração antes do javascript, para que as funcções estejam disponiveis quando o DOM estiver 'pronto' e depois do 'AjaxComplete'.

Adicionar e editar elemento AJAX


Por que um alinhamento interno de um botão  fica diferente de um link , mesmo usando a mesma classe?

Question: Bem, eu criei uma classe chamada .btn, onde eu queria usá-la tanto para button como para a. Por isso eu forcei algumas coisas nessa classe, para resetar o estilo original, tanto do button como do a.
Por exemplo, no a eu removi o text-decoration. No button, forcei a mudança do background e border. Até aqui tudo bem.
O problema é que eu estou notando que o elemento button, mesmo usando o -webkit-appearence: none, apresenta um comportamento diferente em relação ao alinhamento do texto interno, conforme o teste abaixo:

.btn{
    border: 1px solid transparent;
    padding: 10px 20px;
    box-shadow: 0 1px 2px 0px #666;
    outline: none;
    border-radius: 4px;
    background-color: #efefef;
    cursor: pointer;
    transition: box-shadow .1s ease-out, border-color .3s linear;
    font-weight: bold;
    box-sizing: border-box;
    vertical-align: top;
   display: inline-block;

    min-height: 55px;
    font-size: 14px;

   text-decoration: none;
   color: #222;
   background-image: none;

    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
    font-family: Arial;

}
<button class="btn">
  Eu sou um <Button>
</button>

    Eu sou um <A>

Eu vou colocar a  imagem também, pra mostrar como ficou a renderização no meu Google Chrome:

Agora fica minha dúvida:

Que propriedade faz com que o button alinhe os textos no meio, enquanto o a não?
Existe uma forma de resetar essa alinhamento padrão do button? Minha intenção era deixar os dois centralizados, mas mais importante do que isso, quero saber se existe uma propriedade do button fez ficar alinhado ao centro.

Observação: A pergunta não tem o apenas o intuito de saber como alinhar o texto ao centro, mas saber a fundo sobre o que ocasionou a diferença citada acima, já que eu usei o mesmo estilo para todos.

Observação 2: Eu poderia usar inline-flex e combinar com justify-content: center; align-itens: center, mas não é essa a resposta que quero, pois isso já estou colocando ela na pergunta. Quero saber especificamente sobre os detalhes apresentados acima, e não apenas um "suporte para o problema do alinhamento"
Comment: @JorgeCosta eu copiei os estilos do user-agent todo e apliquei ao seletor `a {...}` nada acontece, isso ai é comportamento do elemento Button como se isolasse o texto para, diferente do A que o texto interno acompanha o `vertical-align: top`
Comment: @JorgeCosta até copiando o line-height do user-agent para `` o resultado é o mesmo.
Comment: Caro @JorgeCosta entendo, mas seus comentários foram todos sobre tira isso, faz aquilo, acaba por fazer entender que esta tentando aplicar soluções e não tentar entender o comportamento do box-model: https://www.w3.org/TR/CSS2/box.html, mas acho que já estamos esclarecidos de tudo :)
Comment: Já verificou que estilos são atribuídos por ao  e  por defeito em qualquer browser.
Comment: mas verificou que o button tem line-height, no safari em macOS é line-height: 13px;
Comment: Para testar retire o min-height: 55px;   e coloque   line-height: 3;    padding: 0px;
Comment: @JorgeCosta se você colocar `min-height: 1000px` no button, ele fica com tudo no meio, da mesma forma. Não creio que seja apenas o `line-height`.
Comment: Caro @JorgeCosta tirar o `min-height` não explica como o porque o texto no `` alinha verticalmente para o centro. Aqui ninguém tá procurando soluções de como resolver, mas sim entender o porque isto ocorre, como o autor da pergunta já explicou na propria pergunta.
Comment: Sim eu também estou a tentar perceber e não resolver
Comment: Estava verificando o que o próprio browser aplica por defeito, caso fosse para encontrar a solução me limitaria a aplicar as soluções já encontradas em frameworks como bootstrap. Mas já que está esclarecido sobre a questão agradeço que coloque uma resposta cabal para a pergunta e assim partilhar com todos.
Answer: Atualizado - 11/08/2018
Depois de muita pesquisa apesar de entender a questão de várias formas pesquisei e obtive uma resposta mais plausível com fontes para sua questão.
A resposta é do Cubed Eye usuário do Stack overflow.
Em primeiro lugar, a principal questão aqui é que <button> pelo menos no Firefox são construídos com um elemento interno entre a tag <button> e seus filhos. No Firefox é chamado moz-button-content não é algo que pode ser alcançado com CSS e foi definido para exibir o bloco sem herdar a altura do botão, você pode ver esta declaração de estilo na folha de estilo useragent.
O navegador por padrão já é codificado para centralizar o conteúdo do botão verticalmente.
Com estas duas questões você pode começar a ver como o botão força o conteúdo a ser centralizado, considere:
<button>

+------------------------+ ^
| button extra space     | |
|                        | |
+------------------------+ |
|| ::moz-button-content || | button height
||   display: block;    || |
+------------------------+ |
|                        | |
| button extra space     | |
+------------------------+ v

Há uma solução alternativa para o problema se você realmente quiser alterar o comportamento padrão, mas isso não resolve completamente o problema dependendo da sua implementação.
Se você inserir um wrapper  com display: block o único filho do botão e colocar todo o seu conteúdo nele, poderá usá-lo para pular o moz-button-content elemento.
Você precisará fazer com que este  elemento tenha height: inherit preenchido corretamente a altura do botão e, em seguida, adicionar seu estilo de botão normal ao  invés disso, você obterá basicamente o comportamento desejado.

* {
box-sizing: border-box;
margin: 0;
border: 0;
padding: 0;
font-family: san-serif;
background: none;
font-size: 1em;
line-height:1;
vertical-align: baseline;
}

button, a {
height: 3em;
}

button {
background: red;
}
button::-moz-focus-inner {
border: 0;
padding: 0;
outline: 0;
}

button > span {
display: block;
height: inherit;
}

a {
display:inline-block;
background: green;
}

button.styled > span , a.styled{
padding: 10px;
background: yellow;
}
<button>
Button content
</button>

Link Content

<button class="styled">
Button content
</button>

Link Content

Você deve usar um em  vez de um
, como div não são filhos válidos para <button>.
Comment: Não amigo acho que vc não entendeu bem a pergunta ou está equivocado. O autor da pergunta quer saber pq o texto dentro do btn fica alinhado na vertical por padrão. E não é por causa do vertical-align, pois mesmo colocando no button por exemplo ` vertical-align: bottom !important` o texto continua centralizado verticalmente no meio do button, logo não é isso que faz o texto do btn alinhar centralizado. Resumindo coloca `vertical-align` no button e tenta alinha o conteúdo que não no centro do btn, não vai funcionar...
Comment: Pega um arquivo sem nenhum css, cria um button, coloca um span dentro com display:block e height 100px. Ele vai ficar alinhado no topo verticalmente depois com     transform: translateY vc alinha onde quiser por exemplo. Colocando um elemento dentro do outro vc pode fazer o que quiser.... O que ainda não ficou claro é pq o texto dentro do btn fica sempre no meio vertical... Apesar do sua boa vontade em ajudar acho que ainda não temos uma resposta.
Comment: @hugocsl, editei a resposta, peço que analise novamente, realmente achei que era apenas sobre o alinhamento, adicionei novas observações.
Comment: Era bom pôr um snippet aí mas creio que a resposta esteja errada. Vou ligar meu PC daqui a pouco e já testo
Comment: Não creio que seja do sistema operacional, é sim do user-agent default do browser. input, select, checkbox, todos são estilizado pelo user-agent e não pelo sistema operacional, tanto que no safari para windows (mesmo que antigo), os estilos eram iguais aos do Mac, então acho que OS não tem nada a ver com isso... Depois, fazer o `` ficar igual ao `` é bem diferente de fazer o button ficar igual ai A... Para alinhar verticalmente exitem 1000 fórmulas, mas pq o button faz isso por default? pq não tem como mudar isso? Se vc conseguir, posta ai. E se tiver uma fonte ajuda.
Comment: Sobre deixar  igual ao  olhe novamente a resposta, editei.
Comment: Cara é só dar um all:unset no button, nem precisa escrever tudo isso de css pra "resetar" os estilos padrão do button... mas mesmo zerando tudo o texto continua no centro verticalmente, basta colocar um height no btn que vc vai ver
Comment: @hugocsl atualizado, acho que com a resposta responde tudo, realmente estava entendendo errado e tive que buscar quase a noite inteira pra achar a resposta fiquei atucanado.


Apache - How to disable gzip content encoding (eg DEFLATE) for one set of URLs?

Question: I have a ubuntu apache webserver and I have enabled mod_deflate to gzip all the content. However there's one folder I'd like to disable the mod_deflate for. I was going to do something like this:
<Location /myfolder>
   RemoveOutputFilter DEFLATE
</Location>

But that doesn't work.

Rational: I am trying to debug an XMLRPC server and I am using wireshark to see what gets past in the HTTP requests, since the replies are gzipped, I can't see what's going on.
Answer: I believe that RemoveOutputFilter expects a file extension, not a filter type.  It should be something like:
<Location /myfolder>
      RemoveOutputFilter html
</Location>

or whatever file extension you're using in that directory.
Comment: One look at the documentation of mod_mime (http://httpd.apache.org/docs/2.2/mod/mod_mime.html#removeoutputfilter) and you'd know rather than only believe that `RemoveOutputFilter` expects one or more file extensions as argument. ;)
Comment: In this case `RemoveOutputFilter text/html` would be correct
Answer: @rvf, thanks for the help!
I was struggling with downloading of desktop (not html, css or js) files being corrupted during download but only for some users.  Internet Explorer had the most trouble. The problem was that the server's GZIP was compressing already compressed ZIP files and other files that needed to be unmodified binary transfers including PDF, DWG and SKP.  I thought those files had been removed from the compression but found out they were still being compressed using this online gzip test tool
http://www.gidnetwork.com/tools/gzip-test.php
Comment: IE is notorious for not handling this situation correctly. See: http://stackoverflow.com/questions/1241822/why-is-gzip-compression-with-internet-explorer-not-working


Java 8 doesn't compile on Intellij15

Question: Recently our company moved to Java 8 (previously working with Java 7).
Everything was fine while I was using Eclipse, but now I switched to IntelliJ Idea 15 (it's my first time in IntelliJ Idea) and it simply won't compile any Java 8 code (lambdas, etc.)
I searched for a solution and found out that I have to set a project language level to 8 in IntelliJ project settings, but it still doesn't help.
Any ideas?
Comment: I get that its a neewb question, but its a mistake anyone could make and doesn't deserve the downvotes.
Comment: After changing the project level, try restarting the IDE and rebuilding the project
Comment: It would be better to provide a question with the specific errors you are seeing.
Answer: Make sure that you correctly selected the JDK.
In IntelliJ you should go to: File -> Project Structure... project settings tab, and make sure the project SDK points to the location of your java 8 JDK, (something like: C:\Program Files\java\jdk1.8.0_45)
And, of course, make sure the project language level is set to 8 - Lambdas, type annotations etc.
Comment: Thanks, the JDK was set to java 7, indeed :)

Java 8 doesn't compile on Intellij15


how do i show the products that are uploaded by the logged in user only?

Question: Here's my problem, when a user logs in they can see the products uploaded by the other user also but i am trying to show when an user logged in they can see the products uploaded by them only**
views.py
from django.shortcuts import render, get_object_or_404, redirect
from .forms import ProductForm
from .models import Product
from django.contrib.auth.models import User

prodcut create or upload
def product_create_view(request):
    form = ProductForm(request.POST or None)
    if form.is_valid():
        form.save()
        form = ProductForm()

    context = {
        'form': form
    }
    return render(request, "products/product_create.html", context)

product update
def product_update_view(request, id=id):
obj = get_object_or_404(Product, id=id)
form = ProductForm(request.POST or None, instance=obj)
if form.is_valid():
    form.save()
context = {
    'form': form
}
return render(request, "products/product_create.html", context)

tried by changing in the list view but getting this error product_list_view() missing 1 required positional argument: 'user'
def product_list_view(request, user):

    queryset = Product.objects.filter(user=request.user)

    context = {
        "object_list": queryset
        }
    return render(request, "products/product_list.html", context)

**product detail **
def product_detail_view(request, id):
    obj = get_object_or_404(Product, id=id)
    context = {
        "object": obj
    }

    return render(request, "products/product_detail.html", context)

product delete
def product_delete_view(request, id):
    obj = get_object_or_404(Product, id=id)
    if request.method == "POST":
        obj.delete()
        return redirect('../../')
    context = {
        "object": obj
    }

    return render(request, "products/product_delete.html", context)

this is product list template page
template/product.list.html
  {% extends 'accounts/base.html' %}

  {% block content %}

      {% for instance in object_list %}

{{ instance.id }} - {{ instance.title }}

       {% endfor %}

    {% endblock %}

here's the **
**models.py
from django.db import models
from django.urls import reverse
from django.conf import settings
from django.contrib.auth.models import User

class Product(models.Model):
    title = models.CharField(max_length=120)
    description = models.TextField(blank=True, null=True)
    price = models.DecimalField(decimal_places=2, max_digits=10000)
    summary = models.TextField(blank=False, null=False)
    featured = models.BooleanField(default=False)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE)

    def get_absolute_url(self):
        return reverse("products:product-detail", kwargs={"id": self.id}) #f"/products/{self.id}/"

urls.py
urlpatterns = [
    path('', product_list_view, name='product-list'),
    path('create/', product_create_view, name='product-create'),
    path('<int:id>/', product_detail_view, name='product-detail'),
    path('update/<int:id>/', product_update_view, name='product-update'),
    path('<int:id>/delete/', product_delete_view, name='product-delete'),
]

Comment: Indentations are important for python code. Could you edit your question to correct that?
Comment: Please remove the boldface (boldface should be used to stress *parts* of the question). Furthermore please indent your code.
Comment: thanks for suggesting my fault ,in future i will take care of it
Comment: @redwanabir: not to worry. These are some hints to ask better questions :) such that next time, you receive a better answer in less time :).
Answer: You never set the logged in user in your Product when you create or update it:
def product_create_view(request):
    if request.method == 'POST':
        form = ProductForm(request.POST)
        if form.is_valid():
            form.instance.user = request.user
            form.save()
    form = ProductForm()
    context = {
        'form': form
    }
    return render(request, 'products/product_create.html', context)
def product_update_view(request, id):
    obj = get_object_or_404(Product, id=id, user=request.user)
    if request.method == 'POST':
        form = ProductForm(request.POST, instance=obj)
        if form.is_valid():
            form.instance.user = request.user
            form.save()
    else:
        form = ProductForm(instance=obj)
    context = {
        'form': form
    }
    return render(request, 'products/product_create.html', context)
In your product_detail_view and product_delete_view, you should filter on the user as well:
def product_detail_view(request, id):
    obj = get_object_or_404(Product, id=id, user=request.user)
    context = {
        'object': obj
    }
    return render(request, "products/product_detail.html", context)

def product_delete_view(request, id):
    obj = get_object_or_404(Product, id=id, user=request.user)
    if request.method == "POST":
        obj.delete()
        return redirect('../../')
    context = {
        'object': obj
    }
    return render(request, 'products/product_delete.html', context)
in your list view, you should not use user as a parameter:
def product_list_view(request):
    queryset = Product.objects.filter(user=request.user)
    context = {
        'object_list': queryset
    }
    return render(request, 'products/product_list.html', context)
Additional remarks:

usually in case of a successful POST request, you should make a redirect, in order to implement the Post/Redirect/Get pattern [wiki];
you might want to make the user column non-NULLable, since now it will have NULL if you do not specify a value, and you allow to construct products without a user;
please do not use request.POST or None. A POST request can be valid, even if it is empty;
please do not write urls yourself, Django's redirect(..) [Django-doc] can resolve a URL based on the name of a view, and the values for the parameters. This is more safe if you later want to rewrite the URLs; and
you might want to take a look at class-based views like CreateView [Django-doc], UpdateView [Django-doc], and DeleteView [Django-doc]. These will reduce the amount of boilerplate logic.
Comment: thank you very much, it worked! and i will always keep in mind what you have suggested.


Como gerar um pequeno conjunto de caracteres alfanuméricos em PHP?

Question: Como gerar um pequeno conjunto de caracteres em PHP, como esse M7kL8a8z7q?
Quero fazer um upload de documentos diversos e quero renomear os arquivos em PHP como o botão de imagens faz aqui no Stack Overflow. Se eu misturo md5, com a data e outros fica enorme.
Não precisa seguir essa ordem de caracteres, só tem que ser randômica, não se repetir e ter 10 caracteres.
Comment: [uniqid](http://php.net/manual/pt_BR/function.uniqid.php)?
Comment: Não poderia ser um timespan atual ou um datetime?
Comment: Veja se isso lhe atende: https://ideone.com/1bwioP
Answer: Um gerador de senhas simples, você pode alterar o tamanho da senha alterando a variável length, e os caracteres possíveis alterando a variável characters. Fonte
function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

Comment: Arrumei, me confundi e acabei colocando uma resposta com JAVA


How to check status login and redirect to dashboard in Redux

Question: I created two pages: <login> and <dashboard>. In login form I create userInput and passwordInput and button submit. When the user type and click into button submit. When app start ,how to check if user logined to app, it will redirect to <dashboard> and if user have not login to app, it will redirect to login? Thanks you for support
Comment: Normally one would store an access token in local storage or cookies to determine if the user is logged in or not. To have role based re direct in your app, you can make use of Outlet from react-router-dom version 6.
Comment: thanks you ! i'm learning and i get stuck with redux toolkit : slice..so don't know how to put it code `localStorage.setitem(...)`? @Arpit
Comment: I haven't used redux toolkit so I wouldn't know. To store in local storage, you have to do it like this:  JSON.stringify(localStorage.setIem('token'))
Answer: Check with your token in cookies or local storage with the following database users
export default function route(){

if a user exists in your DB then set validation true or either false
let validation=localStorage.getItem("token");

if(validation){

return(<Dashboard/>)

}
else{
return(<Login/>)
}


Regular Expression: Having All strings except bba and abb

Question: I was working on Regular Expression, There was a question about making a Regular Expression having string containing at-least one of among bba or abb but not both at the same time.
I made below expression for that.

a*(baa*)b+b(a*ab)a

But, A question arise in my mind to make a regular expression having All strings excep bba and abb
I am confuse in it now.
Kindly help.
Note: Its about Automata, Not JavaScript Or PHP Regex ........
Answer: You could use an alternation with a positive and negative lookahead to assert that one of the variations is not there and that the other variation is and vice versa.
^(?:(?=.*abb)(?!.*bba)|(?!.*abb)(?=.*bba)).*$
Regex demo
If neither of them could be there, you could use:
^(?!.*(?:abb|bba)).*$
Comment: @StephanT I see what you mean, for matching all strings excep bba and abb that would match indeed.
Comment: Wouldn't  ^((?!bba)(?!abb).)*$   be enough?
Comment: @StephanT. That would not match when either of them is present.
Answer: If it is an automata, wouldnt the answer just be
b(aa*b + a)* + (aa*b + a)* + b*
// First one:  words like baaaaabaababab, baaa, babaaaaaa
// Second one: words like aaaaabaababab, aaaaaa, aab
// Third one:  words like bbbbb, b, , bbb

because you can't type bb unless it is the only word in the regex
a^+ means at least one a and can be replaced by aa*
Comment: Close, you want it to be `b?(a^+b)* + b*` as the string can optionally start with a  single `b`.
Comment: Ouch, you are right, i will edit it immediately :D Thx
Answer: Try regex ^(?!(.*abb.*bba|.*bba.*abb)).*$
This will match the string contains either abb or bba not both
Regex


Copy and resize UIView to capture contents

Question: I have a UIView, setup on a superview using auto-layout and its subviews are setup too through auto-layout.
I want to be able to resize the view to capture its resized contents to a UIImage, while keeping the view displayed on screen the same size.
I know I can use:
UIGraphicsBeginImageContextWithOptions(myView.bounds.size, NO, 0.0);
[myView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImg = UIGraphicsGetImageFromCurrentImageContext();

to obtain the image from the view,
but how do I resize the view JUST for capturing its contents, whilst leaving it untouched on display?
Thanks
EDIT for clarity
I want to be able to increase the width of the view, changing the aspect ratio of the view, allowing for the auto layout constraints to arrange its subviews to its new size.
Is it possible to simply copy the view, don't add it as a subview of the main window (so it's not visible) and change its frame, then capture it?
Answer: I have created a 2nd instance of the view controller and set it up with the same properties as the original, except at a different size. I also had to add the new view as a subview, capture its contents via UIGraphicsGetImageFromCurrentImageContext() and then remove the view from the subview.
This does not seem like a very efficient solution, and it would be interesting to know if there is a better way to do this.


Is there a way to create hierarchical taxonomies checkboxes?

Question: I have an issue where I want to keep sub category inside a parent category. Say, for preferred vehicle I want a checkbox like this in node creation form
<code>[]Car
  []Volkswagen
  []Toyota
[]Bike
  []Kawasaki
  []Harley Davidson
</code>
Is there a way to implement this using taxonomy?
Answer: Taxonomy is hierarchical by nature, you can create category/sub stuff in it.
AFAIK, there is not any field widget as you describe in drupal core with taxonomy field. Maybe some contrib module (have a look at term_reference_fancytree ).
You also may define your own and generate a field widget dedicated to taxonomy.
Comment: Thank you, it does fulfill my use case


Conditional probability problem with two dice

Question:
We roll two fair dice three times.  (i) What is the probability that we get consecutive sums $6, 8, 4?$  (ii) What is the probability that we get a sum of $4$ on the third throw if on the first two we get a sum of $8$ and $5$ respectively?   (iii) What is the probability that the three outcomes contain exactly one sum of $4$ and exactly one sum of $10?$

My answer to (i) was: The total probability of getting these sums is: $\frac{5}{36}\cdot\frac{5}{36}\cdot \frac{3}{36}\approx 0.0016$. But I'm not exactly sure how to find the answer to the other two. Does (ii) imply that the throws are somehow conditionally bound? Wouldn't it normally be the probability of getting a sum of $4$ irregardless of what you have thrown before? (so $\frac{3}{36}$). And I'm not sure how to approach the third question aswell. Thanks, in advance.
Comment: You're right about ii), it is the probability of getting $4$ regardless of the outcome of the previous throws. About iii) and using the fact that the outcomes are independent, it should be something like $3!P(X=4)\cdot P(X=10)\cdot P(X\ne 4,X\ne 10)$. The $3!$ accounts for the ordering of the three outcomes.
Answer:
Does (ii) imply that the throws are somehow conditionally bound?

That is something you have to determine.  And you did that.

Wouldn't it normally be the probability of getting a sum of 4 irregardless of what you have thrown before?

Indeed. Each pair of rolls are independent of previous rolls.

And I'm not sure how to approach the third question as well.

You have the probability for a particular roll being 4, 10, or elsewise. Being $3/36$, $3/36$, and $30/36$ respectively.
You should be able to count the arrangements of these three distinct results.  $\{[4,10,E], [4,E, 10],\ldots, [E,10,4]\}$
Go forth and multiply.


(CS0029) converter uma List em ObservableCollection || SQLite

Question: Estou tentando criar um método que retorne uma ObservableCollection no lugar de uma Listno SQLite
namespace Projeto_03.DataBase
{
    public class TarefasDataAccess
    {
        private SQLiteConnection _database;

        public TarefasDataAccess()
        {
            _database = DependencyService.Get<IDatabase>().GetConnection();
            _database.CreateTable<Tarefa>();
        }

        public ObservableCollection<Tarefa> GetTarefas()//era List<Tarefa>
        {
            return _database.Table<Tarefa>.ToList();
        }
    }
}

só que na linha que tenta retornar a lista return _database.Table<Tarefa>.ToList(); Ocorre o erro:
Error CS0029: Cannot implicitly convert type 'System.Collections.Generic.List<Projeto_03.Model.Tarefa>' to 'System.Collections.ObjectModel.ObservableCollection<Projeto_03.Model.Tarefa>
namespace Projeto_03.ViewModel
{
    public partial class TelaPrincipalViewModel : ContentPage
    {
        public ObservableCollection<Tarefa> Tarefas { get; set; }//era List<Tarefa>

        public TelaPrincipalViewModel()
        {
            Tarefas = new TarefasDataAccess().GetTarefas();
        }
    }
}

se alguem puder ajudar. Desde já agradeço.
Answer: É só criar uma nova instância de ObservableCollection passando a lista como parâmetro.
public ObservableCollection<Tarefa> GetTarefas()
{
    return new ObservableCollection<Tarefa>(_database.Table<Tarefa>.ToList());
}


What does concurve or convex means in terms of Log likelihood function?

Question: As a non native english speaker and a naive student, I found difficulties in understanding what this means.
While studying a paper, I found that some log likelihood functions showed convexity property in that study.
There are nothing more about this property in that paper.
I spent some time to understand what this property is. However, I think I just wasted my time.
Is it something about maximizing log likelihood so that we can find better estimate from a regression model?
Any suggestions would be much appreciated. Thank you.
Answer: A rough analogy: a convex function is shaped like a valley, a concave function is shaped like a hill. Regression uses maximum likelihood estimation, which is about maximising the log-likelihood function. In some cases, this maximum can be found with an analytic formula. In other cases, it needs to be estimated iteratively. The computer guesses a location and calculates the log-likelihood, then tries another location and sees whether the new log-likelihood is higher. If the computer is on a hill, it can find the summit by walking in whatever direction is uphill, but if it's in a valley, the best direction to walk in is less clear, and sometimes it may fail to find a summit if it gets stuck in a valley or on a flat plain.
Answer: https://en.wikipedia.org/wiki/Convex_optimization
Properties
The following are useful properties of convex optimization problems:[16][12]
every local minimum is a global minimum;
the optimal set is convex;
if the objective function is strictly convex, then the problem has at most one optimal point.
Comment: That is if a likelihood function shows this property then it has only one global minima?
Comment: consider linear regression. if you have linearly dependent variables, then you have a line/hyperplane of solutions. convex - global minima form a convex set (eg a line). If the variables are linearly independent (-> strictly convex objective function) then there is a unique solution