Invalid conversion from std::size_t* to long unsigned int*

Question: On a raspberry pi - arv7l I'm compiling the following C++ program
#include <iostream>

void fun(unsigned long int* i)
{
    std::cout << *i << std::endl;
}

int main()
{
    std::size_t i = 1;
    fun(&i);
    return 0;
}

For the code above I'm getting the following error:
a.cpp: In function 'int main()':
a.cpp:12:9: error: invalid conversion from 'std::size_t* {aka unsigned int*}' to 'long unsigned int*' [-fpermissive]
     fun(&i);
         ^~
a.cpp:3:6: note:   initializing argument 1 of 'void fun(long unsigned int*)'
 void fun(unsigned long int* i)
      ^~~

I understand that on 32-bit systems size_t is 32 bit and may be different than unsigned long but still this should compile?
With regards to the sizes of the various types:
sizeof(size_t): 4
sizeof(unsigned int): 4
sizeof(unsigned long int): 4

sizeof(size_t*): 4
sizeof(unsigned int*): 4
sizeof(unsigned long int*): 4

System: Linux turtlebot 4.14.79-v7+ #1159 SMP Sun Nov 4 17:50:20 GMT 2018 armv7l GNU/Linux
Compiler: gcc-6.3
Comment: "but still this should compile?" - No, these are pointers to unrelated types.
Answer:
I understand that on 32-bit systems size_t is 32 bit and may be different than unsigned long but still this should compile?

This is not correct.  You are correct that the types have the same size, but size is not what makes a type a type.  For instance we have signed char, unsigned char, and char.  All three have a size of 1, but all three are distinct types named by the standard.
In your case size_t* is a unsigned int* and since that is a different type than a long unsigned int*, you cannot implicitly cast it to one.
Comment: yeah tbh I'd probably drop the bit about the names defining type identity cos that's just gonna confuse peeps
Comment: @LightnessRacesinOrbit Done.  Was on the fence so that convinced me.
Comment: I could feel that :D Love the comparison against `char` types though that's perfect
Answer: Why should it compile? You have an unsigned int (on your system a std::size_t), and you are pretending that it is a long unsigned int.
But it isn't, regardless of size, so it doesn't work.
There is more to types than their width.
Use consistent types for portable code.
Comment: Passing an `unsigned int` to a function expecting an `long unsigned int` is not a problem as the value will be converted without loss.  It's the pointers that are a problem.
Comment: @dbush Implicit conversions are one thing. Aliasing is quite another. As you can see from the question, you can't just take a `A*` and make it a `B*` implicitly (except in some cases). That being said, I'd expect a cast to "work" here, for this platform (but don't do it!)
Comment: That's my point.  Your answer is not talking about pointers but about values.
Comment: @dbush It isn't. Taking a `T1*` instead of a `T2*` is pretending that the `T2` were a `T1` ;)
Answer: A unsigned long int* and a unsigned int* are not the same type, even though the sizes are the same.
There are implicit conversions between integer types, however this does not apply to pointers to integer types which is why you get the error.
You'll need to change either the type of the variable or the type of the function parameter for them to match.
Answer: In C++ types with different size modifiers are different even if same size.
There are systems with sizeof(char) == sizeof(short int) == sizeof (int) == sizeof(long int) ...
Add a std::static_assert to your code to ensure that both types are equal size and than you may call the function like this:
fun(&reinterpret_cast<unsigned long&>(i));

Comment: That aliasing seems harmless on the surface but is actually not allowed and the optimiser could well punish you for it. Best to **use consistent types**.


Como parar de emitir particulas após uns segundos?

Question: Tenho um código simples que spawna partículas quando o player fica parado na trigger. Porém elas não param de ser emitidas e eu gostaria que elas parassem logo após uns segundos. Como posso fazer isso?
if (other.gameObject.tag == "Player" && Input.GetKeyDown(KeyCode.E))
        {
            PlayerManager.health += 1;
            MyParticleEffect.SetActive(true);

        yield WaitForSeconds(5); // wait for 5 seconds
        MyParticleEffect.SetActive(false); // turn the particle system on

            Debug.Log("e key was pressed");
        }

Answer: Primeiro, acho que o "yield" não funciona em um Void, mas sim em um IEnumerator.
Creio que esteja usando o OnTriggerStay. Para isso,a forma fácil seria criar uma variável que conta o tempo e usar Update().
public class scriptest : MonoBehaviour {
   float timer = 0; //variável do tempo.
   public GameObject MyParticleEffect;//GameObject do Efeito

 void Update()
 {
    timer += Time.deltaTime; //Somando o timeDelta, conta-se o tempo.
    if (timer > 5) //Se o tempo for maior do que 5, o GameObject do efeito é desativado.
     {
        MyParticleEffect.SetActive(false);
     }
 }

 void OnTriggerStay(Collider other)
 {
     if (other.gameObject.tag == "Player" && Input.GetKeyDown(KeyCode.E))
     {
        //Aqui vai o PlayerManager.health += 1.
        MyParticleEffect.SetActive(true); //GameObject do efeito é ativado.
        timer = 0; //Tempo é zerado.
     }
 }
}

Veja,também, se não tem algum script impedindo o Efeito de ser desativado.


Any intuition for why eigenvector centrality relates to walks of infinite length?

Question: Some centrality measures can be interpreted in terms of walks.

Degree centrality relates to a walk of length one: The more walks of length one reach a node, the higher this centrality measure.
Betweenness centrality relates to walks along the shortest paths. The higher the number of shortest paths that pass through a node, the higher this centrality measure.
Eigenvector centrality relates to a walk of infinite length according to the Wikipedia entry about centrality measures.

I find this characterization of these centrality measures quite useful but I have difficulties developing an intuition why eigenvector centrality relates to walk of infinite length. Any idea?
Answer: Eigenvector centrality relates to a random walk of infinite length, in which each next node is chosen uniformly at random from the set of neighbours of the current node (in an unweighted network; in a weighted network, the next node is chosen with a probability proportional to the edge weight). The eigenvector centrality of a node is proportional to the frequency with which that node is visited during such a walk (corresponding to the stationary distribution of a Markov chain). IMO, the key attribute of this walk is "random", not "infinite" (a random walk with a long but finite length usually comes pretty close to approximate the eigenvector centrality).


How to convert distances among dots to coordinate?

Question: guys!!
I'm a post doc in chemical engineering department.
During my experiment, I have achieved the distances among the dots.
I can calculate the distance between the dots, and I want to convert that information to the coordinates of each dots.
Also, it is hard to figure out the dimension of coordinate system, yet.
Is there any possible ways to calculate the coordinates?
Or is there any theoretical approaches for this kind of problem?
It would be great for me to get any clues for this problem!!
Thanks!!
Comment: How many dot's do you have? How precise are your measurements and what's your expectation on dimension?

The reason I'm asking is the following example: If you have four dots with distances $(1,1,1,1,\sqrt{2},\sqrt{2})$ they can lie in a square in two dim. If the distances are $(1,1,1,1,1.41,1.42)$ you need a third dimension, or a tolerance on your (measured) inputs.
Comment: Set one "dot" as the origin and estimate.
Comment: do the dots have distance in one particular direction? Is the direction important or not?
Comment: How do you calculate the distance between dots if you don't know the coordinates?

You may want to have a look at this: https://en.wikipedia.org/wiki/Nonlinear_dimensionality_reduction
Comment: The number of dots is around 200. And I just can measure the distance among them. I'm not sure that those dots can make coordinate system in 2 or 3 dim.
Comment: The distance has no direction but value. The direction itself may not important. I just hope to make coordinate of each dots in low dimension, and make a mapping of dots.
Answer: If the representation space is 2 dimensional (see "remark about the dimensionality" at the end of this answer), here is a direction to attack the problem.
Fix 2 points $F_1$ and $F_2$ (sufficiently far apart, even at maximal distance in order to limitate the influence of measures' imprecision).
Let us consider that line $F_1F_2$ defines an $x$-axis and that the $y$ axis is defined by the perpendicular bissector line of $F_1F_2$. Divide all distances by $\tfrac12 F_1F_2$ making the normalized distance $F_1F_2$ equal to $2$ ; thus  the coordiantes of $F_1,F_2$ can be taken  resp. as $(-1,0)$ and $(1,0)$.
Consider (see graphics below) the following families of (orthogonal) curves that, each one, allows to cover the plane

ellipses $\frak{E}_u$: set of points M such that $MF_1+MF_2=u$.
hyperbolas $\frak{H}_v$ with 2 branches, $\begin{cases}\text{the set of points M such that} \ MF_1-MF_2=v, v > 0 \\ \text{the set of points M such that} \ MF_1-MF_2=v, v<0\end{cases}. \ \ \ $ The case $v=0$, characterizing the perpendicular bissector of $F_1F_2$, can be considered as a degenerated case of this family.

Ellipses are represented in red (from $u=2$ to  to $u=3$ ; the case $u=2$  is line segment $F_1F_2$, i.e., a degenerate ellipse), hyperbolas in blue (from $v=-2,-1.8, -1.6, ... 2$ (the 2 cases $v=-2$ and $v=2$ being also degenerate cases reduced to half lines). An important feature of these two families of curves is that they share a same set of foci, i.e., points $F_1$ and $F_2$.
Being given a point $P$ of the given set of points, as you know distances $PF_1$ and $PF_2$, you are able to compute their sum and their difference, yielding a value of $u, u \geq 0$ and a value of $v, v\in \mathbb{R}$
This pair of values $(u,v)$ characterizes $2$ possible points, symmetrical with respect to $x$ axis (it is the fundamental "ambiguity" of your issue), thus $2$ possible pairs of cartesian coordinates (see computation below).
A second step is thus needed to "disambiguate" the $y$ coordinate. I have not done it but I have some tracks. One of these tracks is to operate in the same way with $2$ other points $F'_1$ and $F'_2$.

Computation of $(x,\pm y)$ coordinates out of a $(u,v)$ description:
$$\tag{1}\begin{cases} MF_1+MF_2=u \ \iff \ \sqrt{(x+1)^2+y^2} +\sqrt{(x-1)^2+y^2}=u & \ \  (a)\\ MF_1-MF_2=v \iff \ \sqrt{(x+1)^2+y^2} -\sqrt{(x-1)^2+y^2}=v& \ \
 (b) \end{cases}.$$
Squaring and adding, one gets $4x^2+4y^2+4=u^2+v^2$, thus $x^2+y^2=r^2$ with $r:=\sqrt{\tfrac{u^2+v^2}{4}-1}$, giving
$$\tag{2}x=r \cos(\alpha), \ \ y=r \sin(\alpha)$$ for certain values of $\alpha$ (in general 2 values)  that will be found by plugging the expressions given by (2) into (1)(a) for example.
Remark about the dimensionality of the representation space: have a look at "Cayley Menger determinant" (https://en.wikipedia.org/wiki/Distance_geometry_problem) which is a condition
$$det \left( \begin{array}{ccccc}0&AB^2&AC^2&AD^2&1\\
AB^2&0&BC^2&BD^2&1\\
AC^2&BC^2&0&CD^2&1\\
AD^2&BD^2&CD^2&0&1\\
1&1&1&1&0\end{array}\right)=0,$$
that must be fullfilled by any set of 4 points $A,B,C,D$ if the representation space is $\mathbb{R}^2$. You can use it at first as a consistency test for your set of distances' data. If only few sets of 4 points give a LHS significantly different from $0$, you can incriminate errors in measurements, whereas, if a vast amoint of them differ from $0$, you can ask yourself if the real space of representation is a $\mathbb{R^n}$, with $n>2$ ; in this case, test with a "larger" Cayley-Menger determinant involving subsets of $n+2$ points if the representation space is $\mathbb{R}^n.$

Take a look at the nice figure(s) in (https://theinnerframe.wordpress.com/tag/triply-orthogonal-surfaces/).
Comment: Thanks, Jean Marie. I will try to makw solution following your comment.


Como concatenar multiplas Strings em Python?

Question: O seguinte método c.filtraNome(nome) efetua uma consulta no banco (sqlite3), entretanto, não sei como posso agrupar cada campo e retornar a consulta já formatada da seguinte maneira:
Nome:  Fulano Silvia
Idade:  19
CPF:  00000000000
Email:  firstname.lastname@example.com
Celular:  1131345678
Cidade:  Nova Vila
UF:  MT
Data do Cadastro:  2015-08-25

Tentei concatenar as strings com o operador + e com o método ''.join('String') mas não obtive sucesso em nenhum deles.
Rotina que efetua a consulta:
def filtraNome(self,nome):
        self.db.cursor.execute(""" SELECT * FROM clientes WHERE nome like ? ; """,(['%' + nome + '%']))
        for campo in self.db.cursor.fetchall():
            self.dados = 'Nome: '.join(campo[1]).join('Idade: '.join(campo[2])).join('CPF: '.join(campo[3])).join('Email: '.join(campo[4])).join('Celular: '.join(campo[5])).join('Cidade: '.join(campo[6])).join('UF: '.join(campo[7])).join('Data do cadastro: '.join(campo[8])) #Gera um erro nesta linha.

        return self.dados

O erro que esta sendo gerado ao usar o método join():
self.dados = 'Nome: '.join(campo[1]).join('Idade: '.join(campo[2])).join('CPF: '.join(campo[3])).join('Email: '.join(campo[4])).join('Celular: '.join(campo[5])).join('Cidade: '.join(campo[6])).join('UF: '.join(campo[7])).join('Data do cadastro: '.join(campo[8]))
TypeError: can only join an iterable

Rotina que chama o método da classe ClienteDB:
if __name__ == '__main__':
    c = ClienteDB()
    if c.cria_tabela():
        print("Tabela %s criada com sucesso.", c.tb_nome)
    #c.inserir_registro()
    #c.listar_todos()
    nome = raw_input("Informe um nome para pesquisa: ")
    print(c.filtraNome(nome))

Como eu posso concatenar os campos retornados da consulta no Python?
Comment: qual erro é gerado na linha ?
Comment: Este erro: **TypeError: can only join an iterable**
Comment: o join só funciona com arrays ou "coisas que podem ser iteradas"... com o '+' dá algum erro ?
Comment: Sim com mais tambem retorna um erro, no ultimo registro `"Data: " + campo[8]`, os dois estão retornando erro.
Comment: provavelmente tá dando um "index out of range"... estou vendo que você começou a pegar os campos do array a partir do indice 1... mas o array começa em 0.. ta certo isso ?
Comment: O índice zero e o **id** eu não exibo ele.
Comment: qual o erro que está dando entao ? Faça o seguinte... para evitarmos uma "conversa" nos comentários, edite sua pergunta colocando mais detalhes, mostrando quais as abordagens que você usou e quais foram os erros quando usou elas.
Comment: @DenerCarvalho, tenta concatenar usando `Nome: + str(campo[1])...` e me avisa do resultado pra eu postar como resposta. Eu realmente acho que esse é o problema.
Answer: Tu deves converter os teus itens dentro de campo[indice] para string antes de tentar concatená-los.
Um exemplo simples e que resolveria o problema (embora não seja recomendado), é usar:
'Nome: ' + str(campo[1])

No entanto, Python tem várias formas para formatação de strings. Você pode ler mais sobre isso aqui, aqui e aqui.
Alguns exemplos de formatação de strings
Você pode usar o método str.format() para solucionar seu problema, porque ele converte automaticamente para string os dados que são passados para ele.
Um método básico de uso, seria:
'Nome: {} Idade: {} CPF: {}'.format(campo[1], campo[2], campo[3])

As chaves são substituídos pelos objetos passados para o método str.format(), respeitando a ordem dos parâmetros.
Quando se tem muitos campos para concatenar, pode ser interessante "numerar" estes parâmetros, como no exemplo abaixo:
'Nome: {0} Idade: {1} CPF: {2}'.format(campo[1], campo[2], campo[3])

Aqui {0} será substituído pelo primeiro parâmetro do método e assim sucessivamente (lembrando que você não precisa colocar os campos de formatação em ordem.
Outra forma interessante de usar este método, principalmente quando se tem muitos campos para formatar, é usar os parâmetros com nomes ao invés de números, como por exemplo:
'Nome: {nome} Idade: {idade} CPF: {cpf}'.format(nome = campo[1], idade = campo[2], cpf = campo[3])

Comment: Obrigado pela ajuda, desta maneira funcionou, consegui separar  os valores e agrupa-los.
Answer: Python tem há muito tempo vários esquemas de formatar strings, com interpolação de dados, de forma que dão ao usuário bastante controle e separação do que é dado e do que é código.
Isso é certametne o que você quer fazer - melhor que concatenar: ter uma strign grande, com o layout geral de como você quer sua saída, e interpolar os dados lidos do banco de dados.
Atualmente (Python 2.7. 3.4) a forma mais recomendada de se fazer isso é com o método format das strings. VOcê pode até usar uma string de multiplas linhas - as delimitadas por aspas triplas (""") para criar seu layout, deixando os slots para serme preenchidos pelos campos com os marcadores { }. Como é uma strign longa, o melhor é usar a opção que deixa você dar nome ao compo que vai em cada marcados ({campo}).
No seu caso, isso pode ser algo do tipo:
self.dados = """\
Nome:  {nome}
Idade:  {idade}
CPF: {cpf}
Email:  {email}
Celular:  {celular}
Cidade:  {cidade}
UF:  {uf}
Data do Cadastro:  {data}""".format(nome=campo[1],idade=campo[2],...,uf=campo[...])

O .format converte automáticamente os dados para sua representação como string - se vocẽ não desejar isso (por exeplo, quiser formatar um campo com números decimais com um número específico de casas), o método tem uma minilinguagem de formatação, - deixando você especificar o tipo, e números de casas decimais após colocar : depois do nome do campo. Ex. : {total:06.2f} diria que o "total" seria um campo numérico com 6 digitos, preenchidos a esquerda com "0 e duas casa após o ponto decimal. O venerável Luciano Ramalho cirou um cartão de cola para o Format que está online aqui:
http://python.pro.br/material/cartao-format.pdf  -  A docuemtnação oficial está aqui: https://docs.python.org/2/library/string.html#format-specification-mini-language
Ah, se você verificar a documentação do conector do banco de dados, vai ver que existe um "dictcursor" que traz as colunas do seu select como um dicionário, em vez de ordenadas em sequência. Se você mudar seu código para usar dict cursor, poderá chamar o format direto com a linha do cursor da query, algo como """...""".format(**campos)
Comment: Obrigado pela explicação!


TwinCAT HMI initialization does not work - missing screen

Question: I am trying to get a hang of TwinCAT 3 HMI and have been looking at the tutorials on the net. For some reason, however, I can't even duplicate what is done in those. Right in the beginning, when creating the HMI project, the window in the tutorials looks like this:

But when I try to replicate this on my PC, I get this:

I don't have the grey window with the BECKHOFF text, and I can't drag items from the toolbox to the GUI workspace. The project is stuck.
I don't understand what the problem here is and I couldn't find a reference to a similar problem. Is there a setting to create this by default, and/or a command to add a window to the workspace?
Any help is greatly appreciated!
Comment: What version of VS are you using? I would assume that might be the cause for your problem:
`Min version VS2017 15.9 with ASP.NET`
`Min version VS2019 16.4`
`TC XAE shell (Should work, i created empty project and works fine)`

If you have correct version of the IDE I would suggest to reinstall the tool since it is probably an installation issue and should work out the box.
Comment: Also, if you rebuild solution, if there are any errors in the generated HTML code, it should give you the errors (sometimes the auto generated code from the designer could get scuffed, from my experience).
Comment: I am using the default editor installed by TC 4024.47 . Seems to be ASP .NET 2017, ver. 15.9.xxxxx

I think I will try to re-install TC and see what happens. I have been installing and uninstalling various Visual Studio products lately to test them. Maybe they have messed up something.
Comment: There is a difference between TC XAE shell and Visual Studio. Can you show is the entire window? I am not sure if I would go as far to install any packages to XAE shell since it is a stripped down version by Beckhoff. I my self prefer using Visual Studio 2019 and install TwinCAT there.
Comment: I am getting help from Beckhoff support now. It seems that TE2000 and the internal web browser doesn't install correctly on my machine, hence the problem.

Not sure yet what causes the problem, but it could be some PC safety restrictions imposed and installed by the organization I work for.
Answer: For anyone who happens to come across this problem, try the following steps:
First, close all open instances of XAE shell and visual studio 2019.
Next, assuming that TE2000 was already installed, run the TE2000 installer again. Select for "Repair".
Check for both XAE shell and VS2019 as options and run until completion.
Hopefully this resolves the issue.
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Nginx 404 rewrite issue

Question: I'm trying to grab variables between slashes and pass them to my management script with the following rewrite line in Nginx:
<code>rewrite ^/(.*)/(.*)/(.*)/(.*)/(.*)/(.*)$ /index.php?p1=$1&p2=$2&p3=$3&p4=$4&p5=$5&p6=$6;
</code>
If I request the page with less than 6 variables (eg: /var1/var2/var3/var4/var5/) it 404s.
Is it possible to use this with less than 6 variables? (I will need the full 6 variables in different parts of my web application though)
Running CentOS 6 in OpenVZ with Nginx 1.4.1-1.el6 64bit + PHP-FPM.
Thanks in advance.
Answer: If you don't have exactly six items between slashes, then this pattern won't match, and you'll get a 404.
You can make five new rewrite rules containing one through five variables, respectively, (or someone who's better at regex than I am might suggest a single rule to cover all six cases, but that's above most people's heads) or just handle this in your application instead.

Nginx 404 rewrite issue


How do I mark a database query with a tag?

Question: How do I mark a database query with a tag so that I may alter it via hook_query_alter? I get the concept, but does anyone know what the syntax is? A working example would be helpful. Thanks.
Answer: In case you're struggling to find the documentation, the class is called SelectQuery, and you're looking for the addTag function.
$query = db_select('table', 't')->fields('t')->addTag('my_tag');

Then in your query alter:
function MYMODULE_query_alter(QueryAlterableInterface $query) {
  if ($query->hasTag('my_tag')) {
    // Do something...
  }
}

Comment: Note, if the query has a tag, you can also use `hook_query_TAG_alter` e.g: `hook_query_my_tag_alter(QueryAlterableInterface $query){}` similar to `hook_form_FORM_ID_alter` for forms.


Detect application close/minimalize

Question: first - sorry for my English.
I just created Android app. It contains several activities and in the background of this application music is played. When user go out from app in some way (by click "back" button, home button, or in other way), then I need to stop play the music. The problem is to handle this moment. I don't know how.
Please help me,
CD
Comment: please provide some code. especially where the music starts.
Answer: You can check when your application is in background by using :
1.
   public boolean isApplicationSentToBackground(final Context context) {
    try {
        ActivityManager am = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (!topActivity.getPackageName().equals(
                    context.getPackageName())) {
                     return true;
            }
        }
    } catch (SecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return false;
}

Then in your onPause you can call this method ,and can stop the sound.
And in onRestart() you can start the sound.
2.You can override OnBackPressed() method you can stop the sound here in this method
3.Also,You can use keyEvent
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
    // TODO Auto-generated method stub

    if (keyCode == KeyEvent.KEYCODE_BACK) {
             //Your Code here
             // You can stop the sound here also
    }
    return super.onKeyDown(keyCode, event);
}

Answer: You should stop playing music onPause(). Start playing the music onResume(). But obay the guidlines stated by google: http://android-developers.blogspot.com/2011/11/making-android-games-that-play-nice.html
Answer: As per my understanding you want to do something like this Question
If so then use below code..here level is object of mediaplayer.
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
  super.onBackPressed();

  if (level != null) {
    if (level.isPlaying()) {

        level.stop();

    }
    level.release();
    level = null;
  }
}

@Override
protected void onPause() {
 // TODO Auto-generated method stub
  super.onPause();

  if (level != null) {
    if (level.isPlaying()) {

        level.pause();

    }
  }
 }

Answer: There is no way in Android to detect when an app goes into the background. There is only callbacks for when an Activity goes to the background.
An example solution could be playing the music using a Service and in every Activity's onPause and onResume methods', inform the Service to pause/resume the music.

Detect application close/minimalize


How to configure the Nekohtml html parser to turn  into

Question: I'm evaluating the Nekothml parser among other Java HTML parsers, and I'm trying to make it replace all my
 with
 elements. Can this be done using the Nekohtml API?
Any feedback is appreciated.
Thanks.
Answer: The nekohtml parser is a parser. It produces a DOM tree or SAX events, all in memory, not text. If you have configured it properly, it will read the html
 as if it were an empty XML element, and any XML serialization will them produce
.


Access restriction on class due to restriction on required library

Question: I get this error message in Eclipse:
<code>Access restriction: The type DirectoryWalker is not accessible
due to restriction on required library
/Library/Java/Extensions/commons-io-1.4.jar
</code>
what does this mean? There's this other SO question on the same topic but it doesn't seem to apply in this case. I'm not creating a new java class, I'm trying to use one.
Comment: Um. I noted the similarity myself 5+ years ago, but this is slightly different. At least I thought it was at the time. But it was 5 years ago.
Comment: possible duplicate of [Access restriction on class due to restriction on required library rt.jar?](http://stackoverflow.com/questions/860187/access-restriction-on-class-due-to-restriction-on-required-library-rt-jar)
Answer: go to java build path and under Library tab, remove JRE System Library. Then again Add Library --> JRE System Library
Worked for me
Comment: Nice find. This should definitely be best answer.
Comment: Absurd. Had problems with JavaFX getting "access restrictions", and this trick fixed it! Thanks!
Comment: works for me too, now how do i do this magic in my maven POM file?
Comment: I had this error come up for trying to access JavaFX (jfxrt.jar) for the first time (HelloWorld tutorial for JavaFX). Small additional note: when you delete the jre system library, be sure and exit the "Build Configuration" area after doing so. Then, when you return and add it back in, the errors go away. Bizare bug and I have no explanation as to what is going on.
Answer: This is my least-favorite error, I've run into it a few times, and the "restriction on required library" is just dull enough to leave you scratching your head. However, it's easy to fix.
The quickest way (I'm using Helios) is to go to Window->Preferences->Java->Compiler->Errors/Warnings, find and open the "Deprecated and Restricted API" bullet, and set Forbidden and Discouraged Reference to something other than Error.
"Warning" is usually best, as something out there in Java land is triggering this and you probably want a footnote on it. @SuppressWarnings and its cousins, 98% of the time, have the same effect on a programmer's personal and social logic as, say, an ether binge might. But that's just my humble analysis.
Best of luck!
Answer: At a guess another library you are using also requires Apache Commons I/O, but a different version. Having a piece of code (transitively) have access to two versions of the same packages is a little tricky. You can probably arrange it so your code and the other library use the same version. It's all much easier with CLASSPATH! :)
Comment: is there a better well-known place to put .jar files that won't be automatically "sucked in"?
Comment: (removing everything from my classpath & adding specific libs to my Eclipse build path solved it, thanks.)
Answer: For what it's worth, I had this error recently too (different library).
My IDE (MyEclipse) references a certain library as part of the overall project classpath, but I also had a copy of the relevant JAR in my machine's Java extensions folder.
The resulting clash gave the (unhelpful) error that you've experienced. So for anyone else hitting this error, you might want to consider your classpaths too.
Answer: Project build path settings -> Libraries tab -> select JRE System Library -> Edit button -> change from Execution Environment radio tab which says J2SE 1.x (jdk1.6.0_21) to Workspace default JRE (jdk1.6.0_21) [Collected]
This is the best solution for sure!
Comment: How does this help answer the OP's question?
Comment: I don't know, I asked it over 4 years ago.
Answer: I had the same error the way I fixed was setting the default workspace JRE to the same as the project, I had JRE6 for the workspace and JRE7 for the project setting both to JRE7 fixed the problem
Answer: If you are using m2eclipse, I find "Update Project Configuration" fixes it.
Right-click the project, select Maven > Update Project Configuration and give it a few seconds.
Answer: In my case, I was able to solve this by unticking the folder attribute 'Read-only' in the Properties of the project folder.
Then, I re-configured Build path of the project, then Clean.
It had solved the error.
Answer: For those looking why Eclipse can build the project, but Maven can't, check if you have JUnit as a Library, or as a plugin dependency. If it is added as a library, Maven will not be able to pick it up and throw many access restriction (type xyz is not API).


$(\mathbb R^2,+)$ as vector space over $\mathbb R$

Question: It is not hard to see that $(\mathbb R^2,+)$ with this product

$
 {r\cdot(x,y)=(rx,ry) }
$

is vector space over field $\mathbb R$.
I'm looking  for another product that $(\mathbb R^2,+)$ is vector space over $\mathbb R$. I know
$n*(x,y)=\underbrace{(x,y)\oplus (x,y) \oplus \cdots \oplus (x,y)}_n=(nx,ny)$ but I have no idea for arbitrary element of $\mathbb R$.
Any Suggestion.
Thanks
Comment: You are trying to find other definitions for scalar multiplications?
Comment: Aren't the two products equivalent, at least for natural $n$?
Comment: @AsafKaragila yes I'm trying find another definitions for scalar multiplications
Comment: You point out that $n\cdot (x,y) = (n\cdot x, n\cdot y)$ for $n\in \Bbb N$.  It's worth pointing out that you can extend this argument to show that $q\cdot (x,y) = (q\cdot x, q\cdot y)$ for $q\in \Bbb Q$.  And, if you have just a bit more structure (like say, considering inner product space structures of $(\Bbb R^2,+)$ over $\Bbb R$), you can extend the argument further to any $r\in \Bbb R$.
Answer: If you are allowed to use the axiom of choice, then the abelian groups $(\mathbb R, +), (\mathbb R^2, +), (\mathbb R^3,+), \ldots$ are isomorphic. In fact they are all isomorphic to a direct sum of continuum-many copies of $(\mathbb Q,+)$.
So giving a vector space structure to any of them is the same thing. In particular, we know how to give $(\mathbb R^3,+)$ a structure of $\mathbb R$-vector space which is of dimension $3$, thus by transporting it to $\mathbb R^2$, we can give a vector space structure to $\mathbb R^2$ making it into a 3-dimensional $\mathbb R$-vector space (and similarly for any dimension you wish, as long as it's not more than the continuum cardinality).
In fact, even without the axiom of choice, giving a finite dimensional $\mathbb R$-vector space structure to any abelian group $G$ is the same as finding a group isomorphism from $G$ to $\mathbb R^n$ and transporting the natural vector space structure of $\mathbb R^n$ back to $G$. So the real question is how to find those group isomorphisms.
Sadly, I don't think it is possible to find any nontrivial one without the axiom of choice, so all the nontrivial vector space structure you can put on $\mathbb R^2$ need you to use it, and are not constructive.
Comment: "not too big"=cardinality at most that of the continuum?
Comment: @ Managu : yes, I wasn't sure so I needed to check that a direct sum of $\kappa$-many direct sums of $\kappa'$-many copies of $\mathbb Q$ is a direct sum of max $(\kappa,\kappa')$-many copies, and of cardinal max $(\kappa,\kappa',\aleph_0)$ as a result.


CAGradientLayer not changing the background color

Question: I want to create a gradient as a background color for my UIView. I wrote this code
gradient.colors = [UIColor.blue,UIColor.yellow]
        gradient.locations = [0.0 , 1.0]
        gradient.startPoint = CGPoint(x: 0.0, y: 1.0)
        gradient.endPoint = CGPoint(x: 1.0, y: 1.0)
        gradient.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.size.width, height: self.view.frame.size.height)

self.view.layer.insertSublayer(gradient, at: 0)

but the view still the same set on the Interface Builde. If I add this line before the code
self.view.backgroundColor = UIColor.clear

the background color changes to white
Answer:         let gradient: CAGradientLayer = CAGradientLayer()

        gradient.colors = [UIColor.blue.cgColor, UIColor.yellow.cgColor]
        gradient.locations = [0.0 , 1.0]
        gradient.startPoint = CGPoint(x: 0.0, y: 1.0)
        gradient.endPoint = CGPoint(x: 1.0, y: 1.0)
        gradient.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.size.width, height: self.view.frame.size.height)

        self.view.layer.insertSublayer(gradient, at: 0)

try this code. It works for me swift 3
Comment: okay, glad it fixed your issue :)
Can you please upvote my answer as well ?
Comment: @cole - for future reference, when you post an answer, try to include the *why* - not just "here, this code works".
Comment: Okay, thanks for your feedback. Will keep in mind next time


Angularjs performance issues in $apply, but bindings are fast

Question: I have a medium sized angular app which uses angular-1.2.10 and ui-router-0.2.8. When I transition to  a particular state I am getting frame rate issues on the animation regardless of if I am using $animate on a ng-show or manually animating it.
When I dig into the profiler I can see that the $apply after the XHR is taking up to 200ms. Which I am presuming to be the cause of the lag. When I remove the code in the state I am going to, this problem goes as expected.

There is no large ng-repeat, and the bindings are fast:

This is leaving me a bit stuck as I can't see where the issue is originating from. If anyone can see something to point me in the right direction that would be great.
UPDATE
I have done into incoginto mode and run the same tests, with the $digest counter. The $digest runs 40 times and produces the following.
Lots of things seem to take a long time(30ms+) but I still can't find a cause.
UPDATE
looking at the timeline there seems to be a lot of DOMSubTreeModified.
Comment: So what is going on in the success-handler for that XHR call? It's pretty difficult to guess what the problem is just from looking at the profiler.
Comment: How much is the DOM changing? How many $digest loops are triggered?
Comment: Is their a way to count the $digest loops?
Comment: Is Batarang enabled when you are running the profiling? If so, it shouldn't be. It can slow things down significantly as it has to add code to collect its metrics.
Comment: To count $digest loops you can just do
var count = 0;
$scope.$watch(function () {
  console.log(count++)
})
Comment: The problem occurs regardless of Batarang.
Comment: Hmm, 33 times $digest runs on the state change.
Comment: Presuming this is the issue, is there a general way to reduce the number of times I enter the $digest?
Answer: Angular uses $digest cycles to see if anything needs updating.  The pure fact that you've counted a lot is probably just another symptom of potential optimization.  The true problem lies in the time it is taking, and the processing bottleneck since it's slowing down animations.  So there are a couple of things to try:

Make sure you are not deep-watching anything, which means you shouldn't be passing 'true' for objectEquality.  This process is more intensive and uses more memory as well.
Use isolate scope if directives are involved - if you can.  Having an isolate scope will reduce the chatter of $digests in contrast to an inherited scope, since it will re-digest all shared scopes whenever the parent-controller changes.
Try replacing $watch statements with an event handler if they are rendered in the DOM.  The reason for this is you can reduce the number of times the DOM is re-rendered by $broadcasting an event once the data has been processed (at the end of the XHR call) instead of it re-rendering each time you modify a property.
Can you animate via CSS using hardware-accelerated attributes to smooth it out?
Comment: $promises wouldn't change #3 necessarily.  Mileage may vary of course, but the idea is that if you know programmatically when you are done updating an object it may make more sense to notify listeners at that point rather than rely on them watching and updating as they detect changes.  Remember that bound template expressions are also $watch expressions behind the scenes.  You sound familiar with it already, but this article is a good explanation of that http://angular-tips.com/blog/2013/08/watch-how-the-apply-runs-a-digest/
Comment: Thanks for the suggestions. Point 1 & 4 I have already done with no success so far. I am in the process of trying point 2. With Point 3 though, I use promises to give the scope the result of the XHR, does this apply to your point about the $watches? e.g. $scope.model =  modelService.fetch($stateParams.id).$object;
Comment: Using baratang I can see the bindings are quick though. And not too many of them either. Doesn't this say that the $watches are not the issue and it might be the shear number of $digests? Does anyone have any figures on how many $digests I should expect on page load with a few XHRs?
Answer: Multiple $digests means you have cascading model changes, where changing a triggers a $watch('a') that in turn changes b, which triggers another digest that might trigger a $watch('c'), which triggers another digest that might (heaven forbid) trigger a $watch('a').
That cascade can take a long time even if each individual $watch evaluation is fast.  If you can do all of your changes in one go without sending them propogating between watches you'll cut down your digest count.
Comment: Is there a way to find out what caused the $digest? I don't think I have many cascades. I have a service which I used in 2 controllers, which would update itself via ajax in this case.
Comment: I also have a global controller, not sure if this would contribute to the problem?
Answer: It's hard to help without the code and bindings in markup. If you have parts of UI which are read only and it doesn't depend on multiple digest cycles, try using bindonce: https://github.com/Pasvaz/bindonce. It might help you reduce the number of watchers and unexpected digest cycles.


how to make Jquery menu sticky

Question: I found some menu code which is very simple and works nicely from just jquery without plugins.
What I would like to do is to make it sticky so that when a new page is linked to, that page expands the menu (if necessary) down to the linked item and highlights that item as active if the current window.location matches the  tag href.
I've been wading through Dom console looking but I figure there must be a simpler jquery solution if I'm lucky.  any suggestions on how to achieve this much appreciated.
Thanks
    $(document).ready(function() {
        $('#menu ul').hide();

  /* Note the following three lines added as working solution to original question. */
  /* works for fully qualified url: i.e. http://www.mydomain.com/mypage.ext         */
  /* also note that addClass('current') requires .current class in your css          */

        var currentLink = $("a[href='" + location.href + "']");
        currentLink.parents("ul:hidden").slideDown("normal");
        currentLink.filter('a:first').addClass('current');

  /* end of solution fix                                                             */

        $('#menu li a').click(
         function() {
           var openMe = $(this).next();
           var mySiblings = $(this).parent().siblings().find('ul');
           if (openMe.is(':visible')) {
               openMe.slideUp('normal');
           } else {
              mySiblings.slideUp('normal');
              openMe.slideDown('normal');
           }
       });
    });

menu is as follows:

1

2

3

3-1

3-1-1

3-1-2

3-1-3

3-2

3-2-1

3-2-2

4

5

5-1

5-2

5-3

6

6-1

6-2

6-3

7

8

8-1

8-2

8-3

9

Comment: I think you can use `window.location.pathname` to identify the current page, then it's a matter of parsing the path to call `slideDown()` on the appropriate `ul`'s. Can you give us a hint about how your page URL's look so we can deliver a more specific answer?
Comment: links will either be absolute or just relative. I can create either from php. I can also create a class for current page so I guess its just the expansion to current item that I'm looking for but it would be more elegant to do it all in Jquery.
Answer: Here's the bullet-proof way to find links with matching urls:
var currentLink = $("a").filter(function() {
    return this.href == location.href;
});

If you always use app relative URLs for your hrefs (eg href="/abc/123.htm"), you can use the attribute selector:
var appRelativeUrl = location.pathname + location.search + location.hash;
var currentLink = $("a[href='" + appRelativeUrl + "']");

If you always use absolute URLs for your hrefs (eg href="http://mysite.com/abc/123.htm"), you can also use the attribute selector:
var currentLink = $("a[href='" + location.href + "']");

But, if you use relative urls in your HTML, use the first technique using .filter().
Then, to expand the menu, find all the hidden parent
 elements and slide them down.  After the parents are displayed, if you want to expand the link's submenu, issue a click on the link:
currentLink.parents("ul:hidden").slideDown("normal", function() {
    currentLink.click();
});

Demo here
Demo code
Comment: Thanks, I think this puts me on the right track. The bit which says "find all the parent  elements" is my next worry. What would be the construct to loop through each menu element so that I can find them? I'm new to Jquery but not to programing.
Comment: @RobC - In the code snippet at the end of my answer, notice the `currentLink.parents("ul:hidden")`. This returns all the ancestor elements of `currentLink` that are hidden `` elements.
Comment: @RobC - I've added working demo links to the end of my answer
Comment: You're a star. I had seen another script that uses hash for this purpose but it was massively mor complex than this simple and elegant solution.
Thanks again...
Comment: Problem!  Auto expand works nicely using location.href and not hash. But for some reason I can't fathom, no links from the menu work. It's as though they have all been disabled somehow.
Comment: @RobC - yes, `e.preventDefault()` is doing that.  Remove that line and the links will work.
Comment: I'm learning fast(ish). I modded the original code with my now working solution and another tweak for highlighting. Many thanks fo your help. See code in my original post.
Answer: This is typically handled server-side by adding the appropriate class names to the current menu items when the page is served so they're visible.
Comment: I can make them either full url or relative but they all appear as being served from doamin root so currently either http://www.mydomain.com/mypage.htm or just mypage.htm

how to make Jquery menu sticky


Collation conflict ERROR ,Set collation for stored procedure as database default

Question: How can I set for COLLATION for stored procedure as Database default rather than individual column of tables in that procedure .
Cannot resolve the collation conflict between "SQL_Latin1_General_Pref_CP1_CI_AS" and "Latin1_General_CI_AS" in the equal to operation

I am getting collation conflict error as database server collation is different from database collation. The procedure is huge and I don't know on which table column conflict is occuring.
Is it even possible to assign collation for stored procedure such that all columns in that procedure have same collation?
Comment: Be careful when using temp tables, you want them to have the same collation as the database you are working. Temp tables use the database's server default collation. When creating a temp table explicitly set the collation. CREATE TABLE #TestTempTab
   (PrimaryKey int PRIMARY KEY,
    Col1 nchar COLLATE Estonian_CS_AS
   ).  See http://msdn.microsoft.com/en-us/library/ms190920(v=sql.100).aspx
Comment: I don't think comments like that are going to help your cause. I also don't believe you'd be able to do it on a connection wide basis. I think you best bet is to either run queries on the system tables to try and find out which columns contain that collation, and use those query results to see if you can see any that are seem like they might be used in your stored proc.
Comment: sorry i have deleted that comment
Comment: No probs. Try something like the following to see if it narrows down your issue; SELECT TABLE_NAME, COLUMN_NAME  FROM INFORMATION_SCHEMA.COLUMNS WHERE COLLATION_NAME = 'SQL_Latin1_General_Pref_CP1_CI_AS'
Comment: @Daniel Cabral That was some really crucial info you provided me , i will be careful with temp tables now..Thanks a lot sir..
Answer: Firstly, collation is about how the textual data is stored within a table and is not at a stored procedure level.
Collation issues occur when textual data is compared from sources where the text collatation is not stored the same. (I am not talking about the data type of text, just string data)

Check the TSQL where clauses or table joins, this is the most common places where text compares occur. You can collate to the database default by using the collate function next to the compare area. For example
SELECT
c.CustomerID
FROM
dbo.Customer c
INNER JOIN dbo.CustomerLog cl on c.CustomerName = cl.LogEntry collate
database_default

Depending on your circumstance this might not be possible but I always follows these rules.

- Choose the correct server default collation at install so the tempdb is created under the collation, when you create temp tables, these are created in the tempdb

- when creating tables do not specifiy the collation unless you have specific cause to


Help Interpreting a Problem Concerning the Union of Connected Sets

Question: I have a problem where I am to prove that the union of connected sets is also connected, but the notation and set up is confusing me slightly.
Suppose $U_a$ is connected for all $a \in I$ where $I$ is an index set. Also, for all $a < b$ we have $U_a \subseteq U_b$. We are to prove that $$\bigcup_{a \in I} U_a$$ is also connected.
I'm not concerned as much with hints on proving the union is connected, but instead I'm confused on what I'm to infer for the $A < B$. Does this mean all of the $U_a$ are nested subsets?
Thanks for any help.
Comment: You are going to need the hypothesis: $\bigcap U_a\neq\emptyset $ otherwise the statement is false.
Comment: Is there any way that $U_a \subseteq U_b$ implies this? Since the index isn't explicitly stated, what can I infer from the ordering?
Comment: No, I don't think $U_a \subseteq U_b\implies\bigcap_{a\in I} U_a\neq\emptyset$, check this https://math.stackexchange.com/questions/2000408/union-of-connected-sets-also-connected
Comment: @Isa.  That the intersection is not empty is not needed as the sets are nested.
Comment: Yes, the sets are nested.
Comment: The  connected  sets (0,r), r > 0 are nested, their intersection is empty and their union is connected.
Comment: @WilliamElliot I though the nonempty intersection was a _must_ have condition in order to prove that the union is connected, interesting to know that can be replaced with the nested condition.
Comment: @Isa.  There are two cases:  all the sets are empty;  one is not empty.  Proofs are simple.
Answer: Your assumptions are somewhat unclear. The index set $A$ presumably has a (linear?) order and for $a < b$ we have $U_a \subseteq U_b$.
Suppose that $f: \bigcup_{a \in A} U_a \to \{0,1\}$ is continuous, where the image space has the discrete topology. By connectedness of each $U_a$ (I'll assume they're non-empty too WLOG) for each $a$ we have $i(a) \in \{0,1\}$ such that $f[U_a] = \{i(a)\}$. Now if $a \neq b$ we either have $a < b$ or $b < a$ (I am making the assumption that $A$ has a linear order) and in the first case we have $\{(i(a)\} = f[U_a] \subseteq f[U_b] = \{i(b)\}$ so that $(i(a) = i(b)$, the other case yields the same conclusion. So $f$ is constant and so $\bigcup_{a \in A} U_a$ is connected.
The linear order assumption is necessary as there are counterexamples for partially ordered index sets.
Answer: The OP does not like the way the problem is stated. How about this:
Let $(I, \le)$ be a totally ordered set that is also an index for a family of connected subspaces $(A_\alpha)_{ \, \alpha \in I} $ of a topological space $X$. Assume that whenever  $\alpha_0, \alpha_1 \in I$,
$\tag 1  \alpha_0 \le \alpha_1 \text{ implies } A_{\alpha_0} \subset A_{\alpha_1}$
Then $\bigcup_{\alpha \in I} A_\alpha$ is connected.


What's the difference between content type and node?

Question: I have been reading information about what is a content type and what is a node. I understand what a content type is (a collection of fields), but I don't know exactly the difference between a node and a content type.
In drupal website, I can read:

A node is any piece of individual content, such as a page, poll, article, forum topic, or a blog entry
Content-Type is a pre-defined collection of data types (Fields) which relate to each other by an informational context

For example, I think an article is a content-type, but it seems that, at the same time, it's also a node. So I don't understand the difference.
It seems that a node is a super-category while a content-type seems to be a sub-category. Is it right? How would you explain to me as simple as possible?
Comment: A content type is the definition, a node is an instance of a particular definition.
Comment: Of course, but reading again the definition that drupal website offers, I can read "A node is...such as a page...". So, if the node is an instance of a content-type. Is a page a content-type?
Answer: Newcomers to Drupal who aren't tech savvy often struggle with the concept of Content types and Nodes.
I find it beneficial to remind them of the real world equivalent—forms and filling in forms.
Remember in the olden days when you were given a piece of paper out of a whole stack of them, with labels and boxes and you used a pen to fill in your information by hand (name, address, DOB, etc.) when applying for a college or anything?
The Drupal equivalent to a real-life stack of blank sheets of preformatted forms is a Content type. When you're creating a Content type in Drupal, you're actually designing a form of blank fields. You're designing a structure, it holds no data.
In the digital world, we don't have to have multiple copies of Content types, one is enough because it doesn't have to be printed on paper. It is printed on the screen and we can always use the same "source". That's way we only have one "Create article" form and not thousands of them like you have to in paper form.
When you fill in one sheet of paper in ink with your specific information it is considered one form submission. The Drupal equivalent to this one filled-in sheet of paper is a Node. Node is the actual data entered into the structure defined by the Content type. You can create many Nodes (data submissions) for a Content type.
When you want to publish an Article you are first presented with a form to fill—Create Article page. This is the Content type form. Once you enter specific data into it and Save, you have created one submission of that form, one Node. You can create many nodes, with different data, as submissions to the same form.
Answer: In an easy to understand way:
Node is a page.
Content type is the page type or page fields & page structure.
For example, you could create a new content type called "Blog". Here you can add the fields that you would like blogs to have. The other content type "Articles" may not have the same fields that "Blogs" have.
So when you go create a node, you choose which one you would like, "Blog" or "Article".
Comment: Thanks, I better understand right now. So each page is a node that belongs to a specific category (content-type).

Comparing it to fruits, a lemon or an orange are fruits (nodes) and, at the same time, those fruits belongs to a category (content-type), in this case oranges and lemons correspond to citrus. Right?
Comment: @RichardSteele Assuming citrus is the content type, then correct.
Comment: @RichardSteele although, category may not be the best way to describe it as you can categorize stuff using tags/taxonomy reference. Think of it more of a fields that are inside of the content type  and how they display when viewed.  Ex: The blog content type may have 10 fields while the Article content type only has 2 fields.


A convergent sequence of geodesics converges to a geodesic

Question: I'm reading Riemannian Geometry and Geometric Analysis by Jurgen Jost, and having a question about part of the following theorem.

Theorem 1.5.1 Let $M$ be a compact Riemannian manifold, $p,q \in M$. Then there exists a geodesic in every homotopy class of curves from $p$ to $q$, and this geodesic may be chosen as a shortest curve in its homotopy class.

Before outlining the proof of the theorem, we need a Corollary made before.

Corollary 1.4.4. Let $M$ be a compact Riemannian manifold. Then there exists $\rho_0>0$ with the property that any two points $p,q\in M$ with $d(p,q)\le \rho_0$ can be connected by precisely one geodesic of shortest length. This geodesic depends continuously on $p$ and $q$.

Outline of Theorem 1.5.1
Take a minimizing sequence $(\gamma_n)_{n \in \mathbb{N}}$ for arc length in the given homotopy class. We may assume that for any $\gamma_n$, there exist points $p_{0,n},...,p_{m,n}$ for which $d(p_{j-1,n},p_{j,n}) \le \rho_0$, where $m$ is independent of $\gamma_n$ and $\rho_0 <0$ is the constant in Corollary 1.4.4.
By compactness, after selection of a subsequence (still denote $\gamma_n, p_{j,n}$), the point $p_{j,n}$ converges to points $p_j$, and the segment of $\gamma_n$ between $p_{j-1,n},p_{j,n}$ converges to the shortest geodesic between $p_{j-1},p_{j}$.
Question
In the book, it says the statement in bold can be seen by using Corollary 1.4.4. but I don't quite understand what does it mean. Does the continuous dependency on endpoints directly imply the statement in bold? My attempt is to, on each segment, view the geodesics as functions $\gamma_n: [0,1] \to M$ for all $n$ and justify the limit function $\gamma: [0,1] \to M$ also satisfies the geodesic equation. But I have some trouble justifying this.
Answer: Looking at the differential equation would, presumable, repeat the hard work you will have put into proving the Corollary 1.4.4. I'm not sure what you have available at that point, but probably everything you need to follow this reasoning (to simplify notation fix one index $j$ and set $p := p_j, p_n = p_{j,n}$ etc):
Have a look at the exponential maps in $p$ and $p_n$ and the geodesic segments $\gamma_n$ under $\exp_{p_n}$. They will be of the form $t\mapsto exp_{p_n}t v_n$ for some sequence of unit vectors $v_n \in T_{p_n}M$.
After possibly choosing another subsequence the initial vectors $v_n$  will converge to some vector $v$ of length one in $T_pM$ and the curve segments to the segment $exp_ptv$. This is using the continuity of $exp$ on $TM$ in a neighbourhood of the zero section -- and the compactness of the unit sphere (bundle). At this point you may want to have another closer look and some additional reasoning if this is not clear to you. Now you need to know that $exp_ptv $ is, for small $t$, the locally unique geodesic from $p$ to $exp_ptv$ ('small $t$' to be chosen in such a way that you are covered by the Corollary 1.4.4), and you are done.
So continuity of the geodesics should be understood in the sense of continuity of $\exp_pv$.


Why can't I debug my puppet code?

Question: I'm learning Puppet and the biggest frustration I have with the entire paradigm is the try/run/fix development process I'm using to build functional Puppet code. My background is in Java and I'm naturally use to debugging my code to find errors instead of just running the program to see where it bombs making development much faster but I can't seem to find a way to do this using Puppet and Eclipse. I know writing a debugger for Puppet would require some creativity given its nature but I think this is something the community could really benefit from.
I've written debuggers and know the Eclipse SDK but unfortunately it does not map cleanly to the Puppet architecture which is a bit awkward in the sense its runtime stack and execution flow does not happen in natural order as well as the fact the runtime requires a target machine to apply changes on.
I'm curious if the community has done any development work on trying to create some kind of debugger where code can be stepped. To write this I think it would make sense to extend Eclipse with a new Puppet debug configuration type where you specify a target sandbox host to test your code as well as a puppet project in your workspace you want to debug (leveraging existing Gepetto tooling). Then when you start a new Puppet debugging session Eclipse could connect to the remote host, execute puppet apply with some additional debug arguments and somehow provide feedback from the runtime about what line of code is currently being executed.
This still might be awkward but would allow puppet developers to quickly see things like oh duh.. I can't create this directory because the parent path does not exist, wait... why is this if statement not going here like I planned, oh I see here that Puppet is not very clear on single or double quotes or now I see why this fails because this class was not executed first etc. etc.
Instead all we get is a big ugly output on the agent console that yes can give us insight on errors but does not cleanly map exceptions to our code that in my view shows an underlying pain and weakness of Puppet, can you at least give me a stack trace and line number so I know where to look? Nope sorry.
Don't get me wrong, I love how Puppet can make me look very productive throughout the work week when all I'm doing is running Puppet apply on new machines which my manager has not yet figured out but I think for Puppet to really be useful this lack of debugging support is something that needs to be addressed.
Does anyone else feel this pain? - Duncan Krebs
Answer: It would be impossible to "step through" puppet code, unless you want to debug against the ruby codebase itself. It's not just that the order of "execution" is unclear, its that the manifest themselves are never executed at a single time. They are actually evaluated in multiple phases throughout execution.
There are ways to simplify finding problems though. The biggest one is writing unit tests using rspec-puppet. It lets you essentially test the compilation phase of puppet, helping you catch errors like circular dependencies, incorrect conditional logic, etc.
Answer: There is a new tool called the puppet-debugger which allows you to set breakpoints in your puppet code in order to step through it.  So this is no longer "impossible" as it has been available for about 8 months.
You will first need to install the puppet-debugger gem
https://github.com/nwops/puppet-debugger
Then install the debug module, include it in your fixtures or just ensure it is in your module path.
https://forge.puppet.com/nwops/debug
Then just set a breakpoint in your code using debug::break() function.
<code>Ruby Version: 2.0.0
Puppet Version: 4.9.4
Puppet Debugger Version: 0.6.0
Created by: NWOps
Type "exit", "functions", "vars", "krt", "whereami", "facts", "resources", "classes",
     "play", "classification", "types", "datatypes", "reset", or "help" for more information.

>> $vars = ['one', 'two', 'three']
 => [
  [0] "one",
  [1] "two",
  [2] "three"
]
>> $vars.each | String $var | {
  debug::break()
  notify{$var:}
}
From file: puppet_debugger_input20170417-97123-qjwbaj.pp
         1: $vars.each | String $var | {
      => 2:   debug::break()
         3:   notify{$var:}
         4: }
1:>> $var
 => "one"
2:>> exit
From file: puppet_debugger_input20170417-97123-qjwbaj.pp
         1: $vars.each | String $var | {
      => 2:   debug::break()
         3:   notify{$var:}
         4: }
1:>> $var
 => "two"
2:>> exit
From file: puppet_debugger_input20170417-97123-qjwbaj.pp
         1: $vars.each | String $var | {
      => 2:   debug::break()
         3:   notify{$var:}
         4: }
1:>> $var
 => "three"
</code>
Comment: Thanks, sounds like its worth checking out!

Why can't I debug my puppet code?


scraping data from website which uses Ajax requests

Question: I'm have made a program for scraping data from a website
so far I have made a program using python and selenium and beautifulsoup and when it wants to scrape data from a page of that website like this one
I have to click on a tab named "سابقه" (at the top and it's in torquoise color)then website uses Ajax request to get the data and after that I loop through the table and the table has more than one page so I have to click on numbers below the table and collect new data again.
My problem is this method is really slow because I also have to collect data from 500 pages and every page contains 35 tables.
Is there any other faster way to do this?Or maybe a way to fire Ajax request within my program and get the response.It would be better if the solution be in python.
Comment: `AJAX request` is normal request executed by JavaScript - so if you know its url, its method (POST,GET) and its parameters (headers, cookies, etc.) then you can do this request manually using `requests` or `urllib` to make it faster then `Selenium`. You can use `DevTool` in Chrome/Firefox to see all requests in tab `Network` in `DevTool`.
Comment: in `DevTool` I use tab `Network` and select `XHR` to see only javascript requests. And I see url `http://members.tsetmc.com/tsev2/data/InstTradeHistory.aspx?i=9211775239375291&Top=999999&A=0` and it sends data like `email@example.com@email@example.com@firstname.lastname@example.com@email@example.com@460750068@...` and there are values `901.00`, `863.00`, etc. which I see in table on the page.
Comment: you could catch this url many times to compare values in `i=9211775239375291&Top=999999&A=0` - maybe they never change, but maybe `i` is `timestamp` and you have to change it to get current data.
Comment: BTW: mostly `AJAX` sends data as `JSON` which you can easily convert to python dictionary using module `json` but sometimes it can send data encrypted and then there is the problem to decrypt it (if you don't know how data were encrypted).
Comment: You are right first I tried that the method for onclick event of those buttons is showtab(number) but I could'nt find this method using the chorme devtools search where do I have to look for it
Comment: you could raise multiple instances of the browser and Beautiful Soup to extract the data from the different sites simultaneously
Comment: What have you written so far?
Answer: Tab uses JavaScript to get all data from url
http://members.tsetmc.com/tsev2/data/InstTradeHistory.aspx?i=9211775239375291&Top=999999&A=0
and later only change data in table. Other tabs use different urls but rest should be similar.
You can use requests to get all at once
import requests

url = 'http://members.tsetmc.com/tsev2/data/InstTradeHistory.aspx?i=9211775239375291&Top=999999&A=0'

r = requests.get(url)

print(r.text[:50]) # first 50 chars

data = r.text.split(';')

print('number od days:', len(data))

for row in data: # data[:5]: # first 5 rows
    row = row.split('@')
    print('date:', row[0], '|', row[1:4]) # first 3 values

Result (small preview)
firstname.lastname@example.com@email@example.com@firstname.lastname@example.com@859.00

number od days: 1202

date: 20171213 | ['901.00', '863.00', '893.00']
date: 20171212 | ['859.00', '859.00', '859.00']
date: 20171211 | ['823.00', '782.00', '819.00']
date: 20171210 | ['796.00', '780.00', '784.00']
date: 20171209 | ['797.00', '781.00', '787.00']
...

BTW: you could do it also with standard module urllib.request but server sends data compressed with gzip so you would have to use module gzipFile to manually uncompress it.
Or you could try to send request with header Accept-Encoding: deflate to inform server that you need data uncompressed.

I don't know if url always has the same values in arguments
i=9211775239375291&Top=999999&A=0

but value i is also in page url
http://www.tsetmc.com/Loader.aspx?ParTree=151311&i=9211775239375291


Hint for integrating exp(x-x^2)

Question: The function $e^{x-x^2}$ is zero if $x \to \infty$ or $x \to -\infty$ it looks like a normal-distribution-curve with the max. value at $x=0.5$.
Has somebody a hint for integrating it from $-\infty$ to $\infty$ ?
Thank you.
Comment: Maybe try to complete the square and then do a change of variables.
Comment: Do you want an antiderivative, or just to integrate it from $-\infty$ to $\infty$?
Comment: I need to integrate it from $-\infty$ to $\infty$
Answer: $$x-x^2=-\left(x-\frac{1}{2}\right)^2 +\frac{1}{4}$$
So you are going to get the usual normal $e^{-t^2}$ times a constant ($e^{1/4}$) after substituting $t=x-\frac{1}{2}$.
Answer: I assume you need to solve this integral: $$I=\int_{-\infty}^{+\infty}e^{x-x^2}dx.$$ Try this: $x-x^2=-(x-1/2)^2+1/4$. The integral then becomes $$I=e^{1/4}\int_{-\infty}^{+\infty}e^{-(x-1/2)^2}dx.$$ Do a change of variables, recognize the gaussian integral and you're done!

Hint for integrating exp(x-x^2)


Programmatically do something when a node is updated

Question: I want to do something when a node gets updated. To keep it simple, lets say display a drupal message.
hello_world.routing.yml
hello_world:
    path: /node/{node}
    defaults:
        _controller: Drupal\hello_world\Controller\HelloWorldController::hello_world_entity_update
    requirements:
        _permission: 'access content'

Not sure if the path should be /node/{node}/edit instead.
HelloWorldController.php
<?php
/**
 * @file
 * Contains \Drupal\hello_world\Controller\HelloController.
 */

namespace Drupal\hello_world\Controller;

use Drupal\Core\Controller\ControllerBase;

class HelloWorldController extends ControllerBase {

  public function hello_world_entity_update(Drupal\Core\Entity\EntityInterface $entity) {

    drupal_set_message(t('Something @var just happened.', array('@var' => 'cool')));

  }
}

Since hook_node_update() was depreciated, I assume we now have to use hook_entity_update().
I am not getting the message upon updating a node, what I'm I missing or doing wrong?

Update

Just so I don't confuse anyone.
I was brainwashed into thinking I needed a routing file and a
controller. All the D8 examples out there use them.
Since I was not creating any pages,
turns out I did not need a routing.yml file nor a Controller.php file
nor the /src folder. All I had to do is approach this like Drupal 7,
all that I needed was the .info.yml file and a .module file
to put the hook.
Comment: You have to put hook_entity_update() in helloword.module. This does not work as a controller.
Comment: Thank you for the disclaimer at the end.  I'm a D7 veteran but new to D8 and I'm still trying to figure out when to use the OOP structure... all the documentation says how to use it, but not when...
Answer: Hooks are still implemented as global, procedural functions; you need to declare them in the .module file just like Drupal 7, not in a controller class:
function MYMODULE_entity_update(Drupal\Core\Entity\EntityInterface $entity) {
  // ...
}

It's also worth noting that hook_ENTITY_TYPE_update() also exists, so you can still use hook_node_update():
function MYMODULE_node_update(Drupal\node\NodeInterface $node) {
  // ...
}

Comment: Typically a controller is linked up to a route, so they're generally used for building the markup (render array) for a page
Comment: interesting, then what should I put in my controller? controllers are not mandatory?
Comment: `so they're generally used for building the markup (render array) for a page` since I am not building a page, leave the controller class empty? or delete it all together?
Comment: Are you thinking a module requires a controller? It doesn't, so unless you need it for something (essentially building a page), just remove the file
Comment: [according to this](https://www.drupal.org/node/2092643) I need to have something for `defaults:` in my hello_world.rounting.yml, so what should I use instead? `_entity_form`?
Comment: What's that routing entry for exactly? You might just be thinking about this too hard, to do something when a node is updated all you need is a single hook. There's no routing involved
Comment: says here  "[defaults (required):](https://www.drupal.org/node/2092643)"
Comment: Yep, defaults are required for a route. But why do you need a route? What's it for? What are you routing to where and why?
Comment: ah ok gotcha!!! no I am not routing anything, so I will delete the defaults part all together. I couldn't find any D8 example out there that did something without creating a page.
Comment: Sounds like you can just delete the routing file altogether unless there's something else in it :)
Comment: OMG that's even better!
Answer:
You need not define any controller for this .
Write this code in your custom .module file.

use Drupal\Core\Entity\EntityInterface;
 function module_name_entity_update(EntityInterface $entity) {

    drupal_set_message(t('Something @var just happened.', array('@var' => 'cool')));

  }

Comment: Does this hook get invoked when ie. a comment is added with ajax ie. ajax_comments module which uses ajax to add comments.
Answer: There are lots of hooks are available for node.
You can inherit in template.php file and write down your code.
you can use hook_node_update in template.php
Comment: hooks should be used in .module files and not in template.php. Maybe you're confusing them with function template_something. Ex: [template_preprocess_node](https://api.drupal.org/api/drupal/modules%21node%21node.module/function/template_preprocess_node/7.x) which goes in your template.php file.


Import class file into Java program?

Question: I know this has been asked a few times, but I can't find a solution using those answers.
I have a class file called LRW.class which I have put in an folder called external in the eclipse folder under my program name. So my path to the class is: myusername.WorkBench.ProjectA.external.LRW.class and I've made that folder using the new class folder in eclipse.
How do I use/import/call this class in java?
TIA
Answer: If it's in the default package, being used by a class in the default package, you don't need to import it at all. If the class using LRW isn't in the default package, it would be easiest to put LRW in a package--you can't import classes in the default package (see JLS section 7.5).
If it complains it isn't found, you'll need to make sure that folder is listed in the project's build path (right-click project -> properties, Java build path, Libraries tab, Add Class Folder).
Comment: @EricBanderhide I understand that, but a class has a package, either the default, or a named package. Your import must match the package of the class, and the class file must be located in a directory matching its package name. One way to determine what the package is to run `javap LRW` from the command line to see if it needs to go into a sub-directory under `external`.
Comment: It doesn't seem to work still, I've tried setting the folder as a class folder and external class folder, they appear in the structure, but as soon as I type in import LRW; eclipse shows an error with no useful fix?
Comment: @EricBanderhide Is the class really there? Is the `LRW` class *really* in the default package, or did it have a `package` statement in it?
Comment: I don't fully understand, its just a class file I placed in a folder next to the src folder in its eclipse folder?
Comment: @EricBanderhide - I think you need to do a Java tutorial to learn what a package is in Java.  You shouldn't use SO as a way to avoid reading the textbook / tutorial.
Comment: @EricBanderhide That's just where it is in the folder; the *class file itself* was compiled either the default or a named package. Since your class is *also* in the default package (boooo) you don't even need to import it if it *was* compiled in the default package.
Comment: @EricBanderhide I pretty much already told you. *I* don't know anything about the LRW class other than what you've told me, and can't run `javap` on it to check. Try without the import. See if it's supposed to be in a package. Make sure the folder is listed correctly in the build dependencies (as a class folder). If *all* else fails, create a public git repo containing only the source and this single class file, in their current folder hierarchy, and provide a link to the project and I'll take a look.
Answer: it is correct, you  would use "import LRW" however it is a bad practice not to use namespaces. You should better put the class in a folder called , for example "com/mydomainn" and then  use
import com.mydomain.LRW
Answer: Add external to your build path as class folder and use LRW like any other class.
Make sure LRW is in default package, otherwise you need to change it's location according to the package.

Import class file into Java program?


Contraction or Reduction of a Neural Network

Question: Circuit size reduction is common practice in Theoretical Computer science. It is very common to approximate a circuit with a smaller circuit (Or a polynomial and so on). Are there any such techniques in Neural networks? i.e Given a trained neural network can I reduce the size (Say number of perceptrons or layers) without any significant reduction in the performance.
If yes can you please mention the references.
Thank you
Edit: Contraction of a circuit can be seen as an approximation of a larger circuit by a smaller circuit. Suppose I have a circuits $C$ with $n$ gates. I will remove certain gates(say k number of gates) and tweak some connections(wires) to obtain circuit $C'$(These gates are typically the one that doesn't affect the output significantly). Now the new circuit $C'$ and the old circuit $C$ will give the same output for most of the input except an $\epsilon$ fraction of them.
Comment: I think you might get an answer by searching for a phrase "pruning neural networks" on google or similar search engine.
Comment: For those of us who are not theoretical computer scientists, could you explain what contraction is?
Comment: @Sycorax. Suppose I have a circuits $C$ with $n$ gates. I will remove certain gates(say k number of gates) and tweak some connections(wires) to obtain circuit $C'$(These gates are typically the one that doesn't affect the output significantly). Now the new circuit $C'$ and the old circuit $C$ will give the same output for most of the input except an $\epsilon$ fraction of them.
Comment: @Sycorax Typically the reduction in number of gates is of a large fraction compared to the error fraction $\epsilon$
Answer: This assumes that your network is not grossly overtrained. If you want to keep your architecture the same, then you can try looking at activations of your network across images and outright delete any dead or almost-dead neurons. Alternatively, if you're using say, 1x1 convolutions, you might be able to discard a prune convolutions that have not been feature-selected by the 1x1s. Overall, you're probably not going to achieve much in terms of reduction and compression using these techniques (assuming you've already used batch normalization, reasonable learning rates, etc.). Reasonably, you can probably expect upwards of 2x speedup. There are many more techniques, and a nice overview can be found in A Survey of Model Compression and Acceleration
for Deep Neural Networks
- Cheng, et. al..
You can alternatively use floating-point reduction. An example of this is NVIDIA tensorflow RT, which fine-tunes the existing network with lower floating-point precision. This invariably ends up with a much faster neural network, and less memory for weights.
However, if you're willing to switch architecture, a good example of this is MobileNets, which can achieve reasonable accuracy, while being much smaller than most other architectures out there (Resnet, Inception, etc.). The above paper presents nice examples of this, one being a mobilenet implementation of FaceNet. The nice thing about their approach is that they didn't have to use the original dual-embedding techniques from facenet (along with notoriously difficult hard negative mining). Instead, they just train the mobilenet to reproduce facenet's embeddings. A similar approach can be undertaken for other problems.
Comment: I Guess it should be NVIDIA tensorRT and not Tensorflow RT. I was confused


Roots of $P_n(z)=1 + z + z^2 + ... + z^n$

Question: So I know that the factorization of $z^n-1$ is:
$$z^{n}-1=\prod_{k=0}^{n-1}(z-e^{i(\frac{2\pi}{n}k)})$$
But I don't see how to factorize the monic polynomial $1+z+...+z^n$, where none of the coefficients is null.
Comment: It's all the roots of unity that are not equal to $1.$ Do you know the sum of a geometric series?
Answer: As $$\displaystyle{z^{n+1}-1=\prod\limits_{k=0}^{n}(z-e^{i(\frac{2\pi}{n+1}k)})}$$ and $$\displaystyle{z^{n+1} -1 = (z-1)(1+\cdots+z^n)}$$ we get that :
$$\displaystyle{(1+\cdots+z^n) = \prod\limits_{k=1}^{n}\left(z-e^{i(\frac{2\pi}{n+1}k)}\right)}$$
Answer: Hint:
$$P_n(z)=\frac{z^{n+1}-1}{z-1}$$
Answer: Notice that : $$ P_{n}\left(z\right)=\sum_{k=0}^{n}{z^{k}}=\frac{z^{n+1}-1}{z-1}=\prod_{k=1}^{n}{\left(z-\mathrm{e}^{\mathrm{i}\frac{2k\pi}{n+1}}\right)} $$


Extract First chracter of all words except the first one

Question: I have list of names and i am tryign to extract the First word then First character of 2nd word and 3rd character of 3rd work and so on...
I was only able to make this formula but it works till 2nd name how to achieve further any help will be much appreciated.
=LEFT(D4,FIND(" ",D4)-1)&" "&LEFT(LEFT(D4,SEARCH(" ",D4)-1),1)

[enter link description here][2]
[2]:
Link
Comment: updated a link @player0
Comment: @player0 the input is in the column labelled "string" and the output is in the column labelled "Result" or do you think I missed something?
Comment: @SolarMike you didn't, it's just not "easily" scalable I guess (easily like avoiding attaching monstrous strings so it would work for 10+ names)
Answer: So, took only two of your examples as I don't have time to type them all in, but this works:
LEFT(B1,FIND(" ",B1)-1)&" "&MID(B1,FIND(" ",B1,1)+1,1)&IFERROR(MID(B1,FIND(" ",B1,FIND(" ",B1,1)+1)+1,1),"")

I used mid() instead of your left(left( construct and find() to find the second and third spaces.
The iferror is to not have an error when the third name does not exist.
You can expand this for 4 names :) good luck.
Comment: @HSHO As I stated in my answer, I have shown how to do this for 3 and I left you to expand it for 4 or more, just a question of finding the position of the spaces which I have showed clearly.
Comment: Hi thank you for sharing an answer but what if a name has more words like more than 3. It will take the 4th or 5th word first character and it gives an error if string has only single name.
Answer: try:
=ARRAYFORMULA(IFNA(REGEXEXTRACT(B2:B, "\w+ ")&
 BYROW(B2:B, LAMBDA(x, TEXTJOIN(, 1, IFNA(REGEXEXTRACT(
 SPLIT(REGEXREPLACE(x, "^(\w+) ", ), " "), "[A-Z]"))))))

update:
=ARRAYFORMULA(IFNA(TRIM(REGEXEXTRACT(B2:B, "\w+")&" "&
 BYROW(B2:B, LAMBDA(x, TEXTJOIN(, 1, IFERROR(REGEXEXTRACT(
 SPLIT(REGEXREPLACE(x&" ", "^(\w+) ", ), " "), "[A-Z]"))))))))

Comment: @HSHO But none of the examples you gave have a single name. Why are you finding obstacles or is this a question with limitless creep? In which case we tend to stop playing.
Comment: thank you very much but it does not work if cell has single name. @player0
Answer: Here's another variation of regex you can try out:
=INDEX(TRIM(REGEXEXTRACT(B2:B21,"\w+")&" "&MID(REGEXREPLACE(PROPER(B2:B21),"[^A-Z]",""),2,2^99)))
-
Answer: Late to the game, but I think this would be a clean way of extracting those letters, without barfing on single words or blank cells:
=iferror(regexextract(B2,"\w+ ?")&regexreplace(mid(proper(B2),2,99),"[^A-Z]",""))

...or as an array formula:
=arrayformula( iferror(
  regexextract(B2:B, "\w+ ?") & regexreplace(mid(proper(B2:B), 2, 99), "[^A-Z]", "")
) )


Finding the average sum of 15 numbers out of 100 numbers

Question: I've got a question.
For the numbers 1,2,...,100 we choose with the same probability 15 numbers.
1) What is the average sum of those numbers?
2) What is the average sum of those numbers when the probability to choose an even number is 3 times greater than choosing an odd number?
Comment: You choose with or without replacement?
Answer: There are two reasonable interpretations of the problem: (i) the sampling is done without replacement and (ii) the sampling is done with replacement. However, the answers turn out to be the same under both interpretations!
Imagine the sampling is done one at a time. Let random variables $X_i$ be the number pulled on the $i$-th trial. We want $E(X_1+\cdots+X_{15})$, which is $E(X_1)+\cdots+E(X_{15})$.  (Note that the linearity of expectation does not require independence.)
The expected value of $X_i$ is $\frac{1+\cdots+100}{100}$, which is $\frac{101}{2}$. Thus the expected value of the sum is $15\cdot\frac{101}{2}$.
We now look at the evens-odds problem. We interpret "three times greater" as meaning that the probability of pulling an even is three times the probability of pulling an odd. Then the probability of an even is $\frac{3}{4}$ and the probability of an odd is $\frac{1}{4}$.
Again we find $E(X_i)$ and multiply by $15$. Given that  we pull an even, the expected value is $\frac{2+4+\cdots+50}{50}$, which is $51$. Given we pull an odd, the expected value is $50$. So $E(X_i)=\frac{3}{4}\cdot 51+\frac{1}{4}\cdot 50$. Multiply by $15$.


How to specify output name of cc_binary target

Question: I'd like to build a simple application and to specify its output name: for debug version 'd' prefix should be added. I tried to use genrule for it, but I don't know how to change this option in different compilation modes. However I suppose that using genrule is not correct way.
So, how to specify output name?
cc_binary(
    name = "TestApp",
    srcs = [
        "src/TestApp/main.cpp",
    ],
)

genrule(
    name = "output_name_rule",
    srcs = [":TestApp"],
    outs = ["TestAppd.exe"],
    output_to_bindir = True,
    cmd_bat = "rename $(location TestApp) TestAppd.exe"
    )

config_setting(
    name = "release_build",
    values = {
        "compilation_mode":"opt"
    }
)

config_setting(
    name = "debug_build",
    values = {
        "compilation_mode":"dbg"
    }
)

Answer: genrule.outs is documented as nonconfigurable, so you can't use it directly. I would create a genrule that copies the file that exists in all configurations, and then choose between the genrule and the original cc_binary based on the configuration. Something like this:
genrule(
    name = "copy_with_d",
    srcs = [":TestApp"],
    outs = ["TestAppd.exe"],
    output_to_bindir = True,
    cmd_bat = "rename $(location TestApp) TestAppd.exe"
)

alias(
    name = "maybe_with_d",
    actual = select({
        ":debug_build": "TestAppd.exe",
        "//conditions:default": "TestApp.exe",
    }),
)

Some notes on things to tweak for your use case:

On Linux, I would write cmd = "cp $< $@". I'm not sure how Windows rename handles the input not being writable. You can definitely write $< and $@ instead of repeating the filenames though, they are Bazel "Make" variables.
I put the non-d version as //conditions:default so it applies in fastbuild too, up to you which way you want as the default.
Up to you whether you use TestApp.exe or :TestApp.exe or :TestApp in alias.actual to refer to that version, they're all equivalent. Same with TestAppd.exe vs copy_with_d or :copy_with_d, etc.


Solving wave equation by factorizing Laplace Operators: repeated roots

Question: Suppose I have the wave equation:
$u_{tt}=c^2u_{xx}$
I factorize the Laplacian operators:
$\partial_{tt}-c^2\partial_{xx}=(\partial_{t}-c\partial_{x})(\partial_{t}+c\partial_{x})$
From there I can use the change of variable $u(t,x)=v(r,s)$ where $r=x+ct$ and $s=x-ct$
What change of variable do I choose if the Laplacian operators factor into a $(a-b)^2$ identity?
Answer: Assuming your question is, what change of variables would you use for solving $(\partial_t−\partial_x)^2u = 0$...
One quickly sees that this equation is parabolic and thus only has one characteristic.  One could use the one characteristic direction for one new variable, and any direction that is not parallel to the characteristic direction for the other.
To elaborate, for $u_{tt} - 2u_{xt} + u_{xx} = 0,$ one sees that
$$\frac{dx}{dt} = \frac{-(-2) \pm \sqrt{4-4}}{2} = 1,$$
so you have $x = t + \xi.$  Thus, use $\xi(x,t) = x - t$ as one variable.  The other one can be anything not parallel, such as $\eta(x,t) = t.$
Answer: In the case of repeated roots when factorizing Laplacian operators, use the following change of variables:
$u(t,x)=v(t,s)$ where $s=x+\frac{t}{2}$


Regression of proportions

Question: I have to regress the mortality rate which is in number of deaths per thousand and percentage of vaccinated people. Have sample data for different districts. Can I use linear regression directly. The sample sizes are different for different districts. Please suggest the appropriate method.
Comment: You'd need to account for other things that affect overall mortality rate, like differences in age distribution. You'd also need to account for differences in variance between these observations, which are due to more than just variation in sample size.
Comment: possible duplicate of [Analyze proportions](http://stats.stackexchange.com/questions/24187/analyze-proportions)
Comment: So the idea is that mortality rate would be your response variable, & % vaccinated would be a covariate, is that right?
Answer: Your analysis would be improved if you had populations for each of the districts. The variance of the rates will depend on the counts, so the standard deviation of each of the rates will be proportional to the standard deviation of the underlying counts. If you had that information it would be reasonably simple to do a Poisson regression. Linear regression could be examined as well but with variance that is different than the usual naive assumptions.
The other issue to consider is whether the relationship is a simple straight line on either the linear scale or on the log scale. Poisson regression is estimating the relationship on the log scale, while linear regression would be doing so in the linear scale. The assumption of linearity on either (or both) of the scales may be incorrect and you should be prepared to do some spline fits to examine the potential for non-linearity with either method.

Regression of proportions


Set default appearance for a UIView subclass without overriding initialize() in Swift 3.1

Question: I have a subclass of UITextView, which needs to have a specific default appearance. So far, I've been able to achieve this by overriding the initialize() class function, which has been deprecated in Swift 3.1.
public class CustomTextView : UITextView {
    override public class func initialize() {
        self.appearance().backgroundColor = .green
    }
}

Is there a way to achieve the same thing pure Swift?
Comment: you can customize your UITextView appearance overriding the didMoveToSuperview method.
Answer: I'm working around the loss of the class method initialize by using a construct like this:
class CustomTextView : UITextView {
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame:frame, textContainer: textContainer)
        CustomTextView.doInitialize
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder:aDecoder)
        CustomTextView.doInitialize
    }
    static let doInitialize : Void = {
        CustomTextView.appearance().backgroundColor = .green
    }()
}

This construct has the advantage that doInitialize will be initialized only once, so the code connected with it will run only once (in this case we'll configure the appearance proxy only once); and it is early enough to affect even the first instance created (that is, every CustomTextView you ever make will in fact be green).
Comment: @DavorBauk Then you asked the wrong question. You don't customize an _individual_ object by setting its `appearance` proxy. You customize an individual object by customizing that object. If that was really your goal, Leo Dabus' answer was right.
Comment: Thanks. I tried doing something similar but I realized that it would require instantiating the class first. So, if you were to configure the custom appearance first, and instantiated the class at a later time, the default appearance would override the custom one. Eg.:
Comment: ` CustomTextView.appearance().backgroundColor = .orange; let t = CustomTextView()`. The background color of t would be .green instead of .orange.
Comment: Thanks for the feedback. You're right, my question wasn't about trying to modify an individual instance; that was really just a simple illustration. In my particular scenario, `CustomTextField` is defined in a shared framework, which is used by several apps. However, each app has a slightly different color palette, so I would want to further customize the appearance of `CustomTextField` in each individual app. For example, have a different default outline color in each app respectively, but keep the default font and background color as defined by `CustomTextView`.
Comment: Okay, but your question was not about that! Your question was about doing something that would behave like `initialize` and that's what my answer responded to.
Comment: Again, thank you for the response. But your solution does not behave like `initialize()`. The documentation states: "The runtime sends initialize() to each class in a program just before the class, or any class that inherits from it, is sent its first message from within the program.". This means that any call to a class method is guaranteed to execute _after_ `initialize()`. Your solution suggests that a user should make sure to first create an instance of the class, discard that instance, and _then_ call the class function such as `appearance()`.
Comment: Well, if you _really_ want the exact timing of `initialize`, you need to override and implement `initialize` in Objective-C, as described here: http://stackoverflow.com/a/42824542/341994
Comment: Looks interesting. Working from their solution, I would make my text view class conform to a protocol (eg. `ClassInitializing`) which requires that the class implements `class func initializeClass()`, then on app launch list all classes and for each returned class call `(type as? ClassInitializing)?.initializeClass()`. Is there a way to just check whether a class implements `classInitializing()` and call it using objc runtime functions?


MySQL SHOW COLUMNS

Question: Teria como trazer somente as colunas do banco e ordenar da formar que eu quero por exemplo:
show columns FROM table

O código acima traz todas as colunas da tabela.
trazer as colunas ordenadas.
SHOW TABLE.COLUNA1,
     TABLE.COLUNA2
FROM TABLE

Answer: Tenta usar INFORMATION_SCHEMA:
SELECT `COLUMN_NAME`
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`='yourdatabasename'
    AND `TABLE_NAME`='yourtablename';

MySQL SHOW COLUMNS


Zero time spent in initial state in multi-state model?

Question: I'm modelling an illness-death multi-state model (see image, taken from the {survival} vignette, https://cran.r-project.org/web/packages/survival/vignettes/compete.pdf), and have a basic question: in my data, some individuals start in the 'Health' state, whilst some start in the 'Illness' state. I believe the initial state has to be the same for everyone, so should I implement those starting in 'Illness' as having spent zero time in the initial state, 'Health', does this violate model assumptions?

Thanks!
Answer: Although simple examples might have all individuals starting in the same state, that's not a requirement of multi-state models. The models are for each of the allowed transitions, so software should allow for specification of initial states for all individuals.
In the R survival package, you can specify an istate argument to coxph() that points to "the current state at the start each interval," according to the software help page. The vignette you cite mentions that in Section 2.2, on page 8.
I suspect that other multi-state modeling software provides the same possibility.


Songs with off-beats?

Question: I found this a lot in old songs, but also in quite a few new ones. I love songs that have this, off-beat music playing in the background. I know the song 'Bernadette' by IAMX has it. The beginning of Green Day's 'Viva la Gloria' has it. So does Caro Emerald's 'That Man.' I absolutely adore this so I was wondering:
Does anyone know what this is called in music other than "off-beat" or "syncopation?"
Comment: You may be referring to a "back beat", a strong pulse on beats 2 and 4 in 4/4 time (for example).
Answer: The IAMX example is pretty much oom-pah bass, which typically goes   root - chord - 5th - chord.  The downbeats are strong single notes (from the tuba in a brass band), usually alternating between the root and the fifth of the current chord, and the offbeats are chords (played by the higher pitched horns in a brass band).  This puts a kind of emphasis on the off beats since the higher pitched, thicker chords appear on it.
In terms of piano technique, this is  stride piano, as exemplified in your Caro Emerald example.  This term is more closely associated with jazz styles.
Comment: I'd embed the wikimedia image that shows the notation for oom-pah bass, but the imagur engine that we use doesn't accept png images.

Songs with off-beats?


Where do the "spare" balls come from in Test Match cricket?

Question: If a ball has gone out of shape and needs to be changed, the umpires bring out a box of balls which are similar to one being bowled. Where do these other balls come from?
Answer: They are balls used in previous matches and kept to be used as spares.   They will be the same type of ball as being used.
The umpires then look for a ball of similar wear and tear.


Problemas com Fragments: Activity has been destroyed

Question: Meu navigation drawer está correto, mas quando você clica num item do drawer, e ele vai dar um replace nos fragments, a aplicação pára, e no logcat aparece mensagem de erro dizendo que

Activity has been destroyed

Código:
class DrawerItemClickListener extends FragmentActivity implements         ListView.OnItemClickListener {

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    selectItem(position);
}

private void selectItem(int position) {

    Fragment fragment = null;

    switch(position)
    {
    case 0:
        fragment = new DadosCadastraisDilmaFragment();
        break;
    case 1:
        fragment = new DadosCadastraisAecioFragment();
        break;
    ...
            default:
            break;
    }

    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.content_frame, fragment).commit();
}
}

public class MainActivity extends ActionBarActivity{

private String [] listaCandidatos;
private DrawerLayout drawerLayout;
private ListView drawerList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // inicializar a lista do drawer
    listaCandidatos = getResources().getStringArray(R.array.lista_candidatos);
    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawerList = (ListView) findViewById(R.id.left_drawer);

    // Set the adapter for the list view
    drawerList.setAdapter(new ArrayAdapter<String>(this,
            R.layout.drawer_list_item,R.id.drawerListItemTextView, listaCandidatos));
    // Set the list's click listener
    drawerList.setOnItemClickListener(new DrawerItemClickListener());
}

Answer: O problema é que o  DrawerItemClickListener herda de FragmentActivity. E está fazendo reposições de Fragment em uma Activity (DrawerItemClickListener) usando o FragmentManager, que não foi criada pelo ActivityManager (parte do framework Android).
A mensagem:

Activity has been destroyed

É causada porque essa Activity não foi iniciada. Então para ele está destruída.
Remova essa herança e faça com que o DrawerItemClickListener seja declarado não estático dentro da MainActivity.
Mais ou menos assim:
public class MainActivity extends ActionBarActivity {

    // Restante do codigo

    public class DrawerItemClickListener implements ListView.OnItemClickListener {

        // Restante do seu código

    }
}

Comment: Muito obrigado, Funcionou!