O que esta expressão quer dizer?

Question: Estou tentando instalar e usar o minio: https://github.com/minio/minio, e instalei o https://github.com/py-pa/django-minio-storage para user como storage no meu projeto do djando. Porém quando salvo uma image está me dando o seguinte erro:
File "/home/developer/.virtualenvs/store/lib/python3.5/site-packages/django/core/files/storage.py", line 358, in get_storage_class
    return import_string(import_path or settings.DEFAULT_FILE_STORAGE)
  File "/home/developer/.virtualenvs/store/lib/python3.5/site-packages/django/utils/module_loading.py", line 17, in import_string
    module = import_module(module_path)
  File "/home/developer/.virtualenvs/store/lib/python3.5/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 986, in _gcd_import
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load
  File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 661, in exec_module
  File "<frozen importlib._bootstrap_external>", line 767, in get_code
  File "<frozen importlib._bootstrap_external>", line 727, in source_to_code
  File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
  File "/home/developer/.virtualenvs/store/lib/python3.5/site-packages/minio_storage/storage.py", line 52
    **kwargs,
            ^
SyntaxError: invalid syntax

Que está nessa parte do código:
37     def __init__(
 38         self,
 39         minio_client: minio.Minio,
 40         bucket_name: str,
 41         *,
 42         base_url: T.Optional[str] = None,
 43         file_class=None,
 44         auto_create_bucket: bool = False,
 45         presign_urls: bool = False,
 46         auto_create_policy: bool = False,
 47         policy_type: T.Optional[Policy] = None,
 48         object_metadata: T.Optional[T.Dict[str, str]] = None,
 49         backup_format: T.Optional[str] = None,
 50         backup_bucket: T.Optional[str] = None,
 51         assume_bucket_exists: bool = False,
 52         **kwargs,
 53     ):

Então retirei a vírgula e o erro parou de cair ali, mas aconteceu em outros lugares:
raise OSError(f"The bucket {self.bucket_name} does not exist")
Aqui eu retirei o f antes da string e deixou de dar erro.
Porém começou a dar tambem nesta linha:
File "/home/developer/.virtualenvs/store/lib/python3.5/site-packages/minio_storage/storage.py", line 209
    dirs: T.List[str] = []

Nunca me deparei com esses erros, meu python está na verao 3.5 e a compatibilidade da biblioteca é Python 3.4-3.6. Estes erros de sintaxe são reais? E o que dizer esta expressão se ela existir? dirs: T.List[str] = []
Answer: Apesar da compatibilidade da biblioteca estar marcada como "a partir de 3.4", esse código está usando sintaxe específica de Python 3.6 para cima.
Olhando a página do projeto, no Pypi.python.org, de fato eles se listam como "compatíveis com Python 3.4" - mas trata-se de um erro de manutenção do pacote.
Então, quanto ao primeiro erro - eu nem sabia que de tinha mudado - mas testei aqui e é fato: apesar de Python aceitar uma "," extra sempre que tem uma estrutura separada por vírgulas, no contexto específico de definição de funções, não faz sentido ter qualquer parâmetro depois de um parâmetro marcado com ** - justamente por que esse é o "coringa" que vai absorver todos os demais argumentos passados em uma chamada. Entao até a versão 3.5, essa vírgula depois do parâmetro começado com "**" gerava um erro de sintaxe. Testei aqui na versão 3.6, e a sintaxe é válida (você vai ter erro se colocar qualquer coisa depois da vírgula - só passaram a permitir a vírgula solta, por que isso acabou virando uma exceção comparado com todos os outros pontos na linguagem em que vírgulas são usados como separadores).
Esse código, e os outros erros que você está obtendo, tem a ver com a sintaxe de "Annotations".
Desde o Python 3.0 é possível colocar os ":"  def funcao(nome: Tipo=valor_padrao) -> tipo_de_retorno: em uma definição de função em Python. Esses valores são objetos de Python que são colocados em um dicionário especial no atributo __annotations__ de uma função, e não fazem nada diretamente no programa, mas podem ser usados como documentação, e por ferramentas externas de verificação de tipos de variáveis.
A partir da versão 3.6 é possível também anotar com tipos as variáveis no corpo de classe e de funções - como a sintaxe onde ocorreu o próximo erro.
A expressão dirs: T.List[str] = []  cria ua variável dirs com uma lista vazia dentro - []. E junto com isso, cria pra essa variável a anotação T.List[str] - essa convenção foi adotada a partir da PEP 484, e indica que essa variável vai conter uma "Lista" cujos elementos devem ser todos "str".  Se o programa de fato faz isso, como dito acima, pode ser verificado por uma ferramenta externa - o "mypy". Sem essa ferramenta, a anotação serve apenas como dica de uso da variável: você bate o olho e já vê que ela deve ser uma lista, e os elementos devem ser string.  (Note que nesse caso específico, o autor do código usou import typing as T no começo do arquivo, para poder usar T.List, T.Optional - em vez de ter que importar individualmente todos os nomes from typing import List, Optional, Union, ... - eu adoto essa prática também e acho a melhor solução para o uso de anotações)
Mas tudo isso, só é válido a partir do Python 3.6
Melhor do que procurar uma versão antiga da biblioteca "minio" que funcione com Python 3.5, é você atualizar o seu projeto para usar um Python mais recente, como a versão 3.8 - estável desde novembro do 2019, ou a 3.7, lançada a quase dois anos já. O Python que acompanha o sistema operacional é o do sistema, e não pode ser atualizado sem quebrar tudo - mas ele não tem que limitar suas opções de projeto: você pode instalar versões mais recentes do Python como usuário, e usar ambientes virtuais para cada projeto. Uma das melhores opções para poder escolher a versão da linguagem é o PyEnv, mas há outras, como "snaps" e etc... (se você estiver no Windows, simplesmente instale um Python mais novo).

O que esta expressão quer dizer?


Como disparar uma função jQuery após o usuário parar de digitar?

Question: Tenho que fazer um sistema de pesquisa que mostra se um e-mail já está cadastrado em meu banco de dados, porém não sei como fazer para disparar uma função JS após 3 segundos que o usuário parar de digitar. Até tentei com com keyup mais não consegui. Alguém tem alguma base de como eu possa fazer isso?
Answer: É melhor usar input em vez de keyup, porque o keyup vai pegar qualquer tecla digitada, até mesmo TAB, SHIFT ou outra. O input vai chamar a função apenas quando algo for digitado no campo.
Você pode fazer desta forma:
var temporiza;
$("#email").on("input", function(){
   clearTimeout(temporiza);
   temporiza = setTimeout(function(){
      alert("Chama Ajax");
   }, 3000);
});

var temporiza;
$("#email").on("input", function(){
   clearTimeout(temporiza);
   temporiza = setTimeout(function(){
      alert("Chama Ajax");
   }, 3000);
});

<input type="email" id="email" placeholder="Digite o e-mail" />
Comment: vi um problema meio que bobo porem é essencial pra um bom funcionamento, o temporizador deve zerar cada vez que a tecla é pressionada me parece que dessa forma n ão funcionaria assim
Comment: @EstudantePHP Funciona desta forma: cada vez que um caractere é inserido no campo, o temporizador zera. Se achar melhor colocar `keyup`, funciona também, irá pegar qualquer tecla pressionada.
Comment: funcionou perfeitamente aqui obrigado :)


A função MAIL envia dois e-mails para o destinatário

Question: Utilizo a função mail em diversas partes dos meus projetos, porém, em uma aplicação esta função faz o envio de dois emails para o destinatário.
Não tenho ideia porque isso está acontecendo.
Segue o código completo:
<?php
include ("./incluir/conexao.php");

$vconteudo = trim($_GET['conteudo']);
$vmail = trim($_GET['emailcopia']);

$noticia_copia=mysqli_query($con,"SELECT id, slug, titulo FROM noticias WHERE id = $vconteudo GROUP BY id");
while($painel_noticias_copia=mysqli_fetch_array($noticia_copia))
    {
        $vid = $painel_noticias_copia['id'];
        $vslug = $painel_noticias_copia['slug'];
        $vtitulo = $painel_noticias_copia['titulo'];
    }

                $to = $vmail;
                $subject = $vtitulo;
                $message = "

Olá, inscrito!

Segue uma cópia do conteúdo que você solicitou.

Este material foi preparado com muita dedicação.

Pug: conheça tudo sobre a origem milenar da raça

Acesse agora mesmo www.portalvidapet.com.br/{$vid}/{$vslug}

                ";

                $headers = "From: Portal Vida Pet <firstname.lastname@example.com>\n";
                $headers .= 'MIME-Version: 1.0' . "\r\n";
                $headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";

                mail($to, $subject, $message, $headers);

            $cap_email=mysqli_query($con,"SELECT email FROM captura WHERE email = '$vmail' GROUP BY email");
            if (mysqli_num_rows($cap_email) < 1)
            {
                $painel=mysqli_query($con,"INSERT INTO captura(email) VALUES ('$vmail')");
            }

?>

Comment: Acho que o problema está no HTML. Como mencionou o Leandro, a página pode estar sendo chamada 2x.
Comment: a resposta te ajudou? Se sim, procure marcá-la para ajudar outros colegas.
Answer: Vamos lá algumas alternativas podem ser verificadas para isto não ocorrer mais:
1) Pressiona F12 no Chrome, vai na guia "Network", lá mostra todas as páginas que são acessadas. Veja se essa página não está sendo chamada duas vezes. Por exemplo, por ser chamada duas vezes uma por method post e outra document
2) Se aparecer duas vezes por exemplo, vc pode colocar um if no seu código para somente se for method post você enviar seu mail(), assim: (obs.: já aconteceu comigo e consegui resolver com o código abaixo)
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

//Seu código aqui

}

3) Se mesmo assim persistir, verifique sua action no form;
4) Se ainda assim persistir, crie uma variável de controle e salve no banco seu email enviado, assim verifique se já foi enviado e não envie novamente. Enfim, faria essas verificações para travar enviar duas vezes.
p.s.: procure usar phpMailer ao invés de mail()


Can someone explain to me why I cant pull out the constant when I take the variance?

Question: can someone explain why this is wrong:
$\epsilon_t$ is WN~ $(0,\sigma^2)$
$X_t=\frac{\epsilon_t}{1-\phi}$
$V(X_t)=V(\frac{\epsilon_t}{1-\phi})=\frac{V(\epsilon_t)}{(1-\phi)^2}$
$V(X_t)=\frac{\sigma^2}{(1-\phi)^{2}}$  Why is this wrong? $\phi <1$ is a constant
The solution which is right is
$V(X_t)=\frac{\sigma^2}{1-\phi^2}$
Its the variance of an AR(1) process.
Thank you in advance.
Comment: At a guess, there is a typo in the correct solution, since $\text{Var}(aX) = a^2 \cdot \text{Var}(X)$.
Comment: Is $\phi$ really a constant ? What is its definition ?
Answer: Hi: You are attempting to derive the variance of an AR(1) but you are skipping some steps. The AR(1) is
$X_t = \phi X_{t-1} + \epsilon_t$ where $\epsilon_t \sim N(0,\sigma^2)$.
First,  pull the first term over to the left using the lag operator.
$X_{t}(1-\phi L) = \epsilon_t$. Now when you divide by $(1 - \phi L)$, you end up with an infinite series on the right hand side.
$X_t = \frac{\epsilon_t}{1-\phi L}$.
Note that, as long as $\phi < 1$, then the right hand side is an infinite series that converges. So, we end up with:
$X_t = \sum_{t=0}^{\infty} \phi^{t} \epsilon_{t-i}$
Taking the variance of the sum results in:  $var(X_t) = \sum_{t=0}^{\infty} \phi^{2t} \sigma^2 =  \frac{\sigma^2}{1-\phi^2}$.
So, the issue was that the lag operator was left out which made the expression look like it wasn't an infinite series.
HERE IS AN EDIT TO PROVIDE AN ALGEBRIAC REASON WHY NORMAL VARIANCE RULES CANNOT BE USED ON A INFINITE SUM.
Let's suppose that the lag operator, $L$, is not even involved in order not to confound the issue.
Let:
$  1 + \rho + \rho^2 \ldots + \rho^n + \ldots  = A $.
and Let:
$ \frac{1}{1-\rho} = B $.
I'm not 100 percent certain but I think that the reason your squaring approach doesn't work is because $A^2 \neq B^2$. Take the case of $A^2$. When one takes expectations of the individual terms of the  square of the sum, all of the cross product terms are zero because of the independence of the $\epsilon_{i}$ and $\epsilon_{j}$ for $i \neq j$. Conversely, when one squares B, there is no knowledge of individual cross product terms reducing to zero.
If someone else can prove $A^2 \ne B^2$ in a less heuristic way, it's appreciated.
Comment: Can you explain why i cant use the rules for variances?
Comment: Shouldn't the solution be like this even without a lag operator?$\frac{\sigma^2}{1-\phi^2}$ because its the geometric series.
Comment: Hi: I tried to explain that in the answer but  it's essentially because you're initial expression: $X_t = \frac{\epsilon_t}{1-\phi}$ is not true. If it was, then you could do what you did.
Comment: Let me add a step so you can better see what's happening in terms of the infinite series.
Comment: $V(\frac{\epsilon_t^2}{1-\phi})=V(\epsilon_t^2+\epsilon_t^2\phi+\epsilon_t^2\phi^2...)=$

$1V(\epsilon_t^2)+\phi^2V(\epsilon_t^2)+\phi^4V(\epsilon_t^2)...=1\sigma^2+\phi^2\sigma^2+\phi^4\sigma^2...=\frac{\sigma^2}{1-\phi^2}$

Even without Lag operator its possible to derive the solution.

But I don't understand why I can't use the rule for variances to pull out the constant.
Comment: Hopefully now you can see how the lag operator enters into how one obtains the infinite sum.
Comment: you have a squared term in $V(\frac{\epsilon^2}{1-\phi})$ bt it's just a typo. In addition, I don't see how you are getting what you get because there's a $t$ subscript which has to go backwards in time. You can't just remove the lag operator because that's what causes the backwardness to happen. I think the answer is that what you wrote for V is not correct. There's an L in there so you can't use normal rules for variance because you need to expand the sum.
Comment: When you use "normal" rules for variance, you are assuming that the denominator is a constant but it's far from a constant. Specifically, you are using $var(ax) = a^2 var(x)$ which assumes that $a$ is fixed and constant.
Comment: That means a geometric series is not a constant?
Comment: I'm not a math person ( why is why I'm on this list !!! ) but, if your RV has a time subscript and you want to compute the variance of the random variable, then the expression needs to be re-written as an infinite sum of random variables if that is possible. Hopefully, someone else can give a more technical answer.
Comment: the  $(1-\phi L)$ in the denominator is not a constant like "a" is in my earlier example.
Comment: One more thing: Suppose that the $\epsilon_t$ variance was not constant, say $\sigma^2_t$. Then, you're geometric series expansion would not give the correct answer because you couldn't just remove the lag operator like you did.
Comment: @mth: Your question got me hooked ( to some degree. I'll stop and wait for a math person's feedback ) but  I added something to the bottom of the answer that helped me understand things more clearly.
Comment: Thanks for all your help @mark leeds.
I think i got it now.
In a geometric series the Numerator has to be a constant as well. Thats not given here since $\epsilon$ is a random variable. Without your help i would't have get it. Thanks so much.
Comment: @mth: I think that's the best way to think about it. I'm glad it helped.


How is memory handled in Python's Lists?

Question: See the code below, as you see when a=[1,2] that is a homogeneous type the address of 1st and 2nd elements differed by 32 bits
but in second case when a=[1,'a',3],there is no relation between address of 1st and 2nd element but there is relation between 1st and 3rd element that is address differs by 64 bits.
So I want to know how is memory handled and how indexing takes place and how is it linked to being non hashable (that is mutable)
>>> a=[1,2]
>>> print(id(a[0]))
4318513456
>>> print(id(a[1]))
4318513488
>>> a=[1,'a',3]
>>> print(id(a[0]))
4318513456
>>> print(id(a[1]))
4319642992
>>> print(id(a[2]))
4318513520
>>>

Comment: FYI - you forgot to include the 'code below'
Comment: Use code blocks to include code, not images.
Answer: In general, ids don't matter. Don't worry about ids. Don't look at ids. In fact, it's a CPython implementation detail that ids are memory addresses, because it's convenient. Another Python implementation might do something else.
In any case, you're seeing CPython's small integer cache (see e.g. this question), where certain integer objects are preallocated as "singleton" objects since they're expected to be used often. However, that too is an implementation detail.
The string 'a', on the other hand, is not cached (it might have been interned if your code had been loaded from a .py file on disk), so it's allocated from somewhere else.
As for your question about indexing, CPython (again, another implementation might do things differently) lists are, under the hood, arrays of pointers to PyObjects, so it's just an O(1) operation.


Create an Azure AD with different On premise AD name

Question: I'm trying to connect my On premise AD name : DOMAININT.ORG to my azure ad with a domaine name : DOMAINE.org.
On my office 365 all my user have their email adresses.
All configuration are good, i installed the plugin azure ad connect and configure it.
But i have a question. How can i link my office 365 user (azure ad) with my on premise ad. Because they have two differente domaine name.
Sorry for my english, i hope i explained corectly my question.
Have a good day.
Comment: Did you already have Office 365 accounts before you synced your on premises user accounts to Office 365? If so, do you now have two user accounts in Office 365 for each person?
Comment: Hello, yes i already have a office 365 before i started the syn and all my user are already created in the two side (separately). And i have an error when i try to synchronize :ExtraErrorDetails:
[{"Key":"ObjectId","Value":["988e5b29-f0c9-4bf6-9416-7a7a3903078d"]},{"Key":"ObjectIdInConflict","Value":["190811b2-0c8b-497b-90c0-bcd7bb94a6e5"]},{"Key":"AttributeConflictName","Value":["ProxyAddresses"]},{"Key":"AttributeConflictValues","Value":["SMTP:firstname.lastname@example.com"]}]
Comment: The error deseapear , a deleted the @mail. But two accounts are create. But how can i link the two different account in one ?
Answer: You'll need to match the on premises users to the existing Office 365 users.
To do that you'll need to unsync the on premises users and permanently delete them in Office 365, then resync them, after making a few changes:

Reconfigure Azure AD Connect to sync an empty OU.
This will delete the synced users in Office 365. Make sure that only the on premises synced user accounts are deleted in Office 365. You then need to remove these users from Deleted users in Office 365.
Create a UPN suffix in your on premises AD that matches your verified domain in Office 365. This UPN suffix should be the same as the User Principal Name (login name) of your Office 365 user accounts. Example: UPN Suffix = mycompany.com, UPN = email@example.com
Set this UPN suffix on all of your on premises user accounts.
Reconfigure Azure AD Connect to sync your entire domain.
The on premises users should now sync and match to the existing Office 365 users.


Android: Clickable hyperlinks in DialogPreference

Question: What I'm trying to accomplish: create a clickabel hyperlink in the message text displayed by a DialogPreference.
My solution so far: follow this topic: link , and I am accomplished a formating hyperlink displayed in the DialogPreference, but this hyperlink not clickable.
Question:How to make the hyperlink clickable in the DialogPreference.
my code:
public class AboutDialog extends DialogPreference {
public AboutDialog(Context oContext, AttributeSet attrs)
{
    super(oContext, attrs);
    final SpannableString s = new SpannableString(oContext.getText(R.string.about_text));
    Linkify.addLinks(s, Linkify.ALL);
    this.setDialogMessage(s);
}}

Answer: Well, I am not sure but try this :

Create textView, set your string s as it's text, using yourTextVeiw.setText(s)
set onClickListener for this textView
Now set this textView into dialog, try using addView(textview) , method.
Comment: viv, thanks very much for your reply. But it doesn't work. the DialogPreference just has onBindView(View). I tried various methods in your way, but it doesn't work. now I try to use other API take over the DialogPreference:)
Comment: You are a nice guy. I wanna accomplish a "About" Dialog in the PreferenceScreen and add a clickable hyperlink in the "About" Dialog, so I stuck in there:)
Comment: well ycz, it's getting a bit tricky for me atleat, there is a onCreateDialogView(), method which returns View, so if it can be overrided, but just clarify me one thing, do you want to show hyperlink in some dialog type of view or only in  DialogPreference, is it(DialogPreference) that much mandatory, i mean why not use a simple dialog ....
Comment: -_-! Because My App already has 4 icons in the main menu, I am very lazy, I won't to draw a new icons for the "About dialog". and I did a lot of search for "how to create a dialog in the Preferencescreen", but I just found using DialogPreference. well it seems I will do some art work :)
Comment: ha ha, well i am getting helpless with DialogPreference at present, in case in future if you don't get any workaround with DialogPrefernce, you can do it with simple dialog, i will also be able to help in that case, as i have used them frequently, just leave a comment in future here and i will be notified, hope you get what you want to achieve, god bless you ....
Comment: thanks again, god bless you :) finally I add a item in menu for about dialog and save the unclickable link about dialog" in the preference:)
Answer: This seems to work
package net.anei.cadpage.preferences;

import android.content.Context;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.text.util.Linkify;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;

public class DialogPreference extends android.preference.DialogPreference {
  public DialogPreference(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  public DialogPreference(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
  }

  @Override
  protected View onCreateDialogView() {
    final SpannableString s = new SpannableString(getDialogMessage());
    Linkify.addLinks(s, Linkify.WEB_URLS);
    final TextView view = new TextView(getContext());
    view.setText(s);
    view.setMovementMethod(LinkMovementMethod.getInstance());
    return view;
  }
}


Is it possible to update Drupal page cache right after it is cleared?

Question: I am trying to improve Drupal performance and I have all the tuning usual suspects setup:

Varnish
Memcache
APC
Drupal core cache

From what I understand when you clear the Drupal cache it does not replenish page caches until an anonymous end user makes a request for the page. Drupal then builds the cache and the following page requests are snappy. The problem with this is the non cached call can take 2- 4 seconds to finish. We would like all page requests to be as snappy as a cached request. So we are looking into either a way auto replenish or set up a cron that would hopefully make the non cached page request before an end user.
If my assumptions are correct is there a module or way to automatically replenish all page caches? I am assuming that since this does not automatically happen that it is potentially a resource issue to cache the entire site at once. But if we set Drupals cache to live for 1 or 2 days and cleared cache on a cron in the middle of the night it might be ok to automatically replenish. Has anyone ever tried to solution this?
Comment: Related (but I don't think an exact dupe): http://drupal.stackexchange.com/questions/29175/how-to-rebuild-a-cached-page-when-it-expires
Comment: Yes similar, I would like to avoid a cron job to warm the cache as you would not be able to guarantee the timing. A small percentage of users would be warming the cache.
Answer: Cache Warmer Module is the one you are looking for.

cache_warmer is a drush command that hits a set of URIs of a drupal
  site based on the freshness of the content.

It is a drush integration for warming the caches using httprl, which means calls can be made parallely as well.
Since it is a drush extension you can tie it up easily with your cron as well.


How much dynamics, tempo fluctuation is acceptable in Baroque music on piano? How to achieve expressivity?

Question: I'm not talking about exaggerated rubato and a deliberate Liberace-style soup of genres, but is it acceptable to add some dynamics and some tiny tempo fluctuations when playing Baroque on piano to accentuate phrasing?
How much is too much?
I know that it is hard to draw a line, but I guess there is a limit beyond which it gets frowned upon (even if great pianists sometimes may ignore it altogether).
How else are you supposed to pursue musicality in Baroque repertoire on a piano?
Can anybody point to any examples (from amateurs on Youtube, perhaps?) of good and bad playing in this respect?
Answer: The main problem with tempo and dynamic variations in baroque music is that baroque music tends to be polyphonic with independent voices and skewed themes.  Volume changes cannot be done independently without having the transparency of the polyphony suffering, and tempo changes in mid-strife tend to hit different themes in the voices in different state of progress.
So the main opportunities for significant changes happen at times of resynchronization, like a non-polyphonic chorded passage after a fermata, or a chant passage.  Of course the latter mainly applies to singing.
Random changes in tempo or volume are not "musicality".  Musicality arrives from organically dealing with music and expression.  In polyphonic music, it's about making the individual voices coherent by tieing them together with consistent articulation and phrasing.
With piano music, it can be excellently hard to give one line running through different fingers and hands a distinctive phrasing and dynamic flow separately from other lines.  And to keep a level of similarity of the phrasing and dynamics of various themes as they are taken up by different voices.
That's a lot harder and requires a lot more musicality than imposing some irregularities on basically monorhythmic music.
Comment: It's a very good and detailed answer but I do not agree that 'tempo fluctuations' are anything close to the same as 'random changes in tempo'.  The former is used all the time in Baroque recordings (at least the ones I listen to), the latter is a sign of disconnected thinking and lack-of-skill.  But perhaps you are right in listing it as something to be wary of, because it should come naturally as a part of musicality and be so subtle as to NOT be defined as 'tempo fluctuations', if that's how you meant it.
Comment: Wow. Welcome to SE and what a great answer.

So I take it that you are supposed to concentrate your efforts on making the polyphonic clockwork work well instead of being "expressive", which may eventually stem from that.

Am I correct?
Answer: It depends whether you are trying to imitate the harpsichord or the clavichord. The harpsichord doesn't have "touch sensitive" dynamics - if a note plays at all it is at its full volume. That is an advantage for polyphonic music, because nothing can "get lost", and you can still bring individual parts using articulation rather than dynamics. For fast playing, the piano can't compete with the harpsichord for the combination of speed and clarity.
The clavichord is a completely different animal. It is just as touch sensitive as the piano, plus you can play vibrato and/or tweak the tuning of individual notes by varying the pressure on the key after it is struck (of course doing that in a controlled manner is a bit more difficult than playing the piano!) The only (big) disadvantage of the clavichord is that it's a very quiet instrument, completely unsuitable for use in a concert hall unless it is amplified, and difficult to record well. Youtube is full of clavichord videos that sound nothing like a clavichord.
Compare these for yourself. The same performer and the same piece, on piano and clavichord. IMO the piano doesn't come close


How to interpret the deviance plot by boosting models

Question: This plot is taken from a gradient boosting regression example in the scikit-learn documentation.
What does deviance mean? How should this plot be interpreted? In which case do we have over/underfitting? What improvements can we make to the model parameters based on this plot?
<code># Author: Peter Prettenhofer <email@example.com>
#         Maria Telenczuk <https://github.com/maikia>
#         Katrina Ni <https://github.com/nilichen>
#
# License: BSD 3 clause

import matplotlib.pyplot as plt
import numpy as np

from sklearn import datasets, ensemble
from sklearn.inspection import permutation_importance
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split

diabetes = datasets.load_diabetes()
X, y = diabetes.data, diabetes.target

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.1, random_state=13
)

params = {
    "n_estimators": 500,
    "max_depth": 4,
    "min_samples_split": 5,
    "learning_rate": 0.01,
    "loss": "squared_error",
}

reg = ensemble.GradientBoostingRegressor(**params)
reg.fit(X_train, y_train)

mse = mean_squared_error(y_test, reg.predict(X_test))
print("The mean squared error (MSE) on test set: {:.4f}".format(mse))
# The mean squared error (MSE) on test set: 3025.7877

test_score = np.zeros((params["n_estimators"],), dtype=np.float64)
for i, y_pred in enumerate(reg.staged_predict(X_test)):
    test_score[i] = mean_squared_error(y_test, y_pred)

fig = plt.figure(figsize=(6, 6))
plt.subplot(1, 1, 1)
plt.title("Deviance")
plt.plot(
    np.arange(params["n_estimators"]) + 1,
    reg.train_score_,
    "b-",
    label="Training Set Deviance",
)
plt.plot(
    np.arange(params["n_estimators"]) + 1, test_score, "r-", label="Test Set Deviance"
)
plt.legend(loc="upper right")
plt.xlabel("Boosting Iterations")
plt.ylabel("Deviance")
fig.tight_layout()
plt.show()
</code>
Comment: If you post some of your code where you specify the deviance or (more likely) the likelihood used in your boosting model, we can say a bit more about what your value means and how it is calculated. Technically, deviance is a function that satisfies a few axioms, but there are typical functions that have statistical meaning.
Comment: Does something in the documentation say that you are getting "deviance" values? Your code shows that you wrote that word yourself, and while it has a meaing in statistics that makes sense in this context, you just as easily could have used "Squid" as your axis label.
Answer: Deviance is a measure of model quality typically (but, I suppose, not necessarily) related to the likelihood. The lower the deviance, the better the model fit. Perhaps think of it this way: models are good when, in some sense, the predicted values are close to the observed values, and deviance is the quantification of what it means to be close. Deviance functions do not, necessarily, satisfy the axioms of a metric space, so "distance" between true and predicted values need not apply, but that's why we call it the "deviance" between true and predicted values.
Out of context, it is hard to say if your deviance value of $\sim$$3000$ is too high to make for a good model. In general, it is hard to say if a particular measure of performance is good without some reference to the context. One takeaway from the plot, however, is that out-of-sample performance improves quite minimally after about $150$ boosting iterations. You don't seem any worse off for continuing your boosting iterations beyond $150$ or $200$, as the training deviance does not start to shoot up, but the time you spend (which migh also involve money if you have to buy that time on a service like AWS) is not leading to much improvement and could be argued not to be worth performing.
EDIT (It's mean squared error.)
From the code, it is evident that deviance is calculated as the mean squared error. In this case, deviance is calculated as $\dfrac{1}{n}\overset{n}{\underset{i = 1}{\sum}}\left(y_i - \hat y_i\right)^2$. Why they elect to refer to this quantity as the more obscure "deviance" instead of the quite typical "mean squared error" is not clear. Perhaps the goal is to to be general, so the axis labels would apply even if a binomial deviance were used, such as in a binary "classification" problem. Still, I am not sold on the pedagogy.


How to find the probability distribution and we are given the expected value and variance?

Question: The question is:
A random variable $Y$ can only take values in $\lbrace−10, 0, 10 \rbrace.$ The expected value of $Y$ is $0$ and its variance is $80.$ Find the probability distribution of $Y.$
Comment: Have you tried anything?
Answer: Hint:
It works for your case of 3 variables because you have 3 unknowns and but you also have 3 equations, one from normalization of probabilities, one from mean, one from variance.


Relacionamento de uma coluna para várias

Question: Tenho uma classe entidade de nome Medico, na qual possui uma coluna IDMedico. Ela se relaciona com a classe entidade Atendimento, que por sua vez possui uma coluna IDmedico, que seria uma chave estrangeira dessa primeira.
Há também nessa tabela, Atendimento, uma outra coluna chamada IDMedicoIndica, que tambem é uma chave estrangeira da coluna IDMedico da entidade Medico. Ou seja, na tabela Medico possue apenas uma coluna com ID dos médicos e no atendimento eu preciso ter o id do médico que executa e do que indica.
Quando tento relacionar da mesma forma que fiz com o IDMedico, porém mudando o nome da coluna, me é retornado um erro dizendo que não foi possível encontrar a coluna IDMedicoIndica na entidade Medico. Como posso proceder e qual a melhor prática nesse caso?
Segue os código:
@Entity
@Table(name = "Sis_Medico")
@PrimaryKeyJoinColumn(name = "IDMedico", referencedColumnName = "IDPessoa")
public class Sis_Medico extends Sis_Pessoa {

    @Column(name = "IDMedico", insertable = false, updatable = false)
    private Long IDMedico;

        @OneToMany(mappedBy = "medico", fetch=FetchType.LAZY, cascade = CascadeType.ALL)
        private List<Sis_Atendimento> atendimentos = new ArrayList<>();

        @OneToMany(mappedBy = "medicoIndica", fetch=FetchType.LAZY, cascade = CascadeType.ALL)
        private List<Sis_Atendimento> atendimentosIndica = new ArrayList<>();

@Entity
@Table(name = "Sis_Atendimento")
public class Sis_Atendimento {

    @Id
    @Column(name = "IDAtendimento")
    private Long idAtendimento;

    @ManyToOne
    @JoinColumn(name = "IDMedico",
                referencedColumnName = "IDMedico",
                foreignKey = @ForeignKey(name = "SisMedico_SisAtendimento"))
    private Sis_Medico medico;

    @ManyToOne
    @JoinColumn(name = "IDMedicoIndica",
                referencedColumnName = "IDMedico",
                foreignKey = @ForeignKey(name = "SisMedico_SisAtendimento"))
    private Sis_Medico medicoIndica;

O código assim faz até o deploye roda, mas o problema é que quando eu tento chamar a coluna IDMedicoIndica do Atendimento em uma @Query ele dá erro.
@Query("select Atendimento.idAtendimento, Atendimento.dataAtendimento, \n"
            + "paciente.IDPaciente, medico.IDMedico, Atendimento.IDMedicoIndica, Atendimento.desativado \n"
            + "from Sis_Atendimento Atendimento")

Comment: Pode postar seus códigos (anotações )?
Comment: Posso sim, vamos lá:
Answer: Ao usar entidades do JPA e escrever um JPQL, você precisa referenciar os nomes das colunas na entidade e não o nome das colunas na tabela, a não ser que você queira fazer uma consulta nativa (native query).
Se o seu desejo é rodar um SQL e não um JPQL, basta incluir o atributo nativeQuery com o valor true e usar os nomes reais das tabelas e colunas:
@Query("select Atendimento.idAtendimento, Atendimento.dataAtendimento, "
        + "Atendimento.IDMedico, Atendimento.IDMedicoIndica, Atendimento.desativado "
        + "from Sis_Atendimento Atendimento", nativeQuery = true)

Se o seu desejo é usar JPQL, faça:
@Query("select at.idAtendimento, at.dataAtendimento, "
        + "medico.IDMedico, at.IDMedicoIndica, at.desativado "
        + "from Sis_Atendimento at JOIN at.medico medico", nativeQuery = true)

PS.: removi a parte do paciente.IDPaciente por não ter compartilhado o relacionamento de paciente com o restante das tabelas, mas a ideia é a mesma.


Call absolute address in x64

Question: I could not figure this out, I can make an instruction like this and it works no problem
call ffffdd80d60e4000

But how would I go about converting this into bytes? I looked at the instruction in memory and shows weird stuff like
0xe8 0x00 0x40 0x0e 0xd6

The only thing I can identify is the e8 which is the call opcode. Can someone explain what the other 4 bytes are and how would I go about converting an instruction like this into a byte array if the address I need to call is a DWORD64 value? I tried and I can't simply copy the bytes of the address and add an 0xe8 at the start.
Sorry if it might be a dumb question, but I searched through books and websites and couldn't find anything about it.
Comment: It's a relative address. You need to know the address of the current (actually the following) instruction and calculate the difference to the target. See also section _220.127.116.11 Unconditional Transfer Instructions_ in the basic architecture manual.
Comment: You looked wrong. The manual says: _E8 cd CALL rel32 Call near, relative, displacement relative to next instruction._
Comment: Hmm, ok, thanks. It's weird cause I was looking at the x64 asm documentation and it said that an e8 is a call to a absolute address. Guess I can just calculate it then.
Comment: related: encoding a `call` instruction manually with `target - ($ + 5)` in NASM: [How does $ work in NASM, exactly?](https://stackoverflow.com/q/47494744).
Answer: As Jester said, normally a call uses a relative address. If you want to use an absolute address, you can put the destination in a register like this:
    48 b8 00 40 0e d6  mov rax, 0xffffdd80d60e4000
    80 dd ff ff
    ff d0              call rax

You can also call an address that is in memory. For example if the destination address is in memory at [rsp+8], then
    ff 54 24 08        call [rsp+8]

Comment: Yeah, I was thinking about putting it in a register before, but it's not really gonna work for my purpose, since this instruction is gonna be called every second or less  and the registers value would be overwritten.

Call absolute address in x64


How can I access an Instance Store Volume in an ECS Task?

Question: I have a Docker image that downloads a large data set, processes it, creating a ton of temporary files in the process and then uploads the final result to S3. I don't need the temp files to be persistent / survive an instance failure, so I want to use instance store for this. For some reason, Docker refuses to use it though.
In my Launch Configuration, I selected an instance type with instance store (c3.8xlarge), then added the two Instance Store volumes as /dev/xvdcz and /dev/sdb.
In the user data, I mount the sdb volume and make it writable:
sudo mkdir /media/storage
sudo mount /dev/sdb /media/storage
sudo chmod o+rw /media/storage

In the task definition, I create a volume named "InstanceStorage" with the source path "/media/storage" and in the container definition, I added a Mount Point for this volume at /storage.
When I now ssh into the instance while the task is running, and I look at the host's /media/storage directory, it's empty. The task logs clearly show that it can write to the /storage directory of the container. It's just much smaller than the Instance Store - 7.8 GB available instead of 300.
I tried to manually run the Docker container and attach the volume:
docker run -it -v /media/storage:/storage --entrypoint /bin/sh my-docker-image:latest

Same behavior: I can write to /storage, the files even survive exiting and restarting the Docker container, but it's way too small and any files I create in /storage inside the container don't exist in /media/storage on the host.
Looking at df -h at both the host and the container, it becomes clear that it mounted /dev/xvda1 instead -- the volume that also stores the docker images.
Host:
Filesystem      Size  Used Avail Use% Mounted on
/dev/xvda1      7,8G  848M  6,9G  11% /
devtmpfs         30G   88K   30G   1% /dev
tmpfs            30G     0   30G   0% /dev/shm
/dev/xvdb       315G   67M  299G   1% /media/storage

Container:
Filesystem                Size  Used Avail Use% Mounted on
/dev/mapper/docker-(...)  9.8G  1.1G  8.2G  12% /
tmpfs                      30G     0   30G   0% /dev
tmpfs                      30G     0   30G   0% /sys/fs/cgroup
/dev/xvda1                7.8G  848M  6.9G  11% /storage
shm                        64M     0   64M   0% /dev/shm

Why would it do that?
Answer: I finally found the solution. This script pointed me in the right direction.
You need to restart the Docker service.
Apparently, Docker starts before the user data scripts are executed, and it can only access volumes that were mounted when the service started.
So I added this to the end of my userdata script, and that fixed it:
sudo service docker restart


Curiosidade sobre igualdade de Integers

Question: Por que
System.out.println(Integer.valueOf("0")==Integer.valueOf("0"));
System.out.println(Integer.valueOf("1000")==Integer.valueOf("1000"));

retorna
true
false

?
ps. eu sei que == é diferente de equals()
Answer: Porque a classe Integer faz cache dos valores entre -128 e 127.
Olhe isso:
System.out.println(Integer.valueOf("-129") == Integer.valueOf("-129")); // Dá false.
System.out.println(Integer.valueOf("-128") == Integer.valueOf("-128")); // Dá true.
System.out.println(Integer.valueOf("127") == Integer.valueOf("127")); // Dá true.
System.out.println(Integer.valueOf("128") == Integer.valueOf("128")); // Dá false.

Eis aqui alguns trechos do código fonte da classe Integer, tal como implementado na OpenJDK:
private static class IntegerCache {
    static final int low = -128;
    static final int high;
    static final Integer cache[];

    static {
        // high value may be configured by property
        int h = 127;
        String integerCacheHighPropValue =
            sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
        if (integerCacheHighPropValue != null) {
            int i = parseInt(integerCacheHighPropValue);
            i = Math.max(i, 127);
            // Maximum array size is Integer.MAX_VALUE
            h = Math.min(i, Integer.MAX_VALUE - (-low));
        }
        high = h;

        cache = new Integer[(high - low) + 1];
        int j = low;
        for(int k = 0; k < cache.length; k++)
            cache[k] = new Integer(j++);
    }

    private IntegerCache() {}
}

public static Integer valueOf(int i) {
    assert IntegerCache.high >= 127;
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}

public static Integer valueOf(String s) throws NumberFormatException {
    return Integer.valueOf(parseInt(s, 10));
}

Comment: A explicação está correta. Porém, não se atenha a este código fonte da classe Integer pois não é o código da Oracle que está na JVM padrão. É o código da openjdk, que pode ou não ser igual à implementação original.
Comment: @pablosaraiva Obrigado pela dica. Já atualizei o texto para esclarecer este ponto.
Comment: Lembrando que há como manipular o tamanho desse cache.
Answer: Isso é porque a Classe Integer usa o padrão de projeto FlyWeight.
A classe Integer cria um objeto Singleton imutável para cada um dos números de -128 a 127 para que assim esses objetos possam ser compartilhados por toda a aplicação gerando economia de memória.

Curiosidade sobre igualdade de Integers


Download link in jsp doesn't work

Question: I am using apache tomcat and i have some files in my system, I am creating links of these files with the below JSP code.
<%
File files = new File("/Users/user1/tests");
File[] fileList = files.listFiles();
for(int i=0; i<fileList.length;i++) {
    File f = fileList[i];
    out.println(i+". "+f.getName()+"");
}
%>

Now the links are generated fine, but when i click on these links apache is throwing 404 error. How can i make apache to access that folder.
Answer: On local system if your file is in another directory except to current web directory You need to set full absolute path of file to download a file using href.
Syntax is:-
out.println(i+". "+f.getName()+"");

Comment: It didn't solve the issue so i have created a separate servlet to download the file. Thanks you all
Comment: it is showing clearly in the question that is is not windows.
Comment: what os are you using?
Comment: lets try and guess `new File("/Users/user1/tests");`
Comment: a) who said I downvoted? b) why do you think the OP is using windows?
Comment: It is obvious that I am using Mac or linux, but it is Mac
Comment: how is that different to my answer?  Also, the OP was originally using getAbsolutePath, so your explanation does not make sense.
Comment: We need to put only 2 slashes after file: one slash is already coming from absolutePath() function, but now the problem comes in browser, it is showing "not able to load local resource" in its console
Comment: @SumitKumar Do one thing print this line in console and try to run it in browser manually. `file:///"+f.getAbsolutePath()+"' >"+f.getName()'
Comment: @SumitKumar please close this question

Download link in jsp doesn't work


Cannot trigger CKEditor WYSIWYG in form API

Question: I'm using Drupal 7.18 with CKEditor 4.3 (full package), and trying to get a WYSIWYG field via the form API. My code:
function article_edit_form($form, &$form_state, $article)
{
    // ...

    return array(
        // ...
        'content'  => array(
            '#type'    => 'text_format',
            '#title'   => t('Content'),
            '#format'  => 'full_html',
            '#wysiwyg' => true,
            '#input_format' => '1',
            '#value'   => array(
                'value'  => is_null($article) ? '' : $article->content,
                'format' => 'full_html'
            )
        ),
        // ...
    );
}

But this only displays a regular textarea with a section to choose the "text format". The CKEditor is installed, enabled and I'm logged as admin.
Comment: Is CKEditor enabled for `full_html`, not just `filtered_html`?
Comment: @Clive Yes it is.
Answer: There are a couple of things that you could try changing:

#input_format and #wysiwyg are not in the list of available properties for a text_format element, so even if they're not causing the error, you should probably remove them.
You shouldn't set the #value of an element like that (unless it's a value type itself). Instead you should use #default_value. In the case of a text_format the #default_value is expecting the text for the text area (since you've already set the format with #format).

I would expect this to work (certainly does for me if memory serves), but if not, check the console for JS errors
return array(
    // ...
    'content'  => array(
        '#type'    => 'text_format',
        '#title'   => t('Content'),
        '#format'  => 'full_html',
        '#default_value' => is_null($article) ? '' : $article->content
    ),
    // ...
);

Comment: The editor is still not showing.
Comment: Works perfectly for me, your problem must be somewhere else


Allegro não executa nada gráfico

Question: Ele simplesmente não aparece nada gráfico, o funcional (fechar a janela) funciona perfeitamente, porém o gráfico (cor de fundo e a "nave") não funcionam.
<code>#include <allegro5\allegro.h>
#include <allegro5\allegro_native_dialog.h>
#include <allegro5\allegro_primitives.h>
#include "objetos.h"

const int height = 800;
const int width = 600;

void InitNave(NaveEspacial &nave);
void DesenhaNave(NaveEspacial &nave);

int main(void)
{
        ALLEGRO_DISPLAY *display = NULL;
        ALLEGRO_EVENT_QUEUE *fila_eventos = NULL;

        bool end = false;

        NaveEspacial nave;

        if(!al_init())
        {
                al_show_native_message_box(NULL, "AVISO!", NULL, "FALHA AO CARREGAR ALLEGRO", NULL, NULL);
                return -1;
        }

        display = al_create_display(height, width);

        al_init_primitives_addon();

        fila_eventos = al_create_event_queue();

        al_register_event_source(fila_eventos, al_get_display_event_source(display));

        if(!display)
        {
                al_show_native_message_box(NULL, "AVISO!", NULL, "FALHA AO CARREGAR O DISPLAY", NULL, NULL);
                return -1;
        }

        InitNave(nave);

        while(!end)
        {
                ALLEGRO_EVENT ev;
                al_wait_for_event(fila_eventos, &ev);

                if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
                {
                        end = true;
                }

                DesenhaNave(nave);

                al_flip_display;
                al_clear_to_color(al_map_rgb(0, 0, 0));
        }

        al_destroy_display(display);
        al_destroy_event_queue(fila_eventos);

        return 0;
}

void InitNave(NaveEspacial &nave)
{
        nave.x = 20;
        nave.y = height / 2;
        nave.ID = JOGADOR;
        nave.vidas = 3;
        nave.velocidade = 7;
        nave.borda_x = 6;
        nave.borda_y = 7;
        nave.pontos = 0;
}
void DesenhaNave(NaveEspacial &nave)
{
        al_draw_filled_rectangle(nave.x, nave.y - 9, nave.x + 10, nave.y - 7, al_map_rgb(255, 0, 0));
        al_draw_filled_rectangle(nave.x, nave.y + 9, nave.x + 10, nave.y + 7, al_map_rgb(255, 0, 0));
        al_draw_filled_triangle(nave.x - 12, nave.y - 17, nave.x + 12, nave.y, nave.x - 12, nave.y + 17, al_map_rgb(0, 255, 0));
        al_draw_filled_rectangle(nave.x - 12, nave.y - 2, nave.x + 15 , nave.y + 2, al_map_rgb(0, 0, 255));
}
</code>
Comment: Me parece que você inverteu a largura com a altura. A sua lógica dentro do `while` está esquisita, pois me parece que isso significa que ele só irá desenhar quando receber algum evento, inclusive o evento de fechamento. Aliás, o que há no `"objetos.h"`?
Answer: Você esqueceu os parênteses no al_flip_display(). Sendo assim, o display nunca será atualizado a cada iteração (E você nunca verá a nave (Nem nada)).
Comment: Funcionou, obrigado
Comment: De nada :). Me adiciona aí depois (Meu Facebook está no meu perfil aqui do stack). Também desenvolvo com Allegro, e estou criando uma engine em C++ para ele.

Allegro não executa nada gráfico


Java import packages understanding

Question: i'm learning Java for one year now and this question is confusing me.
At the moment i'm working with Java Swing and i want to know why i have to write the line
import java.awt.event.*;

when i want to use the actionListener even when i've already imported the whole awt package before :/
import java.awt.*

why do i have to tell the compiler to import a Sub-package (is it the right name?), for instance the event package, when i already imported everything under the awt package?
Thanks alot!
Comment: Because java.awt and java.awt.event are two different packages. import java.awt.* imports classes from the java.awt package. Not from java.awt.event. Google for "java tutorial import", click on the first link: https://docs.oracle.com/javase/tutorial/java/package/usepkgs.html. And surprisingly enough, it has the answer you're looking for.
Answer: Because each package is separate. They don't have a parent-sub relationship.
import java.awt;

doesn't mean that java.awt.event is imported.
Comment: It would be great to understand the structure of java libraries!
Comment: @Murad_Alm. It has nothing to do with 'structure'. It has to do with the fact that importing an entire package doesn't import its sub-packages, which in turn is due to the fact that that's the way they designed it.
Comment: Tanks a lot mate!

Java import packages understanding


Rails convention for a polymorphic model + controller

Question: I have users, groups, and pages. Each record can have pictures.
Here is my architecture:

Polymorphic model for Pictures. Users, groups, and pages are picturable.
Nested pictures controller for each of users, groups, and pages (e.g. users/5/pictures)

Is this the most standard set up? Am I forgetting any Rails convention?
routes.rb example looks like this:
resources :users do
  resources :pictures

pictures_controller.rb looks like this:
class PicturesController < ApplicationController
  before_filter :load_picturable

  def show
    @picture = @picturable.pictures.find(:id)
  end

  # Get permissible for different objects.
  def load_picturable
    resource, id = request.path.split('/')[1,2] # /photos/1
    # Couples this controller to format of URL, not ideal.
    @picturable = resource.singularize.classify.constantize.find(id)
  end
end

Comment: Looks good for me, but maybe someone could suggest better solution.
Answer: Yup. That's pretty much what I've been using from my past projects that have required polymorphic image models.
In my latest project, I labelled my polymorphic relation as uploadable and I used the same approach to get URL data.
def load_uploadable
    resource, id = request.path.split('/')[1,2]
    @uploadable = resource.singularize.classify.constantize.find(id)
end

Here's my show function if it helps.
def show
@asset = Asset.find(params[:id])
@assets = @uploadable.assets
respond_to do |format|
  format.html
  format.json { render json: @asset}
end

end


Obtain intermediate variables assignments

Question: I am trying to use Prolog to represent state of a room.
I have a set of rules and a set of facts, but sometimes some of the facts are
not defined. For instance, temperature in a room can decrease due to either
cooling or opening a window, but sometimes I do not have a window sensor.
% Rules

temperature_trend(decrease) :-
    cooling(on).
temperature_trend(decrease) :-
    window(open).

% Facts

cooling(off).

%window(close).  % Unknown, I do not have a window sensor

% Main

main() :-
    temperature_trend(decrease).

If I run this program I would get an undefined procedure error. I can deal with
this by explicitly setting the window
status to "anything" with window(W). (I programmatically prepare the Prolog
source, so this is quite easy).
Now the query temperature_trend(decrease)
would succeed because window(W) would lead to window(open). However, in this
case I want to know that W = open.
Is there a way to return the variable assignments for this fact? Or maybe am I approaching the problem in the wrong way?
Note that the
rule tree could be arbitrarily deep, for instance I could add a new rule next_temperature(lower) :- temperature_trend(decrease). and I still
want to know that next_temperature(lower) succeeds only by setting W = open. Terms are also more complex
because they also have a time index (T = 232).
Maybe one option would be to return a list of assignments, which would be empty
if all facts were known.
Comment: Declare `window/1` as dynamic so that `window(X)` query will simply fail if the facts don't exist. `:- dynamic(window/1).`
Comment: Ideally I do not want it to fail if the fact does not exist. I want it tell me it would succeed by adding such fact.
Comment: Well, of course it will succeed by adding such a fact, by definition. So I'm not sure what you mean by that. Without declaring it dynamic, if there's no match to the query via fact or predicate, you get an interpreter error that it doesn't exist. If you declare it dynamic, and make the query, and it doesn't exist, the query simply fails as if the facts/predicates were there, but there was not match. Maybe you need a clearer example shown in your question.
Comment: If I add `window(W).` as a fact, the interpreter will "assign" `W = open` and the query would succeed. I want to know that such "assignment" happened, i.e., that the query would succeed by adding `window(open).` to my facts.
Answer: Write a meta-interpreter that gives you what is true, e.g.,
prove(Goal, True) :-
    phrase(prove(Goal), True).

prove(true) -->
    !.
prove((A,B)) -->
    !,
    prove(A),
    prove(B).
prove((A;B)) -->
    !,
    (   prove(A)
    ;   prove(B)
    ).
prove(Fact) -->
    [Fact],
    { clause(Fact, Body) },
    prove(Body).

Now, given window(_), we get:
?- prove(temperature_trend(decrease), L).
L = [temperature_trend(decrease), window(open)].

Lots of variations are possible!
Comment: Ideally I would like it to tell me only the "new" facts (so only `window(open)`). However, that is definitely a step in the right direction. I will make some experiments with this.


proportional meta-analysis, small confidence intervals and I square of 100 %?

Question: I am performing a meta-analysis of proportions, I have data about the number of cases and the total sample sizes.
I will be using the Freeman-Tukey double arcsine (Freeman & Tukey, 1950; Miller, 1978) to adjust the proportions so that they are between 0.2 and 0.8.
But when I plot data with confidence interval, the confidence intervals are so small and the I square is 100%? what is the problem?
Note: am using R
Answer: What you are seeing is entirely consistent. If you have very narrow confidence intervals you will see very high values for $I^2$. In a paper entitles "Undue reliance on $I^2$ in assessing heterogeneity may mislead" available here Rücker and colleagues explain why this is. Basically it is because you are comparing within study and between study variability. If the within is very small then, all else being equal, $I^2$ is bound to be large. Their article is open access by the way.
It is fine to continue with the analysis but you would want to report on the variability between studies which makes the idea of a single summary value slightly problematic.
Comment: and for the paper its very useful, so does that mean that I cant pool those studies in a meta-analysis?
Comment: Not necessarily. It means that you need to think about the studies being pooled to assess whether they are appropriate to combine. Are things like study design, population of interest, treatment and control interventions, outcomes, follow up times, blinding, etc are all similar enough. There is no metric that will tell you if this is appropriate, only subject matter expertise.


Criar Dockerfile para Zend Expressive

Question: Olá pessoal estou com um dificuldade para rodar o zend expressive com o docker. Tenho outros projetos que funcionam perfeitamente com o docker mas quando eu vou tentar desenvolver com o zend expressive, não consigo, dá erro dizendo que não consegue encontrar o arquivo vendor/autoload.php, sendo que o mesmo está lá.. já tentei de várias manerias mas não tem jeito, se eu entro pelo MAMP, funcona direitinho, mas pelo docker não. Alguém sabe o que pode ser? Segue abaixo o Dockerfile
<code>FROM php:7.0-apache

RUN apt-get update

RUN a2enmod rewrite

RUN docker-php-ext-install pdo pdo_mysql

# install GD
RUN apt-get install -y libfreetype6-dev libjpeg62-turbo-dev libpng12-dev
RUN docker-php-ext-configure gd --with-freetype-dir=/usr/include/ --with-jpeg-dir=/usr/include/
RUN docker-php-ext-install gd

# install json
RUN docker-php-ext-install json
</code>
Ah, para eu criar a imagem do php estou usando "docker build -t projeto/php7 . "
Se alguém puder me ajudar, agradeço..
Comment: Você entrou no container em execução para checar o arquivo em seu caminho absoluto e suas permissões?
Comment: Como assim? não entendi.. o que eu sei é que tem as permissões corretas e que está apontando para a pasta public do projeto, isso está certo até porque está dando o erro do autoload.php, que é este:

Warning: require(vendor/autoload.php): failed to open stream: No such file or directory in /var/www/html/index.php on line 11

Fatal error: require(): Failed opening required 'vendor/autoload.php' (include_path='.:/usr/local/lib/php') in /var/www/html/index.php on line 11
Comment: Como você sabe que o arquivo está acessível dentro do container? Você precisaria entrar nele pra ter certeza, entende? Tem que executá-lo em modo detached (-d) e depois entrar nele pra acessar seu conteúdo com o exec -it.
Comment: Como você sabe que o arquivo está acessível dentro do container? Você precisaria entrar nele pra ter certeza, entende? Tem que executá-lo em modo detached (-d) e depois entrar nele pra acessar seu conteúdo com o exec -it.
Comment: Ta.. eu acesso o container e tenho que acessar a pasta aonde ele tá? como posso fazer isso? OBS: eu sei como acessar o bash, mas não sei como acessar ver o arquivo
Comment: Como está reclamando do arquivo /var/www/html/index.php, depois de entrar no container, roda um "ls -l /var/www/html/index.php".
Comment: Olha, eu acho que ja descobri o que está acontecendo, só não sei como resolver.. o Zend Expressive tem uma estrutura de pastas assim:
- config
- src
- public
- vendor
- templates
e eu configurei o docker-compose.yml para acessar a pasta public por padrão e por causa disso a pasta vendor e as outras não estão sendo "assistidas" pelo container.. só que se eu iniciar o container na raiz e acessar localhost/public, da erro de rota no zend expressive. Sabe como me ajudar? se eu não expliquei direito me avisa..
Comment: Como está teu docker-compose? Como você configurou esse diretório public? Não tem como informar todos os diretórios que precisam ser acessados nele? Se você configurou como volumes, teria que informar todos.
Comment: Você pode dar uma olhada no meu github esta em [https://github.com/AlexandroZaleski/zend-expressive] ali tu vai ver toda a estrutura e os arquivos do docker.. um colega meu me disse que eu precisava instalar o composer no container, to tentando mas ainda não consegui.. e tbm não sei se vai resolver.. mas to atirando para todos os lados kkk. obrigado pela força
Comment: Pessoal, eu consegui fazer funcionar mas usando o servidor interno do php com esta linha no meu docker-compose: command: php -S 0.0.0.0:8080 -t public. Pelo apache  ainda não consigo, então estou usando assim por enquanto.. Obrigado a todos
Answer: Aqui está uma configuração de PHP e Apache para rodar a aplicação com Zend Expressive:
https://gist.github.com/argentinaluiz/6ab98dc03c204a59a5ea6ee018550ee5
;)
Comment: Obrigado Luiz ;)

Criar Dockerfile para Zend Expressive


What is the origin of the term "modular" in different areas?

Question: The word "modular" is used in many different, seemingly unrelated contexts. For example, modular forms, modular representation theory, modular latices, moduli spaces, modules, and modular arithmetic. Why is the word modular (and it's derivatives) so ubiquitous in mathematics, in seemingly unrelated areas?
Comment: See also [the-origins-of-modular-and-moduli](https://mathoverflow.net/q/300013/27004) as https://mathoverflow.net/q/300013/27004
Answer: Modular in mathematics means "relating to a modulus", which is essentially some form of "reduction of information" or a "projection" from a richer set of numbers to a less rich one, by virtue of an equivalence relation.
Positive and negative numbers projected down to positive numbers only.
Modular arithmetic: the integers, projected down to a set of non-negative integers less than N.
etc.
Comment: I don't really see the connection for modular forms or modular representation theory. What is the modulus there?
Comment: Per https://en.wikipedia.org/wiki/Modulus, from the latin *modus* meaning measure or manner. How would you extend your answer to physics/engineering contexts, such as "modulus of elasticity"? I agree that it can, could be a nice addendum though.
Comment: I would say that modulus of elasticity is the properties of something, stripped down to some essential measure, which is a subset of the full set of properties - again, a reduction in properties. Two things may have the same modulus of elasticity, though their breaking strains, and proneness to fatigue may be different.
Comment: @vukov i'm in danger of getting out of my depth but a modular function is is invariant with respect to the modular group and therefore there is an equivalence relation at play just like $-1$ can be considered equivalent to $+1$ under the appropriate equivalence relation, only with a much more complex equivalence
Answer: The sense of "modular" in (elliptic, Hilbert-Blumenthal, Siegel, hermitian, ...) "modular forms", and in "moduli space" appears to be connected to a somewhat archaic use of "modul" (in German, mid-to-late 19th century) for what would be "lattice" (in a Euclidean space) in English, like $\mathbb Z\oplus \mathbb Z\subset \mathbb R^2$. This arose c. 1800 first in the study of elliptic curves over $\mathbb C$, and then "abelian" functions by Abel and Jacobi. The space of "modules", that is, the parameter space for elliptic curves, was the "modul-space" (in some linguistic form). This was a good part of Siegel's studies in the late 1930s regarding moduli of (e.g.) principally polarized abelian varieties (over $\mathbb C$). Functions and sections of line bundles on the moduli-space are "modular..."
Rings of integers in algebraic number fields were often modeled in more "geometric" fashion as lattices ("modules") sitting in Euclidean spaces, and this transitional viewpoint is still used in introductory treatments nowadays. This also connects to "geometry of numbers" developed by Minkowski and others c. 1900.
I think unrelated to the previous: on a topological group, "the modular function" tells how right (or left) Haar measure changes under left (or right) translation. This might be more etymologically related to the use as in "modular arithmetic", but I do not know. I cannot easily determine the early use of "modular" in reference to Gauss' invention of "congruences".


Can I configure Wndows NDES server to use Triple DES (3DES) algorithm for PKCS#7 answer encryption?

Question: I am running SCEP client to enroll certificates on NDES server. If OpenSSL is not in FIPS mode - everything  works fine.
In FIPS mode i get the following error:
pkcs7_unwrap():pkcs7.c:708] error decrypting inner PKCS#7
139968442623728:error:060A60A3:digital envelope routines:FIPS_CIPHERINIT:disabled for fips:fips_enc.c:142:
139968442623728:error:21072077:PKCS7 routines:PKCS7_decrypt:decrypt error:pk7_smime.c:557:

That's because NDES server uses DES algorithm to encrypt returned PKCS#7 packet. I used the following debug code:
/* Copy enveloped data from PKCS#7 */
    bytes = BIO_read(pkcs7bio, buffer, sizeof(buffer));
    BIO_write(outbio, buffer, bytes);

    p7enc = d2i_PKCS7_bio(outbio, NULL);

/* Get encryption  PKCS#7 algorithm */

    enc_alg=p7enc->d.enveloped->enc_data->algorithm;
    evp_cipher=EVP_get_cipherbyobj(enc_alg->algorithm);
    printf("evp_cipher->nid = %d\n", evp_cipher->nid);

The last string always prints:
evp_cipher->nid = 31
defined in openssl-1.0.1c/include/openssl/objects.h
#define SN_des_cbc "DES-CBC"
#define LN_des_cbc "des-cbc"
#define NID_des_cbc 31

I use 3DES algorithm for PKCS7 requests encryption in my code (pscep.enc_alg = (EVP_CIPHER *)EVP_des_ede3_cbc()) and NDES server accepts these requests, but it always returns answer encrypted with DES.
Can I configure Wndows NDES server to use Triple DES (3DES) algorithm for PKCS#7 answer encryption?
Answer: I got answer from Microsoft support (Diana Zhang) saying this is impossible:
http://social.technet.microsoft.com/Forums/en-US/winserversecurity/thread/83a6680c-6610-4cf7-a4fa-1bc63f32a8be
After in-depth research, want to let you know:
The content encryption algorithm for P7 in hardcoded to DES(in CBC mode).
Regards,
Diana


Turan-related graph theory question

Question: Let us have a $G$ graph, which has $4$ vertices and $4$ edges, and $3$ vertices create a triangle. What is the value of $ex(n,G)$ for all $n$?
So basically the task is: If I have $n$ vertices, what is the maximum value of edges I can draw within that graph, that it doesn't conntain our $G$ graph as sub-graph. My first idea was that I can just draw disjunct triangles, in this case, for $n$ vertices I have $n$ edges. This does not contain $G$ as subgraph, but I am not sure that the number of edges is maximal.
Does Turan theorem helps me somehow, or what is the main idea of solving this task? Thanks!
Answer: Turán's theorem is indeed what you need, because the best way to avoid a subgraph isomorphic to $G$ is to produce a triangle-free graph.
According to the special case of Turán's theorem called Mantel's theorem, the maximum number of edges in an n-vertex triangle-free graph is $\lfloor n^2/4 \rfloor$, achieved by creating a complete bipartite graph with the parts as nearly equal as possible. The girth of complete bipartite graphs is of course $4$.
42 edges using 13 vertices, $K_{7,6}$:

Turan-related graph theory question


hierarchical select not working in multistep form

Question: I have created multistep form with help of
link
 and created hierarchial select in step 1.It is working for step 1
but when i click next button and goes to step2, and return step1 it is not working.
Please Help.
Comment: How are you passing the select to second step?
Answer: I'm hoping this will add more info to the above reporting, even though we have different websites, to hopefully enable a fix.
I have a 2 level hierarchical select taxonomy.  Refer to it in my people pages.  Created as Term Reference - Hierarchical Select. When registering a user go to select this term, which is supposed to save term lineage, forces user to select term from deepest level.
Selecting from pulldown menu and clicking add, it appears that the item is being selected correctly and shows up below the pulldown menu, with the option to remove the selection.  I then save, it says everything was saved correctly.  I scroll down to my selection, and it says nothing has been selected.

If I go to a view based off of this information, it indeed finds no data.
I do get data if I change the field from hierarchical select to List Select or check boxes and have the view be rendered taxonomy term.  If I have to use List Select I will have to change the terms to include the first level since it doesn't show or save this way. This list is going to expand as new courses get added.  We can't do check boxes perpetually.  It will get crazy long.

I did find this error message log, but I don't know after which change this appeared.
Notice: Undefined index: value in views_handler_filter_term_node_tid->value_validate() (line 219 of /var/www/vehicledev_ccom_nh/sites/all/modules/views/modules/taxonomy/views_handler_filter_term_node_tid.inc).
Severity
notice


Converting an integer to a vector of 0's and single 1

Question: I have an array of labels in the form:
[1;3;2;]
I wish to convert this to an array of vectors, where only the i'th element is 1, and the rest are 0's.
So the above would be (assuming 5 lables):
[1 0 0 0 0]
[0 0 1 0 0]
[0 1 0 0 0]
How can this be done, without a 'for' loop?
Comment: This is off-topic for MSE, but `A=[1;3;2]; eye(5)(A,:)`.
Answer: What is wrong with just doing it?  Let L be the length of the array.  Dimension A(L,5).  Set all elements of A to zero. Then go through the array, in your example set A(1,1)=1, A(2,3)=1, A(3,2)=1 where the first index just counts from 1 to L and the second is the value in that position.
Comment: I'm looking for a vectorized syntax, that's all. Of-course I can do it with a 'for' loop
Answer: Here is how you can do this in Matlab:
maxLabel = 5;
x = [1; 3; 2];
M = zeros(length(x),maxLabel);
idx = sub2ind(size(M), 1:numel(x),x)
M(idx) = 1;

Or more compact for your specific case:
M = zeros(3,5);
M(sub2ind([3 5], 1:3,[1;3;2]))


Obter div bem acima na hierarquia

Question: Eu tenho essa hierarquia em HTML

                            <button class="send">ENVIAR</button>

e desejo que quando for clicado no botão de classe .send, uma mensagem seja exibida em send_show. Só que existem várias hierarquias dessas na página, ou seja, deve ser pega a send_show do respectivo botão.
Estou usando jQuery para realizar isto.
Answer: Usando parents() para subir para a div "pai" depois desce com children() para a div "filha" que você deseja. Assim você pode ter essa estrutura em vários lugares pois só a que está junta ao pai vai ser afetada.
$(".send").on('click', function() {
    $(this)
     .parents(".footer") //Sobe para o pai do evento click
     .children(".send_show") //Desce para a filha
     .html("Div mais próxima");
});

Espero que seja isso.
Comment: Outra forma é usar o `.parents`  para chegar em `.forms_sends` e usar o `.prev('.send_show')`

Obter div bem acima na hierarquia


Can I access functions variables?

Question: On clicking button I want some function to have its variables defined, is that possible?
button.addEventListener("click", function(){
   x.name = "john";
   x.lastname = "doe";
});

function x(){
   name = "";
   lastname = "";
}

How to make function x return name and lastname defined in event listener?
Comment: When is `x()` called?
Comment: I think you are confused by a few things here.  Hopefully this helps: 1. You have to define `x` with `var`, `let`, or `const` before you can go assigning properties to it.  You also need to define your `button` element before you call a click handler.  And your function `x` does nothing at all atm.
Answer:
On clicking button I want some function to have its variables defined, is that possible?

How functions work is that you define parameters for the function, and then populate the values of those parameters with arguments to the function. This effectively creates variables in the scope of the function with the values of the arguments you provided.
button.addEventListener("click", function(){
   x("john", "doe");
});

function x(name="", lastname=""){
  console.log(name, lastname);
}

Here I also added default values for the parameters to equal an emtpy string, just in case not enough arguments were sent.

How to make function x return name and lastname defined in event listener?

Your use of the word "return" is confusing, since functions can return values, but you seem to actually want to assign the values to the variables.
In case you did want to return the same values back, you'd use a return statement with an object to deliver the same values back, but I don't think that's what you were after.
Answer: You can redefine x within click handler to set default parameters for the function. Note, "name" is a property of window, adjusted identifier to _name

const button = document.querySelector("button");

button.addEventListener("click", function() {

  x = function x(_name = "john", lastname = "doe") {
    console.log(_name, lastname)
  }

  x()
});

function x(_name, lastname) {
  console.log(_name, lastname)
}
<button>click</button>
Answer: Writing something like this means that the anonymous function will be called on click events
button.addEventListener("click", function(){
   x.name = "john";
   x.lastname = "doe";
});

it's the same as writing
function onClickListener(){
   x.name = "john";
   x.lastname = "doe";
}

button.addEventListener("click", onClickListener);

but nothing will be reading the response from the onClickListener function, so no you can not return from the function. You can do this instead
var x = {};
function onClickListener(){
   x.name = "john";
   x.lastname = "doe";
}
button.addEventListener("click", onClickListener);

This is ugly code using globals but it should work. Once the cick event is calld the global x var will have the new values

Can I access functions variables?


Line-circle intersection in spherical geometry?

Question: How does one calculate the intersections between a "line" (a Great Circle) and a circle in spherical geometry?
i.e. given start point (as lat,lon), heading, circle centre (as lat, lon) and circle radius (as a % of the sphere's radius), there will be between zero and two* locations where they meet.
Answer: This is just a special case of circle-circle intersection, because a great circle is just a circle with radius $\frac{\pi R}{2}$. If you embed your sphere in Euclidean $\mathbb{R}^3$ then a circle on the sphere is the intersection of a plane with the sphere (where the plane passes through the sphere's centre iff it's a great circle).
The intersection of the two circles is therefore the intersection of both planes and the sphere. This can be calculated by finding the intersection of the planes, which is a line except in special cases, and then finding the intersection of that line with the sphere.
Answer: OK my first attempt at this goes something like...


Diferença entre ?. e ?? em C#

Question: Eu olhei a documentação da Microsoft mas ainda sim achei um pouco confuso, as principais coisas que eu consegui abstrair foram:

"?." - é um operador nulo condicional e testa o valor do operando esquerdo para nulo antes de executar um acesso de membro. Achei esse bem confuso
"??" - é um operador de coalescência nula, ele retorna o operando esquerdo se o operando não for nulo; caso contrário, ele retornará o operando direito..

Aparentemente eles apresentam ter funções muito similares, queria saber qual é a real diferença entre eles.
E porque não posso utilizar eles dentro da condição de um IF ou um WHILE?
Comment: Coalescência nula é mais fácil de entender. Se o lado esquerdo for nulo, retorne o que está do lado direito. Exemplo: `string nome = null ?? "jeff";`, qual será o conteúdo da variável `nome`?
Answer: Vamos por partes:
O ?. é para evitar comparações do tipo obj != null ? obj.prop : null, ou seja, ele verificará se o que tem antes da interrogação é diferente de null, por exemplo:
//Se qualquer obj for nulo, ele retornará nulo, caso contrário retornará prop
return obj?.objFilho?.objNeto?.prop;

//Equivalente a
if(obj != null && obj.objFilho != null && obj.objFilho.objNeto != null)
{
    return obj.objFilho.objNeto.prop;
}
return null;

Já o ?? serve para, caso o valor retornado seja nulo, ele retornará um valor padrão, por exemplo:
int? a = null;
int b = a ?? 1; //Se a for nulo, ele retorna 1

É possível, inclusive combinar esses operadores da seguinte forma:
var prop =  obj?.objFilho?.objNeto?.prop ?? 0;

Você não consegue usar eles em laços condicionais ou laços de repetição porque eles não retornam um valor booleano, mas sim valores em comparação com null.
Answer: Veja a seguinte estrutura de exemplo:
class Pai
{
    public string Nome { get; set; }
    public Filho Filho { get; set; }
}

class Filho
{
    public string Nome { get; set; }
}

Se você executar o código abaixo, receberá uma exception de referência nula, pois estará tentando acessar o atributo de uma instância que não foi declarada
class Program
{
    static void Main(string[] args)
    {

        var pai = new Pai { Nome = "Teste Pai" };
        var nomeDoFilho = pai.Filho.Nome;

        Console.WriteLine(nomeDoFilho);

        Console.Read();
    }
}

Agora, se você utilizar o ?., será verificado se o objeto não é nulo antes de acessar a propriedade para a atribuição à variável.
class Program
{
    static void Main(string[] args)
    {

        var pai = new Pai { Nome = "Teste Pai" };
        var nomeDoFilho = pai.Filho?.Nome;

        Console.WriteLine(nomeDoFilho);

        Console.Read();
    }
}

E aproveitando a coalescência ??, comentada pelo colega, você pode inclusive já realizar um tratamento para a ocorrência.
class Program
{
    static void Main(string[] args)
    {

        var pai = new Pai { Nome = "Teste Pai" };
        var nomeDoFilho = pai.Filho?.Nome ?? "Não possui filho";

        Console.WriteLine(nomeDoFilho);

        Console.Read();
    }
}

Diferença entre ?. e ?? em C#


Do Odds Ratios (OR) have a similar ranking categorisation as Cohen's conventions?

Question: I'm trying to meaningfully interpret the findings from this meta-analysis which states: "Additional evidence supported the association between fever during pregnancy and increased risk for NDD in offspring."
They base this statement on the following "Maternal exposure to fever during pregnancy increased the risk of [Neurodevelopmental Disorders] in offspring with an OR of 1.24 [95% CI: 1.12–1.38]. Secondary analysis revealed an increased risk for NDD when fever occurred during the first trimester of gestation [OR 1.13–95% CI: 1.02–1.26]."
I am more used to working with Cohen's d effect sizes. Based on this converter, these OR effects sizes of 1.24 and 1.13 appear to be trivial in size when converted to Cohen's d. If that converter is accurate, then these effect sizes become 0.12 and 0.07 respectively.
From a statistical perspective, would it fair to state that these Odds Ratios are trivial and should not worry to-be mothers who experience fever during pregnancy?
Edit / Additions: The context of my question relates to some pregnant women's fear of getting the Covid-19 vaccine due to fear of developing a fever after the injection which some studies are suggesting is associated with neurodevelopmental disorders.
I think as @Noah below mentions, there is arguably no universal rule for what constitutes meaningful or trivial. If memory serves me, Cohen himself even stated that his small/medium/large distinction was ambiguous and that each discipline needs to develop their own reference points of what is meaningful based on their body of literature.
I work in the area of mental health. If a therapy versus placebo generated a Cohen's d of 0.12 favouring therapy in reducing anxiety, then there is no way that therapy would be put forward as warranting implementation in a service as that is well below what is generally accepted in this field to be seen as meaningful.
Using @AdamO's reference to lead below to my query. This paper found that those with ADHD were more likely to have been exposed to lead during childhood than non-ADHD controls. Those with increased levels of lead in their blood had an increased risk of ADHD with an OR 6.0 [95% CI = 4.10–8.77]. Taking this as an example of a reference study, then it would appear that exposure to lead being linked to ADHD has an OR of 6.0 versus maternal exposure to fever being linked to NDD having an OR 1.24.
Said another way (and to quote from @AdamO).

Prevention of fever during pregnancy reduces the risk of NDD by a factor of 24%.
Prevention of lead exposure during childhood reduces the risk of ADHD by a factor of 500%.

Using the ADHD study as one example, it would appear that exposure to maternal fever has a much smaller association with NDD than lead exposure does with ADHD. I know that "much smaller" is still an arbitrary statement, but it terms of potentially allaying some fears of covid-19 vaccine, it somewhat puts those fears into context.
Answer: The methods section says quite plainly:

Odds ratio (OR) were pooled using random-effects meta-analysis.
Heterogeneity in effect size across studies was studied using
random-effects meta-regression analysis. (PROSPERO CRD42020182801)

and provides a variety of references. Most useful is probably the guidance from the Cochrane group, an authority on meta-analyses:

Higgins JPT, Green S. Cochrane handbook for systematic reviews of interventions. New York: Wiley; 2008. [Google Scholar].

In broad terms, this works by allowing for a random intercept to account for differing levels of disease prevalence in the unexposed sampling frame, estimating a "common" odds ratio across all the studies. This is, of course, dependent on running several analyses to assess the "homogeneity" of the odds ratio. The method is intended to generalize the Mantel Haenszel Odds Ratio.
The normal approximation to the odds ratio is usually taken on the efficient (i.e. log odds) scale, where symmetric confidence intervals are calculated. One could calculate the corresponding approximate "Z" statistic for the odds ratio and compare to Cohen's D. But the practice is not standard for a few reasons. Mainly, the odds ratio doesn't often translate into useful scales for understanding the potential of public health interventions.
You may be appealing to the following chart which refers to odds ratios of 1.5 or smaller as producing "small" effects.

https://www.ncbi.nlm.nih.gov/labs/pmc/articles/PMC3444174/
This kind of table does quite a bit to undermine the public health advances of the last century. Indeed, the associations between common exposures and rare outcomes tend to have highly variable odds ratio. The seminal text from Breslow and Day 1987 published by the IARC contains an extensive rationale for basing public policy on odds ratios.
Effect sizes are not a universal lens from which one can view all effects  from clinical and observational studies. Odds ratios are problematic because they only approximate the risk ratio when the incidence is rare. Assuming NDD is rare and well characterized, we have that prevention of fever during pregnancy reduces the risk of NDD by a factor of either 24% or 13% or in the vicinity, depending which analysis is least biased by observational design. You may not be aware but fever during pregnancy is not benign, a mother's immune system is suppressed to prevent a host-vs-graft type reaction, and common infections can have serious consequences, especially listeria. This is women who go through pregnancy are advised against cruises, fountain drinks, processed lunch meats, and sushi; all (mostly) fine for an adult with a normal immune function.
Some argue a risk difference or number-needed-to-treat is a more important scale for understanding potential impact of a preventative measure. The problem is that for very rare events the risk difference is necessarily very small, but if they are events of grave consequences, a binary (yes/no) comparison may not suffice to present the value of a policy or treatment.
In public health cost-benefit analyses, adverse effects are often translated into QALYs - quality adjusted life years. QALYs are a unit that allow one to quantify and compare the loss of dying 10 years early, versus dying 5 years early but spending the last 20 years of your life under terrible living conditions. Neurodevelopmental delay reduces your quality of life forever, and most likely reduces life span. An analysis of lead exposure on NDD using QALYS deemed household lead exposure such an adverse health outcome that public health experts suggested it was cost effective to perform lead abatement on all American homes due to the risk of lead ingestion and inhalation.
As a last point, one must consider the cost of implementing an intervention; both at the outset and to sustain it according to the initial vision. This is an endless point of debate in economics - since government spending is kind of a mystifying subject. Nevertheless, you can ask questions like "I have $500 to spend on something, what's the most impact?" Lead abatement is obviously a highly cost intensive process in terms of hours and materials; demolition, HEPA negative air pressure filters, containment, etc. On the other hand, training protocols for safety in immunosuppressed individuals is kind of standard and inexpensive, not perfectly effective, but individuals are usually motivated to follow the code. Prior to the COVID19 pandemic, for anyone who cared for a loved one going on a chemo that cause neutropenia, you might full well remember mask wearing, hand washing, and social distancing. These are relatively inexpensive things to do that produce a big effect for cancer patients, and as it seems may benefit pregnant mothers.
Comment: (+1) looks good to me. I think the main issue is that the meaningfulness of odds ratios is context-dependent; there is no universal rule for what constitutes as meaningful or trivial (this is true of other effect sizes, too). I think your edit explains that quite vividly.
Comment: I'm not sure this answers the question of whether odds ratios of 1.24 and 1.13 should be considered "meaningful" or "trivial", which seems to be the core of OP's post. I read the question to mean "I understand how Cohen's D values can be interpreted as meaningful vs. trivial; can odds ratios be interpreted in the same way using this converter?" Nothing to do with the methodology of pooling effect sizes across studies.
Comment: Strooby: suppose that in one group of 1000 there are ten deaths and in another of 1000 there are 15 deaths. The odds ratio is 1.33 which is close to the ones which you are bothered about. Now suppose these are two different treatments. Would you recommend to your patient that they take the treatment from the second group or the first?
Comment: @Noah good point. It's a densely layered question to the point it's hard to pinpoint exactly where the line of reasoning fails. Consider the edit, any other input needed by your (or OP's) reckoning?
Comment: Thanks for both of your comments. @Noah, you are correct that it is the meaningfulness of the ORs that I am trying to understand. I have added more to the original question above to potentially add any further clarity to what I am attempting to understand.


UitableView change sectionView after tap

Question: if i tap section, tableview expand onlu current this section, and in sectionView change indicator color
if i collapses section - indicator color have another color
problem - sometimes color's mot change
<code>- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {

    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 80)];
    headerView.backgroundColor = [UIColor lightGrayColor];

    UIButton *buttonHeader = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 320, 80)];
    [buttonHeader addTarget:self action:@selector(expandGroup:) forControlEvents:UIControlEventTouchUpInside];
    buttonHeader.tag = section;

    UIImageView *expandIndicator = [[UIImageView alloc] init];
    expandIndicator.frame = CGRectMake(270, 25, 30, 30);

    expandIndicator.backgroundColor = [UIColor darkGrayColor];

    if ([[_exerciseForGroup objectAtIndex:section] count] > 0) {
        expandIndicator.backgroundColor = [UIColor greenColor];
    }

    UILabel *labeHeader = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, 100, 60)];

    labeHeader.text = [[_groups objectAtIndex:section] objectForKey:@"nameExerciseGroup"];
    [labeHeader setFont:[UIFont systemFontOfSize:25]];

    [buttonHeader addSubview:labeHeader];
    [buttonHeader addSubview:expandIndicator];

    [headerView addSubview:buttonHeader];

    return headerView;
}
- (IBAction)expandGroup:(id)sender {

    UIButton *button = (UIButton *) sender;
    int section = [button tag];

    if ([[_exerciseForGroup objectAtIndex:section] count] == 0) {

        [self addAllExerciseFromGroupInSection:section];
    } else {

        [self deleteExerciseFromGroupInSection:section];

    }
}
- (void)addAllExerciseFromGroupInSection:(int)section {

    [_tableviewExercise reloadData];

    NSMutableArray *indexPaths = [[NSMutableArray alloc] init];

    for (int i = 0; i < [[_originalExercise objectAtIndex:section] count]; i++) {

        [[_exerciseForGroup objectAtIndex:section] addObject:[[_originalExercise objectAtIndex:section] objectAtIndex:i]];
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:section];

        [indexPaths addObject:indexPath];
    }
    [_tableviewExercise beginUpdates];
    [_tableviewExercise insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationFade];
    [_tableviewExercise endUpdates];

    [_tableviewExercise scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:section] atScrollPosition:UITableViewScrollPositionMiddle animated:YES];

    NSMutableArray *indexPathsForDeleteBefore = [[NSMutableArray alloc] init];
    for (int i = 0; i < section; i++) {

        int count = [[_exerciseForGroup objectAtIndex:i] count];

        for (int j = 0; j < count; j++) {

            [[_exerciseForGroup objectAtIndex:i] removeObjectAtIndex:0];
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:j inSection:i];

            [indexPathsForDeleteBefore addObject:indexPath];
        }

    }

    [_tableviewExercise beginUpdates];
    [_tableviewExercise deleteRowsAtIndexPaths:indexPathsForDeleteBefore withRowAnimation:UITableViewRowAnimationFade];
    [_tableviewExercise endUpdates];

    NSMutableArray *indexPathsForDeleteAfter = [[NSMutableArray alloc] init];
    for (int i = section + 1; i < [_groups count]; i++) {

        int count = [[_exerciseForGroup objectAtIndex:i] count];

        for (int j = 0; j < count; j++) {

            [[_exerciseForGroup objectAtIndex:i] removeObjectAtIndex:0];
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:j inSection:i];

            [indexPathsForDeleteAfter addObject:indexPath];
        }

    }

    [_tableviewExercise beginUpdates];
    [_tableviewExercise deleteRowsAtIndexPaths:indexPathsForDeleteAfter withRowAnimation:UITableViewRowAnimationFade];
    [_tableviewExercise endUpdates];
}

- (void)deleteExerciseFromGroupInSection:(int)section {

    [_tableviewExercise reloadData];
    NSMutableArray *indexPaths = [[NSMutableArray alloc] init];

    int count = [[_exerciseForGroup objectAtIndex:section] count];

    for (int i = 0; i < count; i++) {

        [[_exerciseForGroup objectAtIndex:section] removeObjectAtIndex:0];

        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:section];
        [indexPaths addObject:indexPath];
    }

    [_tableviewExercise beginUpdates];
    [_tableviewExercise deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationFade];
    [_tableviewExercise endUpdates];
}
</code>
Comment: where is your expandGroup method?
Answer: YourViewController.h
<code>@interface AboutVC : UIViewController
{
    int section_expand;
}
</code>
YourViewController.m
<code>- (void)viewDidLoad
{
    section_expand = -1;

    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 10;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section_expand == section)
    {
        return [arr count];
    }
    else
    {
        return 0;

    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section;
{
    return 80;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 80)];
    headerView.backgroundColor = [UIColor lightGrayColor];

    //UIButton *buttonHeader = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 320, 80)];
    //[buttonHeader addTarget:self action:@selector(expandGroup:) forControlEvents:UIControlEventTouchUpInside];
    //buttonHeader.tag = section;

    UIButton *buttonHeader=[UIButton buttonWithType:UIButtonTypeCustom];
    [buttonHeader setFrame:CGRectMake(0, 0, 320, 80)];
    buttonHeader.tag=section;
    [buttonHeader addTarget:self action:@selector(expandGroup:) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:buttonHeader];

    UIImageView *expandIndicator = [[UIImageView alloc] init];
    expandIndicator.frame = CGRectMake(270, 25, 30, 30);

    if (section_expand == section)
    {
        expandIndicator.backgroundColor = [UIColor greenColor];
    }
    else
    {
        expandIndicator.backgroundColor = [UIColor darkGrayColor];
    }

    UILabel *labeHeader = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, 100, 60)];

    labeHeader.text = [[_groups objectAtIndex:section] objectForKey:@"nameExerciseGroup"];
    [labeHeader setFont:[UIFont systemFontOfSize:25]];

    [buttonHeader addSubview:labeHeader];
    [buttonHeader addSubview:expandIndicator];

    [headerView addSubview:buttonHeader];

    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *CellIdentifier = [NSString stringWithFormat:@"cell %d",indexPath.section];

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    cell = nil;
    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

        cell.backgroundColor = [UIColor clearColor];

        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;
{

}

-(IBAction)expandGroup:(id)sender
{
    UIButton *btn = (UIButton *)sender;

    section_expand = btn.tag;

    [_TBL reloadData];
}
</code>


One Extra line is added when using mutt for .csv file

Question: I am using python 3 and this is my code
   with open(f"{datetime.datetime.now().strftime(DATETIME_FORMAT)}.csv", "w", newline="") as f:
        w = csv.writer(f)

When I import file from my server to local(Macbook) it shows files in correct format.
when sending email using mutt command, it is adding extra line between each row.
Comment: Please provide a [mcve].
Comment: This worked for me: This removed extra lines from output .csv:     '''with open(f"RMA{datetime.datetime.now().strftime(DATETIME_FORMAT)}.csv", "w", newline="") as f:
        w = csv.writer(f, lineterminator='\n')'''
Comment: I'm not sure I understand your comment.
Answer: This worked for me: This removed extra lines from output .csv:
open(f"RMA{datetime.datetime.now().strftime(DATETIME_FORMAT)}.csv", "w", newline="") as f:
    w = csv.writer(f, lineterminator='\n')