How can I run `git commit` and `git push` in atom?

Question: Is there a way to run git commit and git push in the Atom editor?
I read this blog post but could not find that mentioned: http://blog.atom.io/2014/03/13/git-integration.html
Answer: What you're looking for is the git-plus package. Install that - it provides full Git integration with commands like commit, add, push, pull and lots of others.
Comment: @AkshayLAradhya Press 'Ctrl+Shift+H' and you'll get a palette with all the commands provided by git-plus. ('Cmd+Shift+H' if you're using OSX)
Comment: After installing this how do I use this ?
Comment: @Drmjo you've found this out by now for sure but it's `ctrl` (or `cmd` on mac) + `shift` + `P`
Comment: @AkshayLAradhya The commands are also available from the Packages->Git-plus menu
Comment: how do you open that terminal looking thing where you type in "git wr"  and "git com" @nwinkler
Comment: Use `ctrl` + `(` to open up the git tab in atom
Answer: There've been some developments since this question was initially asked. Both git commit and git push (along with lotsa other commands) are now available in the app natively (version 1.18+).
There is a GUI for staging and reviewing changes as well as committing them with a commit message.

Just double-click to stage or un-stage files. Clicking on a file in Atom's Git GUI will load up the colored diff for reviewing changes. Type in a commit message right there in the text entry box and click the button to make the commit! Commit title's with message bodies (just a new line separating them) is supported - there's even a counter to let you know when your git commit message title is getting too long.
Also, when you have a change that's been staged and committed, you can push the contribution to your GitHub repository by pushing the down/up arrows at the bottom right to load up the options:

...then selecting the "Push" option:

Up goes your commits to the cloud!
See: https://github.atom.io/
Note as well that there is a branch display which can be used to switch branches or create new ones. Also, you can do pulls and fetching.

To stage new files and changes, and make a commit you also can access the git tools from either the Packages Tab:

... or the View Tab:

A push will, of course, require your username and password.
Also, setting up the GitHub preview requires authentication:

ctrl+9 opens the "Git" pane
...and ctrl+shift+9 will close it.
ctrl+8 opens the "GitHub(preview)" pane
...and ctrl+shift+8 will close it.
One way to configure git so you can bypass manually entering your username and password while using these Atom features:

Set your Git user info in the .gitconfig file.
On Windows this is usually located in your Users folder.
Example: If your username was Bob, your .gitconfig should be in: C:\Users\Bob.gitconfig
If this file doesn't exist, you need to create it and fill it out as followed:
(fill in the name and email part and save)
[user]
    name = {NAME}
    email = {EMAIL}

See also: https://help.github.com/articles/caching-your-github-password-in-git/
Comment: Brilliant! Should be the accepted answer because it doesn't require additional packages to be installed. Thanks
Comment: I have 2 remotes set up. I want to specify which remote to push to. Can I do that in Atom? I don't see how to  do it directly from the GUI. Or do I need an additional package?
Answer: You can also use a git GUI package: git-control. It is easier to use and there is a small display of auto generated git commands, which is very helpful for beginners to get a good idea about git and version control.

Answer: There's also one more nice sweet package for commits: git-commit.
Good news: it's super quick to commit all your stuff.
Bad news: it doesn't support pushing.

(source: github-camo.com)
Comment: push can be added on post-commit, nice when working alone
Answer: In order to make the process more automatic, I have switched to another strategy to avoid having to click on too many buttons (am I lazy or it is worth the time?).
The idea is to create a small Makefile file at the root of your project which would contain something like:
default: git

git:
    git commit -am'Atom edits'
    git push

I am then using the excellent build-make package to run that two commands in one key stroke <Cmd>-<Alt>-B in my case.


How to get the path of removable storage/sd card? Latest (/storage/???? ????) format as well

Question: How to get the path of removable storage (removable SD Card) on Android 10, especially samsung phones.
As the location of the removable storage is now of the format /storage/???? ????
I found it hard to get the path as it changes with each phone.
I am posting the solution as well, it has worked well on Samsung and Mi phones.
Answer: On every phone or emulator you get the path to app specific folder on removable micro sd card by using the second item returned by
<code>getExternalFilesDirs()
</code>
The path is different for every micro sd card used.
Answer: I would like to share a solution which took me days to find and hopefully shall help others as well. The removable sd card storage on latest android versions is like "/storage/???? ????", this location is quite hard to get. I found the following code from here:
This code helps get the correct location even on Samsung phones. I have tried it on Samsung and Mi phones.
<code>/**
</code>

Get external sd card path using reflection

@param mContext

@param is_removable is external storage removable

@return
*/
<code> private static String getExternalStoragePath(Context mContext, boolean is_removable) {

 StorageManager mStorageManager = (StorageManager) mContext.getSystemService(Context.STORAGE_SERVICE);
 Class<?> storageVolumeClazz = null;
 try {
     storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");
     Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");
     Method getPath = storageVolumeClazz.getMethod("getPath");
     Method isRemovable = storageVolumeClazz.getMethod("isRemovable");
     Object result = getVolumeList.invoke(mStorageManager);
     final int length = Array.getLength(result);
     for (int i = 0; i < length; i++) {
         Object storageVolumeElement = Array.get(result, i);
         String path = (String) getPath.invoke(storageVolumeElement);
         boolean removable = (Boolean) isRemovable.invoke(storageVolumeElement);
         if (is_removable == removable) {
             return path;
         }
     }
 } catch (ClassNotFoundException e) {
     e.printStackTrace();
 } catch (InvocationTargetException e) {
     e.printStackTrace();
 } catch (NoSuchMethodException e) {
     e.printStackTrace();
 } catch (IllegalAccessException e) {
     e.printStackTrace();
 }
 return null;
</code>
}


Erro segmentation fault

Question: E tendo um problema na minha função, estou recebendo o endereço dela e estou a percorrendo, aonde for maiúsculo eu converto para minusculo e aonde tiver ponto, exclamação, interrogação, dois pontos e ponto e virgula eu troco por um espaço.
Mas de acordo com o valgrind o problema esta na linha 82 e 155 do código, ou seja, na função diminuieeretira(); e na main aonde estou recebendo o retorno da função diminuieretira();. Não estou entendendo qual o problema para dar segmentation fault.
Segue abaixo o codigo:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int contagemCaracteres(char* p) //Declaracao da funcao que conta quantos caracteres existem no texto
{
    int i = 0;

    while(p[i] != '\n')
    {
        i++;
    }
    return i;

}

void contagemPalavras(char* p , int r) //Declaracao de funcao que conta o numero de palavras existentes no texto
{
    int palavras = 0, parada = 0, i;

    for(i = 0; i < r ; i++)
    {
        if(p[i] >=  48 && p[i] <= 57 || p[i] >= 65 && p[i] <= 90 || p[i] >= 97 && p[i] <= 122)
        {
            palavras++;
            while(p[i] != 32)
            {
                parada++;
                i++;
            }
        }

    }

    printf("%d\n", palavras);
}

int  contagemFrases(char* p, int r)
{
    int frases = 0, parada = 0, i;

    for(i = 0; i < r; i = parada + 1)
    {

        if(p[i] == 46 || p[i] == 33 || p[i] ==  63)
        {
            frases++;
            parada = i;
        }
        else if(p[i] == 32)
            parada = i;

        else if (p[i] >= 48 && p[i] <= 57 || p[i] >= 65 && p[i] <= 90 || p[i] >= 97 && p[i] <= 122)
        {
            if(i == 0)
                parada = 0;
            else
                parada = i;
        }
    }

    return frases;
}

void mediaCaracteres(int c, int f)
{
    float media = 0;

    media = (float)(c/f);

    printf("%.1f\n", media);
}

char* diminuieretira(char** p, int r)
{
    int i;

    for(i = 0; i < r; i++)
    {
        if(isupper(*p[i]))
            tolower(*p[i]);

        else if((*p[i]) == 46 || (*p[i]) == 44 || (*p[i]) == 59 || (*p[i]) == 58 || (*p[i]) == 33 || (*p[i]) == 63);
            (*p[i]) == 32;
    }

    printf("%s", (*p));
    return (*p);
}

void retiraespaco(char **p1, int r)
{
    int i , j , e = 0, counter = 1;
    char* paragrafo2 = NULL;

    for(i = 0; j < r; i++)
    {
        for(j = 0; j < r; j++)
        {
            if((*p1[j]) != 32)
            {
                paragrafo2 = (char*) realloc(paragrafo2, counter * sizeof(char));
                paragrafo2[i] = (*p1[j]);
                counter++;
                e = 0;
                break;
            }

            if((*p1[j]) == 32)
                e++;

            if(e == 1)
            {
                paragrafo2[i] = 32;
                break;
            }
        }

    }

    printf("%s\n", paragrafo2);
}

int main (void)
{
    int counter = 0, i = 0, recebe1, recebe2, caso;
    char* paragrafomod = NULL;
    char* paragrafo = NULL;
    size_t tamalocado = 0;

    getline(&paragrafo, &tamalocado, stdin);
    do{
        scanf("%d", &caso);

        switch(caso)
        {
            case 1: //Primeira etapa
                recebe1 = contagemCaracteres(paragrafo);
                printf("%d\n", recebe1);

                contagemPalavras(paragrafo, recebe1);

                recebe2 = contagemFrases(paragrafo, recebe1);
                printf("%d\n", recebe2);

                mediaCaracteres(recebe1, recebe2);

            break;

            case 2:

                paragrafomod = diminuieretira(&paragrafo, recebe1); //Segudna etapa
                retiraespaco(&paragrafomod, recebe1);

            break;

            case 3: //Terceira etapa
            break;
        }

    }while(caso != 0);

    free(paragrafo);

    return 0;
}

Comment: Uma dica, sempre use titulos intuitivos ao problema e organize por "tópicos", assim fica mais legivel.
Comment: `media = (float)(c/f);` faz primeiramente a divisao inteira `c/f` e sepois converte o resultado pata `float`. Acho que devia ser `media = (float)c/f;` para fazer a divisao com numeros de virgula flutuante.
Comment: `tolower(*p[i]);` nao altera valor de nenhuma variavel. Precisa de fazer `*p[i] = tolower(*p[i]);`
Answer: char* diminuieretira(char** p, int r)
{
    int i;

    for(i = 0; i < r; i++)
    {
        if(isupper(*p[i]))
            tolower(*p[i]);

        else if((*p[i]) == 46 || (*p[i]) == 44 || (*p[i]) == 59 || (*p[i]) == 58 || (*p[i]) == 33 || (*p[i]) == 63);
            (*p[i]) == 32;
    }

    printf("%s", (*p));
    return (*p);
}

Neste pedaco de codigo, a sub-expressao *p[i] nao faz o que pretendes. O que pretendes 'e (*p)[i].
Mas, para esta funcao, nao precisas de complicar e passar um valor de tipo char **. Funciona bem com um simples char *.

Erro segmentation fault


How to increase meta tag description field to 320 characters?

Question: We are using metatag v8.x-1.5 on our D8 site (v8.5.3). When filling out the metatag description field, we enter any where from 180-320 characters into the field. However, when the page is displayed it is cutting off after 135 characters.
How can we increase the number of characters that are displayed?
Steps to reproduce:

Enter "Compellingly re-engineer bleeding-edge interfaces whereas interoperable quality vectors. Uniquely incubate one-to-one action items before best-of-breed catalysts for change. Interactively." into the Metatag Description field.

Current behavior:
<meta name="description" content="Compellingly re-engineer bleeding-edge interfaces whereas interoperable quality vectors">
Expected behavior:
<meta name="description" content="Compellingly re-engineer bleeding-edge interfaces whereas interoperable quality vectors. Uniquely incubate one-to-one action items before best-of-breed catalysts for change. Interactively.">
Comment: This sounds like either a module bug or a core bug. I would check the module issue queue and ask there (especially since the help text states 320 characters).
Comment: @Kevin I see a feature request to add a configuration setting for the description length. I might have to write a `mymodule_page_attachments_alter` hook if i cannot find anything else.
Answer: I had to write a hook_page_attachments_alter for this
function mymodule_page_attachments_alter(array &$page) {
  foreach($page['#attached']['html_head] as &$html_head) {
    if($html_head[1] == 'description') {
      $html_head_content = $html_head[0]['#attributes']['content'];
      if(Unicode::strlen($html_head_content) > 320) {
        $html_head[0]['#attributes']['content'] = Unicode::truncate($html_head_content, 320);
      }
    }
  }
}


Probability of Specific event occuring between 2 events?

Question: Forgive me beforehand for what may be a question with an obvious seolution, but I havent had statistics courses in quite some time.
I have an Excel File of approximately 3000 Events, each event has a numberdesignation attached to it (from 1-19). File looks like attached in the picture.
My question is concretely: How do i Calculate the Probability of a number occuring between two other numbers as displayed in the picture, the probability of "17" Occuring between two "18".
Also how would i calculate the probability of number x occuring between two different numbers x1 and x2 such as number 14 occuring between 12 and 19.
https://i.stack.imgur.com/Rqjdh.png
So if anyone knows the name of the methodology/formulas i am looking for please let me know.
Thanks!
Comment: Are the random variables behind those events independent? Can the distribution be assumed to be uniform on the set $\{1,\dots,19\}$?
Comment: Also, if you say probability of number 14 occuring between 12 and 19, does this automatically imply, that you would take a 12, then go further until you find the first 19 and then consider the probability of 14 being between them?
Comment: @DimaMcGreen http://i.imgur.com/ipEJo9C.png performad a chisquare test, and here is a histogram for the entire data table. So the Distribution definitely is not uniform.

As for your question I am not sure how to answer it. I guess it would be what I am looking for or at least i would consider it. The idea is: Wait till event 12 has happened, and then wait until event 19 has happened, and then find out the probability of of 14 being between those 2 numbers in the data set, and do this for the entire dataset.
Comment: Hmmm, I never did any practical statistics :) The least you could try is the empirical distribution function.
Answer: Without further assumptions, let $\Omega=\{1,\dots,19\}$. Let $X_i$ denote the value of the $i$-th experiment (or realisation). I guess assuming stationarity will still fit your problem.
If you are looking for $y\in\Omega$ between $x_1\in\Omega\backslash\{y\}$ and $x_2\in\Omega\backslash\{y\}$, by stationarity you can assume $X_0=x_1$ so you are looking for
$$\sum_{m=1}^{\infty}P(X_m = x_2, X_1,\dots,X_{m-1} \in \Omega\backslash\{x_2\}, \exists i\in\{1,\dots,m-1\}: X_i=y).
$$
Depending on the distribution of your events you can simplify this.
Comment: Great, Now ill just have to figure out how to implement this into a calculation in Excel or in R. You don't happen to have experience with this by any chance?
Comment: I think without making assumptions concerning the distribution that won't work out. As said above, I don't have any experience with data... I would try to see if the empirical distribution is of any help. The state space is discrete, so your 3000 events could be sufficient to make significant estimations.
Comment: I will do some readings in one of my seven thousand mathbooks on Empirical Distribution :)

Thank you so much Dima :)


External database content

Question: I have a database which contains categories and articles.
I want to transfert all this content to a new wordpress website.
Is there a way to import data into a wordpress website ?
I want to do that by code because i will need to run import several times.
Thanks a lot
Answer: WordPress supports exporting and importing data. Check out the "Tools" menu.

External database content


Infinite Rubik's Cube

Question: Is there an infinite analog to the Rubik's Cube?  What does its solution-algorithm look like?  For illustration, consider the Rubik's cube with infinite tiles to a side, on all sides, with sides of finite length.
Comment: You might want to look up [Thompson's groups](http://people.math.binghamton.edu/matt/thompson/cfp.pdf) $F$, $T$ and $V$, and also the [Brin-Thompson groups](https://arxiv.org/abs/math/0406046) $nV$. They are not exactly what you are looking for, but I think they might be close. Certainly, they are "slices" of the interval $[0, 1)$, and the groups $nV$ are slices of the $n$-cube $[0, 1)^n$. They also have rather pleasing graphical representations.
Comment: You have to say what you mean.  For example, it is the cube $[-1,1]^3$, but rotations can be made fixing any subset of one of the axes: rotate the planes corresponding to  that subset, fix the rest of the planes
Comment: I wonder how an infinite rubik's cube can have finite sides?
Comment: Problems might just be slices at real valued intervals through the cube rotated iteratively until a confused state is reached and then solving it.
Answer: I made up two variants of infinite Rubik cube. One uses the space $\bigl(\Bbb{Q}\cap[-1;1]\bigr)^3$, which has countably many tiles. The other one uses the space $[-1;1]^3$, which has uncountably many tiles. In both cases, each face has its own colour and a twist is performed by rotating a slice which is orthogonal to any of the axes. The cube is solved if and only if all tiles on each face have the same colour.
If the Rubik cube is scrambled by finitely many twists, the cube can be discretised in such way that it is symetrical and each great tile has only one colour. After that, it can be solved as a Rubik cube with finitely many tiles.
The problems starts when the Rubik cube can be scrambled by infinitely many twists. Each scramble can be represented as a bijective function from $R$ to $R$ where $R$ is either $\bigl(\Bbb{Q}\cap[-1;1]\bigr)^3$ or $[-1;1]^3$. The task is to decompose such function to an infinite sequence of twists. There are uncountably many scrambles, so it might not be even algoritmically solvable.
Comment: Given the ambiguity and modesty of the question statement, I find this answer acceptable. Thank you.

Infinite Rubik's Cube


Laravel Lighthouse: How can I get graphql-codegen to generate typings from my schema?

Question: I'm using Laravel lighthouse to be my graphql server inside my Laravel app. Now I've added custom queries and types to my graphql/schema.graphql file, I want to be able to get typings in my TypeScript Vue 3 app which is located in the Laravel project. However, when I run the graphql-codegen --config codegen.yml command, it fails because the query being generated doesn't match what's in the schema file.
The query in my graphql/schema.graphql file.
type Query {
    posts: [Post!]! @paginate(defaultCount: 10)
}

My Query I call in my Vue component
            {
                posts {
                    data {
                        uuid
                        body
                        user {
                            name
                        }
                    }
                }
            }

The code below is my codegen.yml file

overwrite: true
schema: "./graphql/schema.graphql"
documents: "./resources/js/pages/**/*.vue"
generates:
  ./resources/js/generated.ts:
    plugins:
      - "typescript"
      - "typescript-operations"
      - "typescript-vue-apollo-smart-ops"

Any ideas where I need to point it to or how I get graphql-codegen to generated the correct typings?
Answer: Your source schema is transformed by directives such as @paginate. Use the following artisan command to generate a single file that contains your entire and final schema:
php artisan lighthouse:print-schema

See https://lighthouse-php.com/master/api-reference/commands.html#print-schema


Convert Solana public key from UINT8Array

Question: I have generated  accounts using the Solana CLI, but I am getting the public and private keys as
publicKey: Uint8Array(32) [
  102, 255,  46,  44,  90, 176, 207,  98,
  251,  66, 136, 190, 240,  59, 198, 177,
  169,  35, 153,   3, 163,  68, 188, 214,
  225,  46,  55, 111, 159, 157, 182, 111
],

but I want readable format to sustain key for next transaction.
Comment: Please supply a snippet that demonstrates the problem. Without that we have to guess what you tried, and that trick never works. Please read "[ask]" along with "[How do I format my posts...](https://stackoverflow.com/help/formatting)"
Comment: Thanks to your question, opened up my eyes on how to properly store a publickey on a solana program.

For others, its helpful to read publickey documentation:

https://solana-labs.github.io/solana-web3.js/classes/PublicKey.html
and for rust specific docs:
https://docs.rs/solana-program/1.4.17/solana_program/pubkey/struct.Pubkey.html
Answer: You can try this
console.log(wallet.publicKey.toBase58());
Answer: Pubkey is base58 so this (dirty) vanilla (or any base58 lib) should work.
// ref: https://gist.github.com/diafygi/90a3e80ca1c2793220e5/
const MAP = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
const encode = function (B) { const A = MAP; var d = [], s = "", i, j, c, n; for (i in B) { j = 0, c = B[i]; s += c || s.length ^ i ? "" : 1; while (j in d || c) { n = d[j]; n = n ? n * 256 + c : c; c = n / 58 | 0; d[j] = n % 58; j++ } } while (j--) s += A[d[j]]; return s };
const decode = function (S) { const A = MAP; var d = [], b = [], i, j, c, n; for (i in S) { j = 0, c = A.indexOf(S[i]); if (c < 0) return undefined; c || b.length ^ i ? i : b.push(0); while (j in d || c) { n = d[j]; n = n ? n * 58 + c : c; c = n >> 8; d[j] = n % 256; j++ } } while (j--) b.push(d[j]); return new Uint8Array(b) };

encode(new Uint8Array([
  102, 255,  46,  44,  90, 176, 207,  98,
  251,  66, 136, 190, 240,  59, 198, 177,
  169,  35, 153,   3, 163,  68, 188, 214,
  225,  46,  55, 111, 159, 157, 182, 111
]))

Output
7w4GYV1BxE9Vvn93BG3NZzZQAYoiTXWnNX8rdXBgQ5Tt


Inverter a ordem do fwrite

Question: Gente, alguém me da essa ajuda por favor ! Tenho um formulário onde as pessoas vão por links do youtube contendo músicas e irá gerar para mim uma lista dessas músicas no arquivo musicas.html.
Como posso inverter a listagem dessas músicas ? O arquivo .html insere cada link do YouTube abaixo do outro, sendo que a minha necessidade é que ele vá listando uma por cima da outra, assim facilita em não ter que ficar rolando a lista para baixo afim de atingir os últimos links enviados.
    <form action="" method="POST">
        <input name="link" type="text" placeholder="Link do Youtube" />
        <input type="submit" name="submit" value="Enviar">
    </form>

    <?php
        if (!empty($_POST["link"])) {

            $mus = $_POST['link'];

            $arquivo = "musicas.html";
            date_default_timezone_set('America/Bahia');
            $data = date('d/m/Y H:i:s', time());

            $fp = fopen($arquivo, "a+");
            fwrite($fp,"Data: $data | Link: Click Aqui

");
            fclose($fp);

            echo "Música enviada com sucesso !";

        }
    ?>

Dúvida extra:
Como faço para explodir esse link do Youtube para modificar o link do vídeo e levar até o link de um site para download do .mp3 do vídeo ?

Exemplo -> www.youtube.com/v=AbCdEFgh_
Explode com as modificações -> www.yout.com/v=AbCdEFgh_

O site yout.com permite fazer o download de .mp3 e .mp4 dos vídeos, assim quando eu acessar o meu arquivo musicas.html, terei este resultado:

Data: 12/04/2016 17:51:21 | Link: Click Aqui | Download: Click Aqui

Obrigado
Comment: Você quer pegar somente o valor do atributo href do link ?
Comment: Isso, para modificar o link todo disso:

www.youtube.com/v=eXEmPLo_

Para isso:
www.yout.com/v=eXEmPLo_
Comment: Ok, vou postar a solução.
Answer: Você quer inserir os dados no começo do arquivo, pode usar essa função.
function prepend($string, $filename) {
  $context = stream_context_create();
  $fp = fopen($filename, 'r', 1, $context);
  $tmpname = md5($string);
  file_put_contents($tmpname, $string);
  file_put_contents($tmpname, $fp, FILE_APPEND);
  fclose($fp);
  unlink($filename);
  rename($tmpname, $filename);
}

DUVIDA EXTRA
Você também precisa pegar o valor do atributo href da tag , para isso, você pode usar a função preg_match()
$link  =   "video";

preg_match('/(?<!_)href=([\'"])?(.*?)\\1/',$link, $matches);

print_r( $matches );

Resultando em:

Array ( [0] => href='www.youtube.com/v=eXEmPLo_' [1] => ' [2] =>
  www.youtube.com/v=eXEmPLo_ )

Espero que te ajude.
Comment: Basta inserir essa função acima do código que postei ?
Comment: Essa função grava um texto num arquivo, mas ela insere o registro mais novo na primeira linha, como se fosse uma listagem ordenando de forma decrescente. Então, quando for gravar o arquivo com os links que vem do formulário, você usa ela.

Inverter a ordem do fwrite


time.mktime time.strptime returns negative number

Question: This code:
print(time.mktime(time.strptime("Jan 10 13:44:31", "%b %d %H:%M:%S")))

Returns:
-2208136529.0

Why am I getting a negative number?
Thanks for your help.
Steve
Comment: So, if there's not Year in the input string, it defaults to 1900?  I guess that makes sense, it has to have something in that field.  Not sure how I'm going to handle this but thanks for the help.
Comment: `>>> time.strptime("Jan 10 13:44:31", "%b %d %H:%M:%S")
time.struct_time(tm_year=1900, tm_mon=1, tm_mday=10, tm_hour=13, tm_min=44, tm_sec=31, tm_wday=2, tm_yday=10, tm_isdst=-1)` . Maybe a hint here: `tm_year=1900`
Answer: Changing the year to 1970 solved my issue. I used the below code to change the year:
datetime.replace(year=1970)


Manipulating infinitesimals - what is wrong with this argument?

Question: Now I know that $dy/dx$ is not a fraction etc., but if you look at the works of 17th -- early 19th century mathematicians you'll see they played fast & loose with their infinitesimals and arrived at correct results.
I tried to give that a go on a differential equation, and I think I obtained an incorrect result. My problem is I can't give an argument as to why any of the steps are illegal. Can anyone help me? Here's the derivation:

A point mass $M$ fixed at the origin gravitationally attracts another point mass. The motion of the test mass satisfies:
$$ \ddot{\boldsymbol r} = -\frac{gM\hat{\boldsymbol r}}{r^2} \tag{1}\label{1}$$
The acceleration vector in polar coordinates is given by
$$ \ddot{\boldsymbol r} = (\ddot r - r\dot\varphi^2)\hat{\boldsymbol r} + \frac{1}{r}\frac{d}{dt}(r^2\dot\varphi)\hat{\boldsymbol\varphi} $$
Plugging that in \eqref{1} and equating like components we get that the $\hat{\boldsymbol\varphi}$ component is zero, which implies
$$ r^2\frac{d\varphi}{dt} = k \tag{2}\label{2} $$
a constant. So we only have the radial equation:
$$ \frac{d^2r}{dt^2} - r\left(\frac{d\varphi}{dt}\right)^2 = -\frac{gM}{r^2} $$
Let's try and prove that this is a conic. We'll use \eqref{2}, rewritten as
$$ \frac{r^2\,d\varphi}{k} = dt $$
to get rid of the $dt$'s in the equation. Also, as long as we're playing "$dy/dx$ is a fraction", we may as well go ahead and expand that squared derivative:
$$ \frac{d^2r}{dt^2} - \frac{r\,d\varphi^2}{dt^2} = -\frac{gM}{r^2} $$
Now rewriting $dt^2$ as $r^4\,d\varphi^2/k^2$ in the above,
$$ \frac{k^2\,d^2r}{r^4\,d\varphi^2} - \frac{k^2r\,d\varphi^2}{r^4\,d\varphi^2} = -\frac{gM}{r^2} $$
$$ \frac{d^2r}{r^4\,d\varphi^2} - \frac{r\,d\varphi^2}{r^4\,d\varphi^2} = -\frac{gM}{k^2r^2} $$
$$ \frac{d^2r}{d\varphi^2} - \frac{r\,d\varphi^2}{\,d\varphi^2} = -\frac{gMr^2}{k^2} $$
$$ \frac{d^2r}{d\varphi^2} = -\frac{gMr^2}{k^2} + r $$
Now, this equation already seems to be wrong. It still holds for a circular orbit (don't forget that $k=r^2\dot\varphi$ though), but I don't think it holds for other conics. Moreover, I worked a bit more on this equation (now with more "conservative" steps) and in more than one way arrived at equations that IIRC the general solutions of which are in terms of elliptic functions (and didn't seem to necessarily reduce to something simpler). See:
(1) If the solution is a conic then
$$ r = \frac{ep}{1-e\cos\varphi} $$
and thus
$$ \frac{d^2r}{d\varphi^2} = \frac{2e^3p-e^2p\cos\varphi-e^3p\cos^2\varphi}{(1-e\cos\varphi)^3} $$
but, abbreviating $gM/k^2$ with $a$,
\begin{align}
-ar^2 + r &= -\frac{ae^2p^2}{(1-e\cos\varphi)^2} + \frac{ep}{1-e\cos\varphi} \\
&= \frac{-ae^2p^2(1-e\cos\varphi)+ep(1-e\cos\varphi)^2}{(1-e\cos\varphi)^3} \\
&= \frac{-ae^2p^2+ae^3p^2\cos\varphi+ep+e^3p\cos^2\varphi-2e^2p\cos\varphi}{(1-e\cos\varphi)^3} \\
&= \frac{(ep-ae^2p^2)+(ae^3p^2-2e^2p)\cos\varphi+e^3p\cos^2\varphi}{(1-e\cos\varphi)^3}
\end{align}
Now we must have these two equal. But the coefficients of the cosine-squared terms can only match if $e=0$ or $p=0$. So general conics don't satisfy the eq.
(2) In $r''=-ar^2 + r$, complete the square on the RHS to arrive at something like $r''=-A\rho^2 + B$. We'll have $d\rho/dr=1$ so the eq. is
$$ \rho'' = A\rho^2 + B $$
Multiply by $\rho'$ on both sides and integrate,
$$ \frac{1}{2}\rho'^2 = 2A\rho^3 + B\rho + C $$
Separate the variables:
$$ \frac{d\rho}{\sqrt{4A\rho^3 + 2B\rho + C}} = d\varphi $$
Integrating again the LHS becomes an elliptic integral in general. So, incorrect.

Where is the illegal step and why is it illegal? Or is the mistake somewhere else?
Comment: I have not read all the details of your post, but basically, manipulating things algebraically in a naive way leads to problems with higher order derivatives. But the issues can be avoided, too. Details are discussed in the recently-popular-on-the-internet paper: "Extending the Algebraic Manipulability of Differentials" by Bartlett and Khurshudyan. One version can be found on the arXiv at [here](https://arxiv.org/abs/1801.09553) and another is on the site for the journal "Dynamics of Continuous, Discrete and Impulsive Systems" [here](http://online.watsci.org/contents2019/v26n3a.html).
Comment: Your tangential part of acceleration is wrong.
Comment: Oops... you mean that $1/4$ over there should be a $1/r$? Nice catch. Though I don't think this affects the proof -- the tangential component of acceleration remains 0. I'm updating the OP though.
Comment: Look up the binet equation related to time independent order differential equation.
Comment: $d^2r/dt^2$ is not $d^2r/(dt)^2$ you need to use the chain rule.
Comment: You mean something like $d^2r/dt^2 = \frac{d}{dt}\left(\frac{dr}{dt}\right) = \frac{d}{dt}\left(\frac{dr}{d\varphi}\frac{d\varphi}{dt}\right)$?
Answer: If $r(t)=u(φ(t))$, then $\dot r(t)=u'(φ(t))\dotφ(t)$. With the next $t$ derivative you also need to apply the product rule
$$
\ddot r(t)=u''(φ(t))\dotφ(t)^2+u'(φ(t))\ddotφ(t).
$$
While a lot can be done working with infinitesimals $dt,dr,dφ$ if one exactly defines how they relate to each other, working with higher order difference operators with infinitesimal step size is not that easy.
One trap is to reuse the same letter for a different function. $r$ depends on $t$, not on $φ$, thus the expression $\frac{dr}{dφ}$ is ambiguous. While it still makes sense if both are functions of $t$, to switch to a depencence $r=u(φ)$ requires some inverse function argument and a new letter for the new functional relation.
Comment: Hummmm. What exactly means "ambiguous"? Could you give an example of some correct infinitesimal manipulation involving higher order derivatives?
Comment: Essentially that reduces to manipulations with truncated Taylor series. There is also a practical effect to that as you can efficiently implement the expansions of all the elementary "pocket calculator" functions and thus also of most finitely composed functions. See automatic/algorithmic differentiation where details of that are explained.
Answer: Special thanks to OP who helps me a lot with this.
Your radical substitution where the differentials are treated as fractions are correct, when $r$ is treated as a constant. You can actually check by more conservative methods.
$$
\frac{d^2 r}{dt^2}=\frac{d}{dt}\left(\frac{d r}{dt}\right)=\frac{d}{dt}\left(\frac{d r}{d\varphi}\cdot\frac{d\varphi}{dt} \right)=\frac{d}{dt}\left(\frac{d r}{d\varphi}\cdot\frac{k}{r^2} \right)=\frac{k}{r^2}\frac{d}{d\varphi}\left(\frac{d r}{d\varphi} \right)\cdot \frac{d\varphi}{dt}=\frac{k^2}{r^4}\frac{d^2r}{d\varphi^2}.
$$
However, in general, we have
$$
\frac{d^2 r}{dt^2}=\frac{d}{dt}\left(\frac{d r}{dt}\right)=\frac{d}{dt}\left(\frac{d r}{d\varphi}\cdot\frac{d\varphi}{dt} \right)=\frac{d}{dt}\left(\frac{d r}{d\varphi}\cdot\frac{k}{r^2} \right)=\frac{k}{r^2}\frac{d}{d\varphi}\left(\frac{d r}{d\varphi} \right)\cdot \frac{d\varphi}{dt}-\frac{2k}{r^3}\frac{dr}{d\varphi}=\frac{k^2}{r^4}\frac{d^2r}{d\varphi^2}-\frac{2k}{r^3}\frac{dr}{d\varphi}.
$$
The second term of this does not show up in your radical method, so the final result is incorrect.
However, $dr/d\varphi$ is zero when the orbit is a circle, so your equation is satisfied by a circle.
Your tangential components of the acceleration seems to be wrong
$$
\frac{d^2\mathbf{r}}{dt^2}=(\ddot r - r\dot\varphi^2)\hat{\boldsymbol r}+(r\ddot \theta + 2\dot r \dot\varphi)\hat{\boldsymbol \varphi}.
$$
For a proof, follow this Link.
In your equation, you write $\frac{1}{4}\frac{d}{dt}(r^2\dot\varphi)\hat{\boldsymbol\varphi}=\frac{1}{4}r(r\ddot \theta + 2\dot r \dot\varphi)\hat{\boldsymbol \varphi}$ instead, which differs from the first equation by a factor of $(1/4)r$. However, that does not affect your results, since they are equavalent when set to zero, in your situation.
Comment: Sorry. I will check it again.
Comment: I wrote $\hat{\boldsymbol r}$, with the hat, the unit vector in the radial direction $= \boldsymbol r/r$.
Comment: Hadn't seen this -- no notifications when someone edits a post! Another poster remarked at how I had written the tangential component of acceleration incorrectly. (I edited the OP and fixed it). Though I think this mistake is inconsequential, since we don't use the tangential component of acceleration anyway, only use the fact that $r^2\dot\varphi = \text{const.}$ (which it is regardless of that factor of $r/4$). I'll take a look at your proof of the correctness of the substitution.
Comment: Regarding your proof using conservative methods: in the step in which you pass from $\frac{d}{dt}\left(\frac{d r}{d\varphi}\cdot\frac{k}{r^2} \right)$ to $\frac{k}{r^2}\frac{d}{d\varphi}\left(\frac{d r}{d\varphi} \right)\cdot \frac{d\varphi}{dt}$, it seems that you are assuming $k/r^2$ is a constant, but it is not. If this proof is indeed incorrect, then it actually should hint at what is wrong with my derivation.
Comment: @whatadisgrace Ok, finished my edit.


pdf of a mixed distribution

Question: Consider the following steps to generate a value from a mixed distribution:

Generate $Z$ from $Bernoulli(0.5)$
If $Z=0$, draw $X$ from $Normal(0,1)$
If $Z=1$, draw $X$ from $Beta(1,3)$

I'm wondering what distribution will $X$ follow in this case. Will the pdf be $\frac{1}{2}f_1(x)+\frac{1}{2}f_2(x)$, where $f_1(x)$ is the pdf of $Normal(0,1)$ and $f_2(x)$ is the pdf of $Beta(1,3)$?
Comment: Yes, that would be the PDF.
Answer: Yes
The density would look rather like the black curve below, being the average of the red and pink curves

pdf of a mixed distribution


Distribution of Function over Arithmetic Operations in Python

Question: Lets say I have an mapping, map, which associates various strings to numerical values :
{['a', 1],['b', 2], ['c',5]}

I want to define an operation, op, which will distribute over arithmetic operations. So I want op to function as follows:
op('a+b') = 3

op('b') = 2

op('a*b+c') = 7

etc.
The only way I could think to do it is simply to parse the string, remember the operations, do the mapping, and do the operations. Seems sorta costly/long and I would hope there could be a more elegant solution with a built-in operation.
EDIT:
I realize the way I phrased this wasn't quiet accurate to my question, the mapping isn't defined on my system so I cannot define all possible mappings. I have to query an outside source for the mappings.
Comment: Have you looked at [SymPy](http://sympy.org) as it appears that's the direction you're heading? (either that or using `eval` with a dictionary of your variables :( )
Comment: Don't use `eval()`, it is a huge security hole.
Comment: @2rs2ts I did not recommend it - the ":(" I thought was enough
Comment: related: [Evaluating a mathematical expression in a string](http://stackoverflow.com/q/2371436/4279)
Comment: All right, fair enough :)
Comment: SymPy looks somewhat promising... I realize my original question wasn't quite what I wanted to say as I have to query the mapping per individual string so I cannot form a full dictionary of values.
Answer: 'not sure that you have in mind but Python allow you to override operators. If parsing a string is not desirable, you might create a wrapper class and define the relevant operators to extract the values from your "mapping". Here, I use a dictionary and I define only the "addition":
class V:
    values = { 'a': 1, 'b': 2, 'c': 3 }

    def __init__(self, name):
        self.name = name

    def __add__(self, other):
        return V.values[self.name] + V.values[other.name]

a = V('a')
b = V('b')

print a+b
# display 3

If you work with strings, you may even eval such expression (even if eval is not your best friend from a security point of view -- you should never directly eval an expression coming from untrusted source):
print eval("a+b")
# display 3

Answer: def op(eqn_str,**vars):
    for var,val in vars.items():
        eqn_str = eqn_str.replace(var,str(val))
    return eval(eqn_str)

op('a+b',a=5,b=3)
op('a+b',**{'a':5,'b':3})
my_vars = {'a':5,'b':3}
op('a+b',**my_vars)

or slightly more interesting
def op(eqn_str,**vars):
    eqn_str = re.sub('(a-z)','%(\\1)s',eqn_str)
    eqn_str = eqn_str.format(vars)
    return eval(eqn_str)
#called same way as above

something like that maybe ... although eval is always a little sketchy
really I second Jon's comment that you should probably look at sympy
to figure out what keys you need you can just do
needed_keys = [letter for letter in str_eqn if letter.isalpha()]

Comment: -1 for eval I assume ... well yeah it is kinda bad form ... but Im not gonna write up a whole grammar thats for a different post ...
Answer: well, except if what you want is to reinvent sympy (see the comment), what you have to do is parse the data in your string, create an abstract syntax tree, get the symbols and transform it to python objects. That way you can even respect operators' priority, and YOU'RE NOT USING EVAL.
My best advice for you would be to look at this 70 lines gist that shows how to implement a simple calculator (somehow what you want). You'll only have to match your values with the ones in the string.
In the same spirit as what I'm talking about, @JFSebastian linked a post that's even better.
Answer: Here is a one-liner:
>>> eval('b', dict([['a', 1],['b', 2], ['c',5]]))
2
>>> eval('a+b', dict([['a', 1],['b', 2], ['c',5]]))
3
>>> eval('a*b+c', dict([['a', 1],['b', 2], ['c',5]]))
7


Haproxy Acl in Https

Question: In haproxy settings there is frontend which bind on 443.
The problem is inside this frontend I need to use acl rules in order to distinguish traffic based on server_name.
However, if I am understand correctly I can't use acl together with 443.
If there any way to send ssl traffic to different backends regarding their hostname?
Thanks!
Answer: In the development branch, we have support for SNI (server name indication) which allows a TCP-mode haproxy to know what server an SSL client is targetting if the client uses the extension too (which all recent clients do). Otherwise as indicated by B14D3, you have to decipher the traffic as it's the purpose of SSL to prevent anyone from seeing what's exchanged in it.
Answer: For using haproxy with ssl (443) you need to use stunnel because haproxy does not support ssl it self.
Answer: By now SNI has been properly implemented in haproxy. You can use use-server to distinguish between different hostnames:
Quote from the documentation:

The "use-server" statement works both in HTTP and TCP mode. This makes it
  suitable for use with content-based inspection. For instance, a server could
  be selected in a farm according to the TLS SNI field. And if these servers
  have their weight set to zero, they will not be used for other traffic.

Example from the documentation:
# intercept incoming TLS requests based on the SNI field
use-server www if { req_ssl_sni -i www.example.com }
server     www 192.168.0.1:443 weight 0
use-server mail if { req_ssl_sni -i mail.example.com }
server     mail 192.168.0.1:587 weight 0
use-server imap if { req_ssl_sni -i imap.example.com }
server     imap 192.168.0.1:993 weight 0
# all the rest is forwarded to this server
server  default 192.168.0.2:443 check

Haproxy Acl in Https


Erro no horário de verão (summer time) no bootstrap-datepicker

Question: O plugin parou de funcionar com o início do horário de verão no Brasil. Quando desabilito a opção na minha máquina (Ajustar automaticamente para o horário de verão) o plugin volta a funcionar.
Código:
$('.campodata').datetimepicker({
    useSeconds: false,
    format: 'DD/MM/YYYY HH:MM'
});

Erro no console:
Comment: Bem vindo a StackOverflow em português, vulgo SOpt. Editei sua pergunta para remover a parte em inglês(não escrevemos em inglês para explicar o problema), também retirei sua saudação, pois como as pessoas leem em horários diferentes ela perde o sentido, nosso foco está sempre nas perguntas e respostas, pode parecer grosseiro de minha parte, mas é uma convenção que temos aqui :)
Comment: Arthur, qual é a versão do datepicker que estás a usar?
Comment: Da uma olhada aqui: https://github.com/eternicode/bootstrap-datepicker
Tem um link pra uma demo online, tenta reproduzir o problema que você está tendo na sua aplicação, se acontecer vc pode abrir uma issue ou tentar resolver o problema. Caso não aconteça, vc pode tentar da uma olhada senao tem nada de errado no seu código.
Comment: Ele dá algum erro? No meu simplesmente não funciona, sem erro no console....
Answer: Tive esse problema recentemente. Para corrigí-lo editei um trecho o método fill do bootstrap-datepicker que antes era assim:
var prevMonth = new Date(year, month - 1, 28, 0, 0, 0, 0),
   day = DPGlobal.getDaysInMonth(prevMonth.getFullYear(), prevMonth.getMonth());

E depois ficou assim:
var prevMonth = new Date(year, month - 1, 28, 12, 0, 0, 0),
   day = DPGlobal.getDaysInMonth(prevMonth.getFullYear(), prevMonth.getMonth());

E o método parseDate, onde era:
date.setHours(0);

Ficou:
date.setHours(12);

Comment: Sua nota de rodapé cabe bem no seu "Sobre mim", que diga-se de passagem está vazio. O site costuma evitar qualquer tipo de interferência nas publicações, seja na pergunta ou nas respostas. Aqui costumamos evitar saudações, agradecimentos e propagandas. Se o seu link fosse vital para o entendimento da resposta faria sentido em mantê-lo, mas do jeito que está é meramente promocional e foge do escopo do site. Qualquer dúvida pode consultar o [meta].


A value of type 'Widget?' can't be assigned to a variable of type '_BlocProviderInherited'

Question: So, my code:
Type _typeOf<T>() => T;

abstract class BlocBase {
  void dispose();
}

class BlocProvider<T extends BlocBase> extends StatefulWidget {
  BlocProvider({
    Key? key,
    required this.child,
    required this.bloc,
  }) : super(key: key);

  final Widget child;
  final T bloc;

  @override
  _BlocProviderState<T> createState() => _BlocProviderState<T>();

  static T of<T extends BlocBase>(BuildContext context) {
    final type = _typeOf<_BlocProviderInherited<T>>();
    _BlocProviderInherited<T> provider =
        context.getElementForInheritedWidgetOfExactType<type>()?.widget;
    return provider?.bloc;
  }
}

class _BlocProviderState<T extends BlocBase> extends State<BlocProvider<T>> {
  @override
  void dispose() {
    widget.bloc.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return new _BlocProviderInherited<T>(
      bloc: widget.bloc,
      child: widget.child,
    );
  }
}

class _BlocProviderInherited<T> extends InheritedWidget {
  _BlocProviderInherited({
    Key? key,
    required Widget child,
    required this.bloc,
  }) : super(key: key, child: child);

  final T bloc;

  @override
  bool updateShouldNotify(_BlocProviderInherited oldWidget) => false;
}

The offending line is this one:
_BlocProviderInherited<T> provider =
        context.getElementForInheritedWidgetOfExactType<type>()?.widget;

And throws the error:
A value of type 'Widget?' can't be assigned to a variable of type '_BlocProviderInherited<T>'.

Edit: Additionally, it is throwing an error on the next line:
return provider?.bloc;

Error:
A value of type 'T?' can't be returned from the method 'of' because it has a return type of 'T'.

This is previously working code from my published app that no longer works after upgrading flutter from a quite old version.
Anyone know what it wants from me?
Edit: Have included full code, as referenced functions were not previously shown.
Comment: Code I wrote. There is no package, my only import is: 'package:flutter/material.dart';
Comment: Is this code you wrote or code from the Bloc package you are using?
Comment: The implementation is wrong the answer to your question will not help you with this code working. I would suggest you use a Bloc library or at least look at how it is implemented under the hood. Regarding your question - you try to assign `Widget widget` to `_BlocProviderInherited provider`, which obviously won't work, and that is basic programming and basic flutter, so I would suggest you to read the documentation about that also.
Answer: _BlocProviderInherited<T> provider =
        context.getElementForInheritedWidgetOfExactType<type>()?.widget;

This line fails because the variable types don't match. A Widget? is not a _BlocProviderInherited<T>. My guess is that the extends InheritedWidget used to mean that _BlocProviderInherited<T> had a type of Widget, but now (based on the InheritedWidget documentation and the method documentation) that is not the case.
A value of type 'T?' can't be returned from the method 'of' because it has a return type of 'T'.
This error is caused by trying to return a variable that can be null from a method that only returns non-null variables. Flutter has changed a lot between major releases, including adding null safety. To fix it, change that line to return provider!.bloc; or provide a default bloc after: return provider?.bloc ?? <default value here>. Either way the returned value won't be null.
Comment: Hi mate, sorry I have been away and just looking at this now.   So you solved part 2, in that I can just remove the '?' and it works fine now.   The problem with the first part is you have given me some information, but I don't know what actual code to use to make this work again.
Comment: Thanks for getting back to me again, but you can't do what you suggested here.  I changed everything like you said, but it still will not allow _BlocProviderInherited anywhere.   The closest I have come to resolving this is:  _BlocProviderInherited provider =
        context.getElementForInheritedWidgetOfExactType as _BlocProviderInherited;  This results in a compilable app finally, but the logic is wrong and it crashes.
Comment: @bisclavret Please accept the answer if it solved your problem/helped. If not, can you please tell me what didn't work/help?
Comment: @Bisclavret based on the documentation, it looks like you'll have to redo `_BlocProviderInherited provider =       context.getElementForInheritedWidgetOfExactType()?.widget;` to be `_BlocProviderInherited provider = context.getElementForInheritedWidgetOfExactType()?.widget` and change `` to `` in every place that refers to `_BlocProviderInherited`.


Qual a diferença ente arrays vs. collections em C#?

Question: Referente a arrays e collections em C#, variam de aplicação para aplicação ou existe uma unanimidade entre eles?
Comment: classe [Array](https://docs.microsoft.com/pt-br/dotnet/api/system.array?view=netframework-4.7.2) e interface [ICollection](https://docs.microsoft.com/pt-br/dotnet/api/system.collections.icollection?view=netframework-4.7.2).
Answer: Se existisse unanimidade não precisaria existir os dois. A dicotomia entre esses dois nem faz muito sentido.
Ao contrário do que as pessoas podem achar, uma coleção que está falando deve ser do tipo ICollection, e é algo abstrato, não existe de fato. Você usa uma coleção em específico, e existem várias, assim você deve escolher qual é mais adequada para você para cada situação. Não existe solução única, cada estrutura de dados (e este é o assunto que deve estudar) tem vantagens e desvantagens. Despende da sua aplicação naquele momento o que escolher.
De forma geral nunca deve usar array em C#. Ele é concreto demais, tem limitações e quase nenhuma vantagem relevante. Quase todas as estruturas de dados que implementam ICollection tem todas vantagens relevantes do array e mais algumas. O uso de array em código moderno e bem escrito só deveria usar array por causa de código legado ou que tenha alguma questão de performance específica.
Tipos que são coleções costumam ter a mesma estrutura básica do array, inclusive internamente tem um array em muitas delas, mas tem a vantagem de poder fazer algumas operações que array não conseguem, por exemplo aumentar ou reduzir o tamanho da coleção. Pode ver mais sobre isso em Diferença entre ICollection, IList e List?. Lendo aí, uma coleção não garante que possa inserir ou remover itens no meio da coleção, apenas uma lista (IList) permite isto. Ok, ela é uma coleção também, mas existem coleções que não possuem esta característica.
Uma coleção pode ou não definir tipos nelas, mas as que não permitem são consideradas obsoletas e para todos os efeitos não devem ser usadas, esquece que elas existem, são problemáticas. Mesmo que queira colocar qualquer tipo na coleção moderna e eficiente use o tipo object. E mesmo neste caso pense bem se é isto mesmo que quer, quase sempre é um erro fazer assim. E pode fazer com array também, só usar object[].
Também não faz o menor sentido o que a outra resposta (havia uma, e foi apagada, a maioria desta resposta é contestação do que havia errado na outra) diz sobre os elementos serem somente de leitura ou não. Em laços brutos em qualquer caso que a estrutura não seja explicitamente readonly tanto array quanto as coleções podem ter seus dados alterados normalmente, já em laços foreach há limitações em ambos por um conta do iterador.
Também estava errado que um deles é definido em tempo de compilação e outro em execução. São iguais, ambos são escritos e definidos em tempo de compilação e ambos são instanciados em tempo de execução, a diferença é só como cada um pode ser manipulado, nada mais, inclusive porque boa parte das coleções tem um array instanciado internamente.
Coloquei no GitHub para referência futura.
Answer: Arrays são estruturas de dados simples e eficientes para armazenar um conjunto fixo de elementos do mesmo tipo. Eles têm um tamanho fixo e são ideais quando você sabe exatamente quantos elementos precisa armazenar e não precisa adicionar ou remover elementos com frequência.
Por outro lado, as collections em C# (como List, Dictionary, HashSet, etc.) fornecem estruturas de dados mais flexíveis e dinâmicas. Elas são úteis quando você precisa lidar com conjuntos de elementos que podem crescer ou diminuir ao longo do tempo. Collections oferecem métodos convenientes para adicionar, remover e manipular elementos de forma mais fácil do que os arrays.
A escolha entre arrays e collections dependerá das necessidades do seu aplicativo. Se você precisa de uma estrutura de dados simples e sabe o tamanho exato do conjunto de elementos, um array pode ser a melhor escolha devido à sua eficiência. No entanto, se você precisa de flexibilidade para lidar com conjuntos dinâmicos de elementos, as collections são mais apropriadas.
Além disso, as collections em C# geralmente oferecem recursos adicionais, como pesquisa eficiente, ordenação e outros métodos úteis, que podem ser valiosos em muitos cenários de aplicativos. Portanto, é importante avaliar os requisitos específicos do seu projeto antes de decidir entre arrays e collections.
Comment: Se o Autor da Pergunta quisesse usar o ChatGPT ele iria direto ao site da OpenIA. [O Conteúdo gerado por ChatGPT não é permitido na rede](https://pt.meta.stackoverflow.com/q/8842/137387)  . https://imgur.com/a/OtRBCw0


convert string value to charsequence and show it in notification in android

Question: I want to show the result of this function in notification.
public class TimerService extends Service {
    public String timeString;
... // service methodd
public class CountingDownTimer extends CountDownTimer{
             public CountingDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long leftTimeInMilliseconds) {

            timeString = String.format("%02d", 5000/ 60)
                    + ":" + String.format("%02d", 5000% 60);
                ...
        }
...// at the end of TimerService class
                    notification = new NotificationCompat.Builder(this)
                    .setContentText(timeString).build();

but unfortunately nothing(null) show in the notification. what can I do? how can I convert String value to char sequence?
Answer: I had similar problem before. you should create new method and put notification in it.
private void setupNotification(String s) {}

The most important thing is that you should send timestring from CountingDownTimer to setupNotification. so do it like this:
public class CountingDownTimer extends CountDownTimer{
    public String timeString=null;

         public CountingDownTimer(long millisInFuture, long countDownInterval) {
        super(millisInFuture, countDownInterval);
    }

    @Override
    public void onTick(long leftTimeInMilliseconds) {
        timeString = String.format("%02d", 5000/ 60)
                + ":" + String.format("%02d", 5000% 60);
       setupNotification(timeString);

    }

private void setupNotification(String s) {
    notification = new NotificationCompat.Builder(this)
                .setContentText(s)
}

I hope it works!
Answer: String s="STR";
CharSequence cs = s;  // String is already a CharSequence

so you just pass timeString to setContentText
Edit:
it seems you call notification.setContentText() before CountingDownTimerstarts.
call notification
inside OnFinish()
 public CountingDownTimer(long millisInFuture, long countDownInterval) {
        @Override
        public void onTick(long l) {
            timeString = String.format("%02d", l / 60)
                    + ":" + String.format("%02d", l % 60);

        // Add Here
        notification = new NotificationCompat.Builder(this)
                             .setContentText(timeString).build();

        }

        @Override
        public void onFinish() {

        }
    }.start();

here notification set after Countdown timer finished
Comment: I update my question and post some details. would you please check it.
Comment: oh no! I want to show counter in notification during counting.


QoS - How to detect Youtube HTML5 video over port 443?

Question: I'm running Tomato on a small network. It has fairly comprehensive QoS controls, but I'm having trouble getting it to correctly classify Youtube HTML5 videos over port 443. They are being classified as FileXfer, the same as a regular download. I want FileXfer to only be used for normal file downloads, whereas HTML5 video should be classified as Media. Is there any additional rule I can use to match Youtube? Or is this not possible since it's encrypted traffic over port 443?
Thanks a lot for the help.
Comment: It actually _is_ a file transfer.
Comment: Everything coming in from the internet is a file transfer. :-) The problem is recognizing what *kind* of file is being transferred so as to assign it the correct priority.
Answer: Add a classification to throttle traffic on port 443 after 512kb have been downloaded to a specific internal address. or you can set the destination address to any.
it will look like this in the end

Inbound Direction:
<code>TCP
DstPort: 443
Transferred: 0-512kb
</code>

make sure you set src ip is statically assigned on the machine so tomato will know whom to throttle. or you can set a DHCP reservation to assign that machine the same address each time.
*make sure your on inbound classification
Here's how it looks:
Comment: Thanks a lot for the reply. I actually want to assign *higher* priority to Youtube downloads, and make it throttle other kinds of large file downloads, but *only* when needed. In other words, I want full-speed normal file downloads as long as nobody is trying to stream a video.
Comment: what are your layer 7 options in the classifications?
Comment: I tried `httpvideo` and `youtube-2012`, doesn't seem to catch it.
Comment: [heres a list of supported layer 7 protocols.](http://l7-filter.sourceforge.net/protocols) youtube is not a protocol but i thought it may have found a pattern and created into a filter in the "Layer 7 Filter" project. but it hasnt worked.
Comment: [Pattern Writing](http://l7-filter.sourceforge.net/Pattern-HOWTO) gives you the ability to write a specific filter to add to L7-Filtering.
Comment: as far as i can see unless you add your own filter, you will have to accelerate by ip address or mac on port 443 and low(er) priority on 80.


IPMI device flooding /var/log/messages

Question: I've a CentOS 7.6 server being flooded by the IPMI device with a lot of errors on a specific sensor:
<code>ipmievd: Unknown sensor ff
ipmievd: Get SEL Entry 1fe command failed: Requested sensor, data, or record not found
</code>
Any ideia on how to do this?
Answer: A simple firmware upgrade solved the issue.
I only upgraded the BIOS completely forgetting about the IPMI firmware.
Link to the SuperMicro firmware downloads is here:
https://www.supermicro.com/support/bios/firmware.aspx

IPMI device flooding /var/log/messages


Hamiltonian Monte Carlo (HMC): what's the intuition and justification behind a Gaussian-distributed momentum variable?

Question: I am reading an awesome introductory HMC paper by Prof. Michael Betancourt, but getting stuck in understanding how do we go about the choice of the distribution of the momentum.
Summary
The basic idea of HMC is to introduce a momentum variable $p$ in conjunction with the target variable $q$. They jointly form a phase space.
The total energy of a conservative system is a constant and the system should follow Hamilton's equations. Therefore, the trajectories in the phase space can be decompose into energy levels, each level corresponds to a given value of energy $E$ and can be described as a set of points that satisfies:
$H^{-1}(E) = \{(q, p) | H(q, p) = E\}$.
We would like to estimate the joint distribution $\pi(q, p)$, so that by integrating out $p$ we get the desired target distribution $\pi(q)$. Furthermore, $\pi(q, p)$ can be equivalently written as $\pi(\theta_E \hspace{1.5pt} | \hspace{1.5pt} E) \hspace{1.5pt} \pi(E)$, where $E$ corresponds to a particular value of the energy and $\theta_E$ is the position on that energy level.
\begin{equation}
\pi(q, p)=
\begin{cases}
\pi(p  \hspace{1.5pt} |  \hspace{1.5pt} q)  \hspace{1.5pt} \pi(q) \\
\pi(\theta_E \hspace{1.5pt} | \hspace{1.5pt} E) \hspace{1.5pt} \pi(E), \hspace{5pt} \text{microcanonical decomposition}
\end{cases}
\end{equation}
For a given value of $E$, $\pi(\theta_E \hspace{1.5pt} | \hspace{1.5pt} E) $ is relatively easier to know, as we can perform integration of the Hamilton's equations to get the data points on the trajectory. However, $\pi(E)$ is the tricky part that depends on how we specify the momentum, which consequently determines the total energy $E$.

Questions
It seems to me that what we are after is $\pi(E)$, but what we can practically estimate is $\pi(E \hspace{1pt} | \hspace{1pt} q)$, based on the assumption that $\pi(E \hspace{2pt} | \hspace{1pt} q)$ can be approximately similar to $\pi(E)$, as illustrated in Fig. 23 of the paper.  However, what we are actually sampling seems to be $\pi(p \hspace{1pt} | \hspace{1pt} q)$.
Q1: Is that because once we know $\pi(p \hspace{1pt} | \hspace{1pt} q)$, we can easily calculate $E$ and therefore estimate $\pi(E \hspace{2pt} | \hspace{1pt} q)$?
To make the assumption that $\pi(E) \sim \pi(E | q)$  hold, we use a Gaussian distributed momentum. Two choices are mentioned in the paper:
\begin{equation}
\pi(p|q)=
\begin{cases}
\mathcal{N}(p \hspace{1pt}| \hspace{1pt} 0, M) \hspace{5pt} \text{Euclidean-Gaussian kinetic energy} \\
\mathcal{N}(p \hspace{1pt}| \hspace{1pt} 0, \Sigma(q)) \hspace{5pt} \text{Reimannian-Gaussian kinetic energy},
\end{cases}
\end{equation}
where $M$ is a $D \times D$ constant called Euclidean metrics, aka mass matrix.
In the case of first choice (Euclidean-Gaussian), the mass matrix $M$ is actually independent of $q$, so the probability we are sampling is actually $\pi(p)$. The choice of the Gaussian-distributed momentum $p$ with covariance $M$ implies that the target variable $q$ is Gaussian-distributed with covariance matrix $M^{-1}$, as $p$ and $q$ need to be transformed inversely to keep the volume in the phase space constant.
Q2: My question is how can we expect $q$ to follow a Gaussian distribution? In practice $\pi(q)$ could be any complicated distribution.
Answer: It's not so much that we are after $\pi(E)$, it's just that if $\pi(E)$ and $\pi(E|q)$ are dissimilar then our exploration will be limited by our inability to explore all of the relevant energies.  Consequently, in practice empirical estimates of $\pi(E)$ and $\pi(E|q)$ are useful for identifying any potential limitations of our exploration which is the motivation for the comparative histogram and the E-BFMI diagnostic.
So, what do we know about the two distributions?  As we increase the dimensionality of our target distribution then $\pi(E)$ sort-of-tends to look more and more Gaussian.  If our integration times are long enough then our explorations of the level sets will equilibrate and if $\pi(p | q)$ is Gaussian then $\pi(E|q)$ will also tend to be more and more Gaussian.
Hence a Gaussian-Euclidean kinetic energy is a good starting point but it is by no means always optimal!  I spend a good bit of time trying to fit models where Stan yells at me about bad E-BFMI diagnostics.  A Gaussian-Riemannian kinetic energy can be a significant improvement in many cases as the position-dependent log determinant in $\pi(p | q)$ can make $\pi(E)$ significantly more Gaussian, but this there is still much more research to be done to fully understand the problem.
Comment: @cwl - it's a standard asymptotic argument.  If the target distribution converges to an independently distributed distribution with increasing data or parameters then $pi(E)$ will converge to a $chi^{2}$ which will be well approximated by a Gaussian above a few dimensions.  On the other hand we tend to reach for Hamiltonian Monte Carlo in practice when the target is complex so the asymptotics may not be particularly relevant.  Hence the hedging.
Comment: I was trying to write an answer, but if THE Michael Betancourt is on Cross Validated, then I'll gladly step back :-) just a note, " log determent" is most likely a typo: I bet you meant "log determinant".
Comment: Flattered to have @Michael Betancourt's answer :-) Just curious, when you said "As we increase the dimensionality of our target distribution then $\pi(E)$ sort-of-tends to look more and more Gaussian", is there a theoretical proof or is it an empirical observation?
Comment: Got it @Michael Betancourt, thanks a lot for the explanation!


Integrating a Periodic Function

Question: Problem: Suppose $f:\mathbb R→\mathbb R$ is continuous and has period $p$, so that $f(x+p)=f(x)$ for all $x\in \mathbb R$. Show that $\int_{x}^{x+p}f(t)dt$ is independent of $x$ in that, for all $x,y$
$$\int_x^{x+p}f(t)dt=\int_y^{y+p}f(t)dt.$$
Show then, that $\int_0^p[f(x+a)-f(x)dx]=0$ for any number $a$. Conclude that for any number $a$, there is $x$ such that $f(x+a)=f(x)$.

I do not know how to start this problem. I thought about defining a function $g(x)=f(x+p)-f(x)$. This is not equal to $\int_x^{x+p}f(t)dt$ right? Even though there seems to be a close relationship by the FTC. This is a clear thing when discussing $\cos(x)$ or $\sin(x)$, trig functions since they do have this periodicity. How am I supposed to show this is $x$ independent? Then it seems like we're supposed to integrate the original integral.
Answer: The derivative of $\int_x^{x+p} f(t) dt $ w.r.t. $x$  is $f(x+p)-f(x)$ which is $0$ by hypothesis. Hence this function is a constant and $\int_x^{x+p} f(t) dt =\int_y^{y+p} f(t) dt $ for  any $x,y$. In particular $\int_x^{x+p} f(t) dt =\int_0^{p} f(t) dt $. Make the substitution $u=t-x$ to get $\int_0^{p} f(u+x) du =\int_0^{p} f(t) dt $. This can be written as $\int_0^{p} [f(t+x)-f(t)] dt=0$. Now the integrand here (which is continuous) cannot take only positive values or only negative values since the integral won't be $0$ in such cases. Hence it must attain the value $0$ at some point.
( I proved that for every $x$ there exists $t$ such that $f(x+t)=f(t)$ which is same as what we are asked to prove with slight change of notations).
Comment: @help Your $g(x)$ is just $0$ by periodicity. It is not equal to $\int_x^{x+p} f(t)dt$ .
Comment: So, I know I asked if the integral was equal to the $g(x)$ I have written, but now I'm asking how. One, has to be derivative of the other doesn't it?
Comment: Okay, I get it, I understand that now. Thank you!

Integrating a Periodic Function


Are there real numbers that cannot be uniquely expressed with a finite number of symbols?

Question: Are there real numbers that cannot be uniquely expressed with a finite number of symbols? Is this the same thing as an uncomputable number?
I can show that if there is one such number then there are infinitely many, and the set of all these numbers is not compact if it is nonempty, but I don't know if any such numbers exist.
Suggestions for tags are welcome.
Edit: I want to add that by "symbols" I mean numbers, mathematical symbols, or English language descriptions (or any language really). So for π, you could write it as "the ratio of a circle's circumference to its diameter" and that would count.
Comment: I guess that would mean "using the whole set theoretic universe to our disposal". But this could also mean that the language you allow for this is uncountable, e.g. one that has a constant symbol for each and every real number, and therefore all the reals are definable. And don't even get me started about asking what is the logic in which we are allowed to write the formulas. I'm sorry if this sounds annoying or pedantic, but this is a very naive question that has an answer once formalized properly, but the formalization is usually **very** not-naive and technical.
Comment: I can only recommend that you look at the links I gave in the first couple of comments.
Comment: Relevant soapboxing: http://karagila.org/2015/name-that-number/
Comment: Also http://math.stackexchange.com/questions/1125213/definable-real-numbers and http://math.stackexchange.com/questions/961558/undefinable-real-numbers are relevant here. Which may or may not already answer your question in detail.
Comment: I think that all the mentioning of "language" in this post refer to mathematical language. Defining something means giving a definition in a mathematical language. But *which one*? The language of orders? Of fields? Of ordered fields? Of exponential fields? Of set theory itself? Etc. etc.
Comment: @AsafKaragila I was thinking any description whatsoever
Comment: @AsafKaragila essentially anything that can be written down.
Comment: @AsafKaragila that's a good point, but that answer definitely falls outside the realm of "acceptable answers" under the rules I want to use. I'll try to think of a better phrasing.
Answer: Internally, most of them cannot be so expressed, assuming you have a finite alphabet. The set of all finite strings from a finite alphabet is countable, but the reals are uncountable. Consequently, every function from the set of strings to the set reals is missing uncountably many reals.
Externally, it is possible (but not necessary) that every real number can be uniquely expressed in the same metalanguage you use to describe the set theory you're using. Here is a related question asking whether, not just each individual real number, but every set can be defined.
Comment: Thanks for the explanation! Could every member in a countable infinite set of number (for example $\mathbb N$) be represented by an alphabet of a limited length (for example, 10 pages)?
Answer: Yes.
Just note that there are uncountably many real numbers, while there are only countably many finite strings of symbols (unless you are willing to use uncountably many symbols, but then I guess the question is moot, as you might as well have one symbol for each real), and most of them don't even describe a real number.
The numbers you are asking about are called definable numbers. They do include computable numbers, but there are definable numbers which are not computable.
Comment: What about models of ZFC which are pointwise definable?
Comment: @AsafKaragila Well, that's not quite accurate - in a slightly larger universe, all reals are definable *from ordinal parameters* (you have to find the right part of the continuum pattern), and that's not really surprising since there are plenty of those.
Comment: @AsafKaragila To be fair, this answer is probably talking about the "actual" real numbers, and "obviously" the actual universe isn't pointwise definable. :P (I love pointwise definable models, so weird!)
Comment: @Noah: But one can always code all the reals into a GCH pattern without adding new reals. So in a slightly larger universe, all the reals are definable!
Comment: @AsafKaragila: Well, those models clearly have no idea (well, no correct idea) what a finite string of symbols is (that, or "countable"), and hence of no interest when the question is about actual real numbers and actual finite strings of symbols.
Comment: @Noah: I'm pretty sure that you can code them in intervals of length $\omega$ above $\omega_1$. Then you can just say that there is some limit ordinal $\alpha$ such that $x$ is the GCH pattern between $\aleph_\alpha$ and $\aleph_{\alpha+\omega}$ (more or less).
Comment: @tomasz That's only partly right - these models *can* have a correct understanding of the "actual" set of finite strings from a countable alphabet. They will, however, think that certain sets are uncountable which (externally) are actually countable. However, this happens in a much broader way too by the [Lowenheim-Skolem theorem](https://en.wikipedia.org/wiki/L%C3%B6wenheim%E2%80%93Skolem_theorem).
Comment: @AsafKaragila That doesn't let you define an individual real in a parameter-free way - multiple reals will satisfy the definition "I am coded into the continuum pattern above some limit $\alpha$" . . .
Comment: @NoahSchweber: Hence my parenthetical remark.
Comment: @tomasz Yes indeed - I just wanted to clear things up around that.
Comment: @Noah: Okay, sure, I concede to that remark, then. But nobody said "no ordinal parameters!" :-) Also, since the language wasn't specified, maybe it includes all the reals as constants, eh? :P
Comment: @AsafKaragila: That in turn is addressed by the parenthetical remark in my answer. ;)
Answer: I'd appreciate it if a set-theorist chimes in to shred this answer but here is a half-serious attempt:
Apply a well-ordering to the real numbers.
Define $$E = \{x \in \mathbb R : \text{$x$ cannot be uniquely expressed with a finite number of symbols}\}.$$
Assume $E \not= \emptyset$. Then $E$ has a least element $e$. Thus $e$ cannot be uniquely expressed with a finite number of symbols, yet we can unambiguously state

$e$ is the least element of $\mathbb R$ (unique, under the given well-ordering) that cannot be uniquely expressed with a finite number of symbols

which uniquely expresses $e$ with a finite number of symbols. This is a contradiction which leads to $E = \emptyset$.
p.s. My own guess is that the argument fails because the well-ordering itself is not expressible with finitely many symbols.
Comment: This is kind of an infinitary variant of [Berry's paradox](https://en.wikipedia.org/wiki/Berry_paradox), which founders on the fact that you need to specify what "expressed" means, in a way such that this meaning can _itself_ be "expressed". The problem of being sure _which_ well-ordering you're talking about is just a cherry on top.
Comment: The argument fails because you don't tell us what is the language in which we are allowed to use to express these real numbers. If this is something like the language of ordered fields with some basic arithmetical augmentations (e.g. roots and exponents) then well-ordering is not at all definable. If this is the full-power of the language of set theory... well, then it is *consistent* that a well-ordering is in fact expressible.


Document.js:54 Uncaught TypeError: Cannot read properties of undefined (reading 'traverse') Autodesk Viewer + React

Question: Since Sunday, February 18, I am experimenting in this project (react + Autodesk Viewer):
Proyect: https://github.com/autodesk-platform-services/viewer-react-sample
The following error:

Document.js:54 Uncaught TypeError: Cannot read properties of undefined
(reading 'traverse')
at new Document (Document.js:54:18)
at Function.onSuccess (Document.js:172:29)
at onSuccessWrapped (Xhr.js:609:40)
at XMLHttpRequest.onLoad (Xhr.js:851:34)

Error Image
enter image description here
Before that date, I didn't have that, the problem didn't exist. I checked the updates and there was one on February 14 but I see no relation to the error. I tried different environments, browsers, computers, etc. Does anyone have any ideas?
Updates:
https://aps.autodesk.com/en/docs/viewer/v7/change_history/changelog_v7/
Install the proyect with dependencies ,but not run the models .
Answer: This might be related to a recent change in the Viewer SDK. Before this change, it was possible to call Autodesk.Viewing.Initializer without specifying the env option, and the viewer would try to auto-detect the proper settings based on the URL of the website that's hosting it. After the change, the auto-detected settings might be different, so I'd recommend hard-coding the env property to be on the safe side. Please see this blog post for more details: https://aps.autodesk.com/blog/getting-404-resource-not-found-error-viewer.
Answer: Making some tests into loadModel function I faced this error too, the solution for me was add the "urn:":
Autodesk.Viewing.Document.load(
   "urn:" + urn,
   onDocumentLoadSuccess,
   onDocumentLoadFailure
);


How to get the parent entity title inside image.html.twig

Question: I want to get the node title inside an image.html.twig override so I can use it to replace the 'title' and 'alt' attributes of the image.
So far I was able to pass simple variables with THEME_preprocess_image(&$variables) but no luck getting the title of the parent node.
Comment: Try https://api.drupal.org/api/drupal/core%21includes%21theme.inc/function/template_preprocess_field/8.5.x `template_preprocess_field()`, then check for the field name/type/etc. inside an `if ()` statement.
Answer: The cleanest solution that I could find is to get node object in image-formatter.html.twig which is a wrapper to image.html.twig.
Add THEMENAME_preprocess_image_formatter to your THEMENAME.theme
function THEMENAME_preprocess_image_formatter(&$variables) {
  $variables["node"] = $variables['item']->getEntity();
}

Copy core/themes/classy/templates/field/image-formatter.html.twig into your THEMENAME/templates directory.
Now you can get the node title in this twig file using {{node.getTitle()}} or {{node.label()}}
The twig file might look like this
Node title: {{node.getTitle()}}

{% if url %}
  {{ image }}
{% else %}
  {{ image }}
{% endif %}

Don't forget to rebuild cache (clear cache) for the changed hooks/twig files to be seen by your Drupal installation.
Alternatively if you want to just change the alt and title attributes of your image based on the node title here is one way to do it (covers question in the comments)
function THEMENAME_preprocess_image_formatter(&$variables) {
  $node = $variables['item']->getEntity();
  $variables["image"]["#alt"] = $node->label();
  $variables["image"]["#title"] = $node->label();
}

Comment: Thanks for the answer. Your solution worked as you said and I was able to print the title of the node inside image-formater.html.twig.
The problem is that I need the title inside {{ image }} so I can replace the 'title' and 'alt' attributes and I think the corresponding template is the image.html.twig but when I tried to do that by replacing:
Comment: THEMENAME_preprocess_image_formatter()
with:
THEMENAME_preprocess_image()
I get
Error: Call to a member function getEntity() on null

Am I missing something. Is the image.html.twig the template I need or there is a way to override {{ image }} inside image-formater.html.twig?
Comment: yes entity is not available inside `THEMENAME_preprocess_image`, I am not sure why.  As a workaround you can bring all the code you have in `image.html.twig` inside  `image-formatter.html.twig`  and put it where right now there is `{{ image }}`.
Comment: If you implement the workaround just make sure other image fields don't break.
Comment: @NikosKakos also look at alternative solution in my answer based on your comment question.


Does the Hilbert transform of Schwarz function decay far away

Question: The Hilbert transform $H$ of Schwarz functions can be defined as
\begin{equation}
Hf(x)=\int_{|y|<1}\frac{f(x-y)-f(x)}{y}dy + \int_{|y|>1} \frac{f(x-y)}{y}dy.
\end{equation}
I would like to know whether
\begin{equation}
Hf(x)\to 0 \ \ \ \ \ as\ \ |x|\to\infty
\end{equation}
or not. If it is true, please show me how to prove this. If not, please give me the counter example.
Thank you.
Answer: Note: the following is valid only for $f$ of compact support. As noted in mickeo's comment, functions in the Schwarz class do not in general have compact support.
Suppose that the support of $f$ is contained in $[-R,R]$, $R>0$.

If $|x|>R+1$ and $|y|<1$, then $f(x)=f(x+y)=0$, and the first integral is equal to $0$.
If $x>R+1$ and $|y|>1$, then
$$
\Bigl|\int_{|y|>1} \frac{f(x-y)}{y}\,dy\Bigr|=\Bigl|\int_{x-R}^{R+x} \frac{f(x-y)}{y}\,dy\Bigr|\le\frac{\|f\|_\infty}{x-R}.
$$
If $x<-R-1$ and $|y|>1$ a similar reasoning applies.

Proof for $f$ in te Schwarz class
There is a constant $C$ such that
$$|f(x)|, |f'(x)|\le\frac{C}{1+x^2}\quad\forall x\in\mathbb{R}.$$
Then, by the mean value theorem,
$$
\Bigl|\int_{|y|<1} \frac{f(x-y)-f(x)}{y}\,dy\Bigr|\le\sup_{x-1\le\xi\le x+1}|f'(\xi)|\le\frac{C}{1+(x-1)^2}.
$$
For the second integral we have
$$
\Bigl|\int_{|y|>1} \frac{f(x-y)}{y}\,dy\Bigr|\le\int_{|y|>1} \frac{C}{1+(x-y)^2}\,dy,
$$
which converges to $0$ as $x\to\infty$.
Comment: [Schwartz functions](https://en.wikipedia.org/wiki/Schwartz_space) do not in general have compact support. (I guess OP means Schwartz functions, and not Schwarz functions, whatever that should be).
Comment: True. I will try to find a proof, perhaps using the result for functions of compact support.


Problems with classification in imbalanced datasets

Question: I often read about the problematic of doing classification in imbalanced datasets and methods to address it. Namely, off-the-shelf classifiers learn to minimize some form of total miss-clasffication cost, and thus have a bias towards the most frequent class in the training set.
My question is: what other serious problems exist in this setting that can not be solved by simply adjusting the thresholding function of the response of the classifier?
Answer: You've made an important observation that many miss by noticing that so-called classifiers like logistic regressions and neural networks return class membership probability values instead of discrete classes.
And I am with you that it is misleading to say that your classifier is really accurate at, say, $98\%$ if you have a $99:1$ class imbalance and could get $99\%$ accuracy by always guessing the majority class.
Take it a step further and directly evaluate the probability values. Two common metrics are log loss and Brier score. I'll give the equations for each of those in the binary case, where $y$ is the $0/1$ vector of observed classes and $\hat y$ is the vector of predicted probabilities of class $1$.
$$
\text{Log Loss}(y, \hat y) = -\dfrac{1}{n}\sum_{i=1}^n\left[
y_i\log(\hat y_i) + (1-y_i)\log(1-\hat y_i)
\right]\\
\text{Brier Score}(y, \hat y) = \dfrac{1}{n}\sum_{i=1}^n\left(
y_i - \hat y_i
\right)^2
$$
By looking at the probability values, we do away with hard classifications and can make decisions based on how bad it is to make wrong classifications. For instance, even in a balanced problem, it might be the case that it is much worse to call a $0$ a $1$ than to call a $1$ a $0$, so we might require extreme evidence to call a case a $1$, say $P(1)>0.9$, in order to keep to a minimum the number of times a $0$ gets called a $1$. This is an example of changing the threshold like you mention in your question, but this has the advantage of being driven by the cost of misclassification, not arbitrary goals about misclassification rate that might be fairly unrelated to actual costs of misclassifications. Further, the cost of misclassification might be different for different subjects. By forcing a discrete choice, you lose the useful information contained in the probabilities.
Frank Harrell has two good blog posts on this topic (1) (2) and often writes about it here on Cross Validated.
Answer: "Namely, off-the-shelf classifiers learn to minimize some form of total miss-clasffication cost, and thus have a bias towards the most frequent class in the training set. ... My question is: what other serious problems exist..."
This is not a problem.  The bias is correct, it is just Bayes rule
$p(\mathcal{C}_+|\vec{x}) = \frac{p(\vec{x}|\mathcal{C}_+)p(\mathcal{C}_+)}{p(\vec{x})}$
Note the probability that a pattern belongs to the minority positive class is proportional to the frequency of positive patterns in the data set (which should be the same as that in operational use).
If it is unacceptable that all patterns are assigned to the majority class, it is just an indication that the misclassification costs are not equal and the threshold on the probability of class membership should be adjusted accordingly.
In most cases, there is no "class imbalance problem", it is just the "cost-sensitive learning problem" in disguise.
Now if the dataset is very small, there can be an undue bias against the minority class (see my answer to this related question), but in that case there generally isn't much you can do about it anyway.


sqlQuery of DocumentDB input bindings with modulation symbol makes function's failure

Question: I using the DocumentDB input bindings on Azure Functions.
Today, I specified a following query as a sqlQuery.
SELECT c.id, c.created_at FROM c
WHERE {epoch} - c.created_at_epoch >= 86400*31
AND (CEILING({epoch}/86400) - CEILING(c.created_at_epoch / 86400)) % 31 = 0

Afterwards, I saw a following error when function is triggered.
2017-07-04T10:31:44.873 Function started (Id=95a2ab7a-8eb8-4568-b314-2c3b04a0eadf)
2017-07-04T10:31:49.544 Function completed (Failure, Id=95a2ab7a-8eb8-4568-b314-2c3b04a0eadf, Duration=4681ms)
2017-07-04T10:31:50.106 Exception while executing function: Functions.Bonus. Microsoft.Azure.WebJobs.Host: The '%' at position 148 does not have a closing '%'.

I want to use a modulation symbol within sqlQuery. What can I?
Best regards.

2017-07-15(JST) Append.
And today, I tried following another query for avoid this issue.
SELECT c.id, c.created_at FROM c
WHERE {epoch} - c.created_at_epoch >= 86400*31 AND
(CEILING({epoch}/86400) - CEILING(c.created_at_epoch / 86400)) -
(31 *
    CEILING(
        (CEILING({epoch}/86400) - CEILING(c.created_at_epoch / 86400))
        / 31
    )
) = 0

Just in case, I tried this query that is specified a epoch = 1499218423 on the Cosmos DB.
SELECT c.id, c.created_at FROM c
WHERE 1499218423 - c.created_at_epoch >= 86400*31 AND
(CEILING(1499218423/86400) - CEILING(c.created_at_epoch / 86400)) -
(31 *
    CEILING(
        (CEILING(1499218423/86400) - CEILING(c.created_at_epoch / 86400))
        / 31
    )
) = 0

That's result is followings.
[
  {
    "id": "70251cbf-44b3-4cd9-991f-81127ad78bca",
    "created_at": "2017-05-11 18:46:16"
  },
  {
    "id": "0fa31de2-4832-49ea-a0c6-b517d64ede85",
    "created_at": "2017-05-11 18:48:22"
  },
  {
    "id": "b9959d15-92e7-41c3-8eff-718c4ab2be6e",
    "created_at": "2017-05-11 19:01:43"
  }
]

It looks fine. Then I specify it as sqlQuery and test with following queue data.
{"epoch":1499218423}

And code of the function is followings.
module.exports = function (context, myQueueItem) {
    context.log(context.bindings.members, myQueueItem);
    context.done();
};

Afetrwards, I saw following results.
2017-07-05T03:00:47.158 Function started (Id=e4d060b5-3ddc-4271-bf91-9f314e7e1148)
2017-07-05T03:00:47.408 [] { epoch: 1499871600 }
2017-07-05T03:00:47.408 Function completed (Success, Id=e4d060b5-3ddc-4271-bf91-9f314e7e1148, Duration=245ms)

It looks differences in results of bindings(as context.bindings.members).
Why appeared this differences?
Related question : Deferences among the Azure CosmosDB Query Explorer's results and the Azure Functions results
Answer:
I want to use a modulation symbol within sqlQuery. What can I?

The modulation symbol(%) in Azure function configuration is used to retrieve values from app settings. For your issue, I suggest you add a item in app setting as following.

After that, you could use %modulationsymbol% instead of % in your query as following.
SELECT c.id, c.created_at FROM c
WHERE {epoch} - c.created_at_epoch >= 86400*31
AND (CEILING({epoch}/86400) - CEILING(c.created_at_epoch / 86400)) %modulationsymbol% 31 = 0

Comment: I tried it, and error is resolved. But differences is appeared among CosmosDB query explorer's results and Azure Functions results. I'm going to create an another question about this deferences. Thank you.
Comment: I created another question about this differences. [Deferences among the Azure CosmosDB Query Explorer's results and the Azure Functions results](https://stackoverflow.com/questions/44903632/sqlquery-of-documentdb-input-bindings-with-modulation-symbol-makes-functions-fa)


Programmatically assign permisions to role

Question: I have a custom module and with hook_permission() I create module's specific permissions. Is there a hook (hook_role_permission) in which I can create a module specific role and assign it's permissions?
I don't want to put these in custom_module.install file because I don't want to reinstall the whole website.
Comment: Please check this link it has a good description http://www.drupal-solutions.com/drupal-7-create-users-and-roles-programmatically
Comment: Thanks. But I'm don't know exactly where should I write that code? In hook_permission or is there any other hook?
Answer: You don't need to re-install the whole website just to make a change to your .install file...you can just implement hook_update_N() instead.
/**
 * Description of the update.
 */
function MYMODULE_update_7100() {
  // Perform some tasks. From the comments it looks like you have the logic you need.

  return t('Tasks completed');
}

After adding that code visit update.php and follow the instructions (or run drush updatedb) to update the database.
The changes will then be applied, without having to reinstall your modules.
This hook is the best place for your code in this situation (in my opinion) as it will only need to be run once. The update system will make sure of that on your behalf, and if you need to make further changes you can just add another update function.
Please make sure you read through the docs fully before giving it a go, there are some caveats that you really should know. Basic stuff but quite important


Integral over boundary vs Integral over entire region (relationship?)

Question: Let ${\bf{x}}\in\mathbb{R}^2$ and $f({\bf{x}}): \mathbb{R}^2 \rightarrow (\epsilon,\infty)$, $\epsilon > 0$, that is, $f({\bf{x}})$ is scalar and positive for all $\bf{x}$. Let $S$ be bounded convex (polygon) subset of $\mathbb{R}^2$ and let $\partial S$ be the boundary of $S$ (so in $\mathbb{R}^2$ we have that $S$ is a non-smooth but piecewise continuous curve). Do I have any relationship between:
$$ \int_{\partial S} f({\bf{x}}) d{\bf{x}}~~~~{\rm{and}}~~~~\int_{S} f({\bf{x}}) d{\bf{x}}$$
Perhaps, can I bound one using other, using the diameter of the polygon? I believe I can say $ \int_{\partial S} f({\bf{x}}) d{\bf{x}} \leq \int_{S} f({\bf{x}}) d{\bf{x}}$ but I am looking for something more tight.
I do not know if this helps, but this problem shows up if I want to evaluate how the mass of a Voronoi cell changes over time, where $S$ is the Voronoi cell and $f$ is the density function.
Answer: The answer is basically: 'no'. There is no a priori relation between
$$
\int_{\partial S} f({\bf{x}}) d{\bf{x}}~~~~{\rm{and}}~~~~\int_{S} f({\bf{x}}) d{\bf{x}}.
$$
These quantities have to be considered completely independent. Asking for an estimate of the value of the first integral given the value of the second (or viceversa) is just as groundless as asking for the value $f(1)$ given the value $f(0)$ for a real function.
Instead, there is a relation between (for example)
$$
\int_{\partial S} f({\bf{x}}) d{\bf{x}}~~~~{\rm{together\; with}}~~~~\int_{S} \nabla f({\bf{x}}) d{\bf{x}}
$$
on one side and
$$\int_{S} f({\bf{x}}) d{\bf{x}} $$
on the other side.
This kind of relations are called "Poincaré inequalities"
Comment: I appreciate your answer a lot. I have been searching for "Poincaré inequalities" but I dont seem to find one that gives me a relationship with the integral over the boundary. Can you help me locate that information? Thank you very much!
Comment: @csystemsguy The point is that you have no definite relation between $\int_{\partial S} f({\bf{x}}) d{\bf{x}}$ and $\int_{S} f({\bf{x}}) d{\bf{x}}$ for scalar and positive functions $f$ (even regular as you want). In fact, you can consider these two integrals completely independent, whatever the form and the dimensions of the polygons are. To link them you need additional information: $\int_{S} \nabla f({\bf{x}}) d{\bf{x}} $ is an instance of the  information you need in order to relate the two integrals.
Answer: Assuming the function $f$ is bounded both below (by $\epsilon$ as specified) and above (by some maximum value $M$ which wasn't specified), the relationship is related to the Isoperimeteric Inequality. In two dimensions, this says that the sets perimeter is larger than its area,
$$
\left(\int_{\partial S} d{\bf x}\right)^2 \geq 4 \pi \int_S d{\bf x}.
$$
Applying the bounds ($f > \epsilon$ and $f < M)$, this becomes,
\begin{align}
\left(\int_{\partial S} f \, d{\bf x}\right)^2  & \geq \epsilon^2 \left(\int_{\partial S} d{\bf x}\right)^2 \\
 & \geq 4 \pi \epsilon^2 \int_S d{\bf x}\\
 & \geq \frac{4 \pi \epsilon^2}{M} \int_S f \, d{\bf x}.
\end{align}
The reverse inequality cannot be established without additional assumptions: an arbitrarily thin rectangle can have a significant perimeter and an arbitrarily small area.
However Voronoi cells are convex and in many cases avoid problematic thinness as long as the Voronoi sites cannot get too close to each other. Let's proceed with two assumptions:

$S$ is convex
There is a constant $c>0$ such that some ball of radius $c\, {\rm diam}(S)$ is contained in $S$.

The second assumption is a requirement on the Voronoi cells that is roughly equivalent to good spacing of Voronoi generators or, equivalently, the aspect ratio of the Voronoi cells is bounded.
With convexity, the perimeter of a set can initially be bounded in terms of the area and diameter of set and then with the second assumption, becomes a bound on the area. The first bound (which seems to go back to Blaschke, W., Konvexe Bereiche gegebener konstanter Breite und kleinsten Inhalts., Math. Ann. 76, 504-513 (1915). ZBL45.0731.04.) says that the unit circle maximizes the perimeter over all convex sets with unit diameter. Scaling by the diameter, this is,
\begin{align}
\left(\int_{\partial S} d{\bf x}\right)^2 & \leq \pi^2 \, {\rm diam} (S)^2\\
 & \leq \frac{\pi}{c^2} \int_S d{\bf x}.
\end{align}
A function $f$ bounded between $\epsilon$ and $M$ can be introduced into these integrals and passed through as before,
\begin{align}
\left(\int_{\partial S} f \, d{\bf x}\right)^2 & \leq \frac{M^2}{\epsilon}\cdot \frac{\pi}{c^2}\int_Sf  \, d {\bf x}.
\end{align}
Comment: Sorry, can you help me understand how you get to $\pi^2 diam(S)^2 \leq \frac{4}{c^2\pi}\int_S dx$. I can easily get to $\pi^2 diam(S)^2 \leq \frac{\pi}{c^2} \int_S dx$ but your bound is more tight.
Comment: Thank you, this answer is very helpful.
Comment: You are right... I mixed something up but have corrected it now.
Comment: Great! Thanks a lot.


Symmetric PDFs in Metropolis-Hastings

Question: My textbook says that a symmetric PDF satisfies
$$f(x|y)=f(y|x).$$
Can anyone explain this? Is it equivalent to $f(x+a)=f(x-a)$?
Comment: I am not sure what you mean by $f(x+a) = f(x-a)$ and exactly what $a$ is here, but I have answered the question about symmetric PDFs.
Answer: I will explain a symmetric PDF by example. Suppose the proposal distribution in the Metropolis-Hastings algorithm is a Normal distribution with variance 1. Then
$$f(x|y) = \text{density of } N(y,1). $$
This proposal distribution is symmetric since $f(x|y) = f(y|x)$. I will demonstrate this by writing the pdf of both.
\begin{align*}
f(x|y) = \dfrac{1}{\sqrt{2\pi}}\exp \left\{-\dfrac{(x - y)^2}{2} \right\}\\
f(y|x) = \dfrac{1}{\sqrt{2\pi}}\exp \left\{-\dfrac{(y - x)^2}{2} \right\}\\
\end{align*}
Thus, you see that the pdfs are the same, and hence we say that the proposal distribution is symmetric.

Symmetric PDFs in Metropolis-Hastings