Como desenhar um cubo usando openGL?

Question: Como desenho um cubo usando OpenGL no Android?
Comment: Já fez alguma tentativa? Quais foram os resultados das tentativas que você fez?
Answer: <code>Cubo.java
package com.teste;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import javax.microedition.khronos.opengles.GL10;

public class Cubo {
   private FloatBuffer vertexBuffer;
   private int numFaces = 6;

   private float[][] colors = {  // Array para armazenar cores dos 6 lados
      {1.0f, 0.5f, 0.0f, 1.0f},  // 0. laranja
      {1.0f, 0.0f, 1.0f, 1.0f},  // 1. violeta
      {0.0f, 1.0f, 0.0f, 1.0f},  // 2. verde
      {0.0f, 0.0f, 1.0f, 1.0f},  // 3. azul
      {1.0f, 0.0f, 0.0f, 1.0f},  // 4. vermelho
      {1.0f, 1.0f, 0.0f, 1.0f}   // 5. amarelo
   };

   private float[] vertices = {  // Vertices dos 6 lados
      // FRENTE
      -1.0f, -1.0f,  1.0f,  // 0. left-bottom-front
       1.0f, -1.0f,  1.0f,  // 1. right-bottom-front
      -1.0f,  1.0f,  1.0f,  // 2. left-top-front
       1.0f,  1.0f,  1.0f,  // 3. right-top-front
      // ATRÁS
       1.0f, -1.0f, -1.0f,  // 6. right-bottom-back
      -1.0f, -1.0f, -1.0f,  // 4. left-bottom-back
       1.0f,  1.0f, -1.0f,  // 7. right-top-back
      -1.0f,  1.0f, -1.0f,  // 5. left-top-back
      // ESQUERDA
      -1.0f, -1.0f, -1.0f,  // 4. left-bottom-back
      -1.0f, -1.0f,  1.0f,  // 0. left-bottom-front
      -1.0f,  1.0f, -1.0f,  // 5. left-top-back
      -1.0f,  1.0f,  1.0f,  // 2. left-top-front
      // DIREITA
       1.0f, -1.0f,  1.0f,  // 1. right-bottom-front
       1.0f, -1.0f, -1.0f,  // 6. right-bottom-back
       1.0f,  1.0f,  1.0f,  // 3. right-top-front
       1.0f,  1.0f, -1.0f,  // 7. right-top-back
      // EM CIMA
      -1.0f,  1.0f,  1.0f,  // 2. left-top-front
       1.0f,  1.0f,  1.0f,  // 3. right-top-front
      -1.0f,  1.0f, -1.0f,  // 5. left-top-back
       1.0f,  1.0f, -1.0f,  // 7. right-top-back
      // EM BAIXO
      -1.0f, -1.0f, -1.0f,  // 4. left-bottom-back
       1.0f, -1.0f, -1.0f,  // 6. right-bottom-back
      -1.0f, -1.0f,  1.0f,  // 0. left-bottom-front
       1.0f, -1.0f,  1.0f   // 1. right-bottom-front
   };

   // Construtor - para configurar o buffer
   public Cubo() {
      ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length * 4);
      vbb.order(ByteOrder.nativeOrder()); // Use native byte order
      vertexBuffer = vbb.asFloatBuffer(); // Converte Byte para Float
      vertexBuffer.put(vertices);         // Copia os dados para o buffer
      vertexBuffer.position(0);
   }

   // Desenha a forma
   public void desenha(GL10 gl) {
      gl.glFrontFace(GL10.GL_CCW);
      gl.glEnable(GL10.GL_CULL_FACE);
      gl.glCullFace(GL10.GL_BACK);

      gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
      gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);

      // Renderiza todos os lados
      for (int face = 0; face < numFaces; face++) {
         // Set the color for each of the faces
         gl.glColor4f(colors[face][0], colors[face][1], colors[face][2], colors[face][3]);
         // Draw the primitive from the vertex-array directly
         gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, face*4, 4);
      }
      gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
      gl.glDisable(GL10.GL_CULL_FACE);
   }
}
</code>
Comment: Era o que precisava. Obrigado!

Como desenhar um cubo usando openGL?


Using Euler's Formula to prove $\sin^32x\cos^23x = -\frac1{16}(\sin12x-3\sin8x+2\sin6x+3\sin 4x-6\sin 2x) $

Question: I am asked to show the following using Euler's formula, but I cannot see, how this relates to Euler's formula.
$$
\sin^32x\cos^23x = -\frac{1}{16}(\sin 12x - 3\sin 8x + 2\sin 6x + 3\sin 4x - 6\sin 2x)
$$
Comment: Maybe you could remind us what Euler's method is?
Comment: I guess you mean [Euler's formula](https://en.m.wikipedia.org/wiki/Euler's_formula), not Euler's method.
Comment: For the record, an alternative would be to write $$\sin^3(2x)\cos^2(3x)=\left(\frac{3\sin(2x)-\sin(6x)}{4}\right)\left(\frac{1+\cos(6x)}{2}\right)$$ and then product-to-sum identities.
Comment: By the way, your formula is not correct, it should be
$$
\sin^3(2x)\cos^2(3x) = \color{red}{-}\frac{1}{16}(\sin 12x - 3\sin 8x + 2\sin 6x + 3\sin 4x - 6\sin 2x)
$$
Answer: By Euler the left hand side is
$$
\left(\frac{\zeta^2-\zeta^{-2}}{2i}\right)^3
\left(\frac{\zeta^3+\zeta^{-3}}{2}\right)^2
$$
where $\zeta:=e^{ix}$.
It is easy to multiply this out and identify every term on the right hand side.


axios is not working with post file data wirh new FormData()

Question: My previous code for file uploading is working with jQuery Ajax call. But when I am trying to achieve the same task with Axios library then I got errors. I also search solution for that but not found. If anyone faces this issue. guide us. My previous code in Ajax call:
$.ajax({
    url: this.props.url,
    data: formData,
    cache: false,
    contentType: false,
    processData: false,
    type: 'POST',
    xhrFields: {
        withCredentials: true
    },
    crossDomain: true,
    success: function (response) {
        console.log(response);
    },
    error: function (err) {
        console.log(err);
    }
});

But in my new project (ReactJs and Axios), I 'm trying to achieve the same task with Axios(v0,17.0). But I am getting the error:

Access to XMLHttpRequest at 'https://example.com/' from origin
  'http://localhost:9002' has been blocked by CORS policy: Request
  header field Access-Control-Allow-Origin is not allowed by
  Access-Control-Allow-Headers in preflight response.
Error: Network Error
      at createError (createError.js:16)
      at XMLHttpRequest.handleError (xhr.js:87)

below code in Axios, I am using formData() to append file to eaily.
import axios from 'axios';

let formData = new FormData();
formData.append('noteFilename', files);

axios({
    method : 'POST',
    url : this.props.url,
    data:formData,
    headers: {
        'cache': false,
        'Content-Type' : false,
        'processData': false,
        'Access-Control-Allow-Origin': '*',
        'crossDomain' : true,
    },
    withCredentials: true,
}).then((response) => {
    console.log("response", response)

}).catch(function (error) {
    console.log(error);
});

Comment: Axios is not jQuery. Read the Axios API documentation. Don't just pass it the same options you pass to jQuery.
Comment: Sorry for title typo mistake it should be  "axios is not working with post file with new FormData()"
Comment: You can edit your question and remove typo! And you should edit format of your AJAX code.
Comment: CORS is something related to server not send the needed headers for OPTIONS request. Is your url same for both jQuery and react js projects. You have to check on  your server to add the needed CORS headers
Comment: Yes URL is same.
Answer: The error occurs because the browser sends a request to check if the api is allowed to be accessed from the browser on a different domain. Add headers to the server for the client-side to understand that it can make calls and will get a valid response for subsequent GET/POST calls.
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS, POST, PUT");
response.setHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");

you can even restrict the domain via the Access-Control-Allow-Origin key
response.setHeader("Access-Control-Allow-Origin", "xyz.com");

PS: Changes are to made on the server-side and not the client-side.
Comment: thanks, But I am uploading the file through $.ajax() this is uploaded successfully.
Comment: are you setting axios defaults or instance properties properly? they both use XHR under the hood so it shouldn't make a difference tbh @DheerajRao
Answer:
Access to XMLHttpRequest at 'https://example.com/' from origin 'http://localhost:9002' has been blocked by CORS policy: Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response.

This is because you are trying to set the Access-Control-Allow-Origin header on the request.
It makes no sense to do that. Access-Control-Allow-Origin is a response header which the server sets to give the client permission to pass the data to JS.
Remove that header.


What is a "kernel" in plain English?

Question: There are several distinct usages:

kernel density estimation
kernel trick
kernel smoothing

Please explain what the "kernel" in them means, in plain English, in your own words.
Comment: I absolutely hate wikipedia answers for stats. There are rambling, symbolic messes. I am looking for a gem of an answer that can explain the answer in plain English, as I believe that that shows a deeper level of understanding than a math equation. There are many popular "plain English" questions on here, and for good reason.
Comment: Not to be rude, but isn't this a question that is already answered ad nausea on Wikipedia and the likes? Google gave me the answer within 15 seconds...
Answer: There appear to be at least two different meanings of "kernel": one more commonly used in statistics; the other in machine learning.
In statistics "kernel" is most commonly used to refer to kernel density estimation and kernel smoothing.
A straightforward explanation of kernels in density estimation can be found (here).
In machine learning "kernel" is usually used to refer to the kernel trick, a method of using a linear classifier to solve a non-linear problem "by mapping the original non-linear observations into a higher-dimensional space".
A simple visualisation might be to imagine that all of class $0$ are within radius $r$ of the origin in an x, y plane (class $0$: $x^2 + y^2 < r^2$); and all of class $1$ are beyond radius $r$ in that plane (class $1$: $x^2 + y^2 > r^2$). No linear separator is possible, but clearly a circle of radius $r$ will perfectly separate the data. We can transform the data into three dimensional space by calculating three new variables $x^2$, $y^2$ and $\sqrt{2}xy$. The two classes will now be separable by a plane in this 3 dimensional space. The equation of that optimally separating hyperplane where $z_1 = x^2, z_2 = y^2$ and $z_3 = \sqrt{2}xy$ is $z_1 +  z_2 = 1$, and in this case omits $z_3$. (If the circle is off-set from the origin, the optimal separating hyperplane will vary in $z_3$ as well.) The kernel is the mapping function which calculates the value of the 2-dimensional data in 3-dimensional space.
In mathematics, there are other uses of "kernels", but these seem to be the main ones in statistics.
Comment: Very nice! I'm going to use your example with the circle to explain kernel methods, as it is the best visualization I met up til now. Thanks!
Comment: The following video was proposed by an anonymous potential editor as "a great visualisation of what Thylacoleo explained:" http://www.youtube.com/watch?v=3liCbRZPrZA
Comment: Following up Thylacoleo's example using the circle to explain the kernel trick (i don't have enough reputation to add a comment directly to his answer) Was there a simple typo in the equation for the separating hyperplane? and it should be z1 + z2 = r^2, instead of z1 + z2 = 1? Or do I misunderstand? I agree its a nice simple example to illustrate the concept. Thanks. Though the definition of z3 still seems a bit of a mystery, but apparently it doesn't matter for the example centered at the origin.
Comment: Yes there was a typo. Thanks for that Alex. I don't always proofread :-)
Comment: Do we use inner products t o map 2-dimensional data to 3-dimensional?
Answer: In both statistics (kernel density estimation or kernel smoothing) and machine learning (kernel methods) literature, kernel is used as a measure of similarity. In particular, the kernel function $k(x,.)$ defines the distribution of similarities of points around a given point $x$. $k(x,y)$ denotes the similarity of point $x$ with another given point $y$.
Comment: In a way, yes. One way to understand kernel density estimation is that you approximate the density of a point from some distribution as a weighted average of its similarities with a set of points from the distribution. So the notion of similarity does play a role here as well.
Comment: I understand "kernel" in statistics to be borrowed originally from jargon used in discussion of integral equations.
Comment: This is a nice way of putting it. I am wondering if you can generalize this description to also apply to the kernel of 'kernel density estimation'.

What is a "kernel" in plain English?


looking for SharePoint REST API end point to get list view items

Question: we are trying to get SP list view items, means whatever the fields that are enabled in that specific view, those fields(columns) and items.
so what SP REST API end point is helpful
ex:...
to get SP lists: _api/web/lists
to get SP list view: _api/web/getlistbytitle('sampleList')/views
etc... we need SP list view items
Please assist me on how to get list view items.
Comment: would you please provide us with an update on the status of your issue?
Answer: You need to get the ViewQuery for the view and use it to execute a CAML query on the list.
This post on SharePoint StackExchange has details: How to get all items in a view using REST API.
Here's the relevant code snippet from that post:
function getListItems(webUrl,listTitle, queryText)
{
    var viewXml = '<View><Query>' + queryText + '</Query></View>';
    var url = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/getitems";
    var queryPayload = {
               'query' : {
                      '__metadata': { 'type': 'SP.CamlQuery' },
                      'ViewXml' : viewXml
               }
    };
    return executeJson(url,"POST",null,queryPayload);
}

function getListViewItems(webUrl,listTitle,viewTitle)
{
     var url = webUrl + "/_api/web/lists/getByTitle('" + listTitle + "')/Views/getbytitle('" + viewTitle + "')/ViewQuery";
     return executeJson(url).then(
         function(data){
             var viewQuery = data.d.ViewQuery;
             return getListItems(webUrl,listTitle,viewQuery);
         });
}


Recyclerview com analise JSON

Question: Meu código PHP gera o seguinte JSON:
{
"resposta":[
    {
     "cd_servico":"1",
     "ds_servico":"NOME SERVICO",
     "ITEMS":[
        {
          "ds_descricao1":"DESCRICAO SERVICO",
          "ds_descricao2":"DESCRICAO 2",
          "ds_valor":"120.00"
        },
        {
          "ds_descricao1":"DESCRICAO SERVICO",
          "ds_descricao2":"DESCRICAO 2",
          "ds_valor":"65.00"
        }
        ]
    },
    {
      "cd_servico":"2",
      "ds_servico":"SERVICO CATEGORIA 2",
      "ITEMS":[
          {
            "ds_descricao1":"DESCRICAO",
            "ds_descricao2":"DESCRICAO",
            "ds_valor":"90.00"
           }
           ]
      }
  ]

}
Estou tentando ler esse arquivo e listar os itens em um recyclerview, mas sem sucesso.
Segue meu código:
MainActivity.java
StringRequest stringRequest = new StringRequest(Request.Method.POST,
            Connect.URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        JSONArray array = jsonObject.getJSONArray("ITEMS");

                        for (int i = 0; i < array.length(); i++) {
                            JSONObject o = array.getJSONObject(i);
                            ListItem_Result_Parceiro item = new ListItem_Result_Parceiro(
                                    o.getString("cd_servico"),
                                    o.getString("ds_servico"),
                                    o.getString("ds_descricao1"),
                                    o.getString("ds_descricao2"),
                                    o.getString("ds_valor")
                            );
                            listItems.add(item);
                        }
                        adapter = new Adapter_Result_Parceiro(listItems, ResultParceiroFrag1.this.getContext());
                        recyclerView.setAdapter(adapter);
                        RecyclerSectionItemDecoration sectionItemDecoration =
                                new RecyclerSectionItemDecoration(getResources()
                                        .getDimensionPixelSize(R.dimen.header_recyclerview),
                                        true,
                                        getSectionCallback(listItems));
                        recyclerView.addItemDecoration(sectionItemDecoration);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(ResultParceiroFrag1.this.getContext(), "Sem conexão com a internet", Toast.LENGTH_LONG).show();
                }
            }
    ) {

        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> params = new HashMap<>();
            params.put("cd_parceiro", "1");
            params.put("app_chave", chave);//
            return params;
        }
    };//Acão acima envia um post para a url (Somente tipo String)////

    RequestQueue requesQueue = Volley.newRequestQueue(ResultParceiroFrag1.this.getContext());
    requesQueue.add(stringRequest);

Adapter.java
private List<ListItem_Result_Parceiro> listItems;
private Context context;

public Adapter_Result_Parceiro(List<ListItem_Result_Parceiro> listItems, Context context) {
    this.listItems = listItems;
    this.context = context;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.result_parceiro_frag1_list_item, parent, false);
    return new ViewHolder(v);
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    ListItem_Result_Parceiro listItem = listItems.get(position);

    holder.HeadFrag1Parceiro.setText(listItem.getDs_descricao1());
    holder.DescFrag1Parceiro.setText(listItem.getDs_descricao2());
    holder.txtValorServ.setText("R$ "+listItem.getDs_valor());

}

@Override
public int getItemCount() {
    return listItems.size();
}

public class ViewHolder extends RecyclerView.ViewHolder{

    public TextView HeadFrag1Parceiro, DescFrag1Parceiro, txtValorServ;
    public LinearLayout LinearLayout;

    public ViewHolder(View itemView) {
        super(itemView);

        HeadFrag1Parceiro      = (TextView) itemView.findViewById(R.id.HeadFrag1Parceiro);
        DescFrag1Parceiro     = (TextView) itemView.findViewById(R.id.DescFrag1Parceiro);
        txtValorServ     = (TextView) itemView.findViewById(R.id.txtValorServ);
        LinearLayout            = itemView.findViewById(R.id.linearFrag1Parceiro);
    }
}

ListItem.java
public class ListItem_Result_Parceiro {

private String cd_servico;
private String ds_servico;
private String ds_descricao1;
private String ds_descricao2;
private String ds_valor;

public ListItem_Result_Parceiro(String cd_servico, String ds_servico, String ds_descricao1, String ds_descricao2, String ds_valor) {
    this.cd_servico = cd_servico;
    this.ds_servico = ds_servico;
    this.ds_descricao1 = ds_descricao1;
    this.ds_descricao2 = ds_descricao2;
    this.ds_valor = ds_valor;
}

public String getCd_servico() {
    return cd_servico;
}

public String getDs_servico() {
    return ds_servico;
}

public String getDs_descricao1() {
    return ds_descricao1;
}

public String getDs_descricao2() {
    return ds_descricao2;
}

public String getDs_valor() {
    return ds_valor;
}

}
Verifiquei vários exemplos mas não encontrei a solução.
Agradeço desde já a ajuda dos amigos.
Comment: Se possível troque a imagem pelo código.
Comment: Alguma exceção ou erro especifico?
Comment: @CaiqueRomero editei a imagem pelo código.
Comment: @MaxFratane, acredito que o problema esteja na leitura dos "ITEMS", pois se eu modificar no php para gerar o json da seguinte forma: {
 "resposta":[{ "cd_servico":"1", "ds_servico":"NOME SERVICO"}]}, ele funciona bem...
Answer: Seu problema está na leitura do JSON. Você está considerando que o array ITEMS está no primeiro objeto da hierarquia, quando, na verdade, ele está no segundo.
JSONObject jsonObject = new JSONObject(response);

JSONArray resposta = jsonObject.getJSONArray("resposta");
for (int i = 0; i < resposta.length(); i++) {

  JSONObject object = resposta.getJSONObject(i);
  JSONArray items = object.getJSONArray("ITEMS");
  for (int j = 0; j < items.length(); j++) {
    JSONObject o = items.getJSONObject(j);
    ListItem_Result_Parceiro item = new ListItem_Result_Parceiro(
        o.getString("cd_servico"),
        o.getString("ds_servico"),
        o.getString("ds_descricao1"),
        o.getString("ds_descricao2"),
        o.getString("ds_valor")
    );
    listItems.add(item);
  }
}

Recomendo que você estude bibliotecas para conversão de JSON, como Gson e Moshi. Com elas você consegue converter objetos JSON para POJOs, facilitando seu trabalho e evitando este tipo de confusão.
Comment: Obrigado pela dica Leonardo, o código que vc postou funciona se eu retirar os itens "cd_servico" e "ds_descricao" que no caso estão fora do array "ITEMS", esse item "ds_descricao" eu queria que ficasse como cabeçalho no recyclerview dos itens que estão dentro do array "ITEMS".

Recyclerview com analise JSON


Envelope of Lines

Question: Its been a while that I'm stuck with an apparently "simple" problem. My goal is to build the envelope of a set of lines that are "attached" to a curve. Let's say a curve like this:

For the above example I would expect the envelope of lines (whose directions are depicted by arrows and are orthogonal to the edges of the red curve) to be an arc of a circle.
I thought of doing this in two computationally separate ways:

Intersection of consecutive lines: In an ideal smooth world, the envelop of lines attached is a curve where the red lines are all tangent to. Now, coming back to the discrete world I try to obtain the envelope curve by intersecting consecutive lines (for example the first line with the second line would give the first vertex of the envelope).
Evolute of the red curve: Again in an ideal smooth world, one can think of such an envelop as the evolute of the red curve (see Evolute - wikipedia). Therefore, all I had to do in addition to current info was to compute the curvature and then build the evolute (naturally I had to use a discrete version of curvature which you can find its definition here: Discrete Curvature - wikipedia).

Doing any of the above approaches I would get the following result:

However, finding the "correct arc" is heavily dependent on the accuracy of the initial data which is the red curve. As soon as the red curve has some "noises" in the vertices the envelope is heavily distorted. Here I add a picture (where the red curve is visually intact (but not actually) yet the envelope is distorted):

My Question: How can I rectify this? I believe there should be a numerical approach to solve this issue as I badly need this envelope to be correctly built. I'm a mathematician and am not fully aware of the numerical tricks that might exist in dealing with cases like this.
However, I believe that this should be a standard question in computer graphics community though I could not find anything properly relevant after searching for months.
It would be great if the solutions are in MATLAB language. Please let me know if you want me to be more accurate regarding the passage.
Comment: see [draw outline for some connected lines](https://stackoverflow.com/a/22068534/2521214)
Comment: Are you asking for an offset curve from the original, where every point is set distance away?
Comment: At this point in time I am not sure what might be best without seeing the data. So  as a start if you can provide the  data you are using to calculate the lines and the code you are using calculate the intersection points  for, perhaps, 40 lines.
Comment: My comment above was meant to be a follow up comment to my request below.
Comment: Do you have a description of the slope of the curve, or how its changing or is it just points? Either way, you can fit a cubic spline and get the slope information, which means you can get the normal direction and thus calculate the offset curve points.
Answer: For the line intersecton method, yes, because the lines are relatively parallel, any small error in the defining data for a line will produce a dramatic error in their intersection points.
I suggest the following:

Calculate all lines.
Calculate all intersection points of the adjacent lines.
Calculate the distances between all adjacent intersection points.
Sequence plot the distances, and identify all distances which are more than,
perhaps, 2 standard deviations from the trend line of the distances.
If the data is not "too bad" then I think the identified distances
will mostly come in pairs, ie, there is one "bad" intersection line
causing two "bad" distances.
Exclude the "bad" lines and reprocess the remaining intersection points.

The above assumes the granularity of the data is greater where the base curve is curvier.
If the intersection point distances seem to form two trend lines, especially if they look like to two diverging, or two converging, trend lines, then group the intersection lines accordingly, plot two envelopes, and take the average of the two envelopes as "the envelope". (Or perahps even more trend lines, if there is a regular error in the data.)
But, if there are signs of regular data errors, then a contextual assessment and analysis of the data source and how it was generated/gathered/measured might be required to correctly determine which data should be excluded.
Comment: If you can provide some data I will try to look at MATLAB too.

Envelope of Lines


What is $\widehat{G}$ here in transfer kernel?

Question: I'm reading a paper by A. WEISS and K.W. GRUENBERG "Captilulation and transfer kernels"
(Can be found here.)
It says:

It used $\widehat{G}$ to denote norm map $m\mapsto \sum_g gm$ for some $G$-module $M$ before, but doens't seem to be the case here.
I find some conventions denoting $\widehat{G}$ as a character of the group, but this is a map $G\rightarrow \mathbb C^{\times}$ and seems only restricted to abelian groups.
So what is the definition of $\widehat{G}$ in $\Lambda$? It never states it in the paper.
Answer: I think it's just $\hat{G}=\sum_{g\in G}g$. So you would have $\Lambda = \mathbb{Z}G/\hat{G}\mathbb{Z}$.
There's a newer paper that's typeset a little better you may be interested in looking at.
Comment: Is it obvious that $\Lambda_G = \mathbb Z/|G|\mathbb Z$? Or is there some references?


Is there any difference between a soprano trombone and a slide trumpet?

Question: Occasionally, I will see people arguing about whether an instrument should be called a "soprano trombone" or a "slide trumpet" yet I have never seen any instrument designated as one as being any different from an instrument designated as the other.
Is there any reason these terms are not interchangeable, or that one or the other is not appropriate to refer to this instrument?
Answer: The first answer above by NReilingh covers the physical appearance of the instruments but there is also an acoustic difference.
A Slide trumpet has a large bore of .460-.470" and is played using a trumpet mouthpiece. It also has a long tapered lead-pipe inside the upper tube just like any other trumpet.
A Soprano trombone has a more trombone like smaller bore of around .420-.430" and the better ones use a smaller shank mouthpiece like a modern cornet. That mouthpiece should have a deeper cup and larger throat than a trumpet mouthpiece. It will have either no tapered lead-pipe or a short one with little taper as it is with trombones.
That said, if the modern trumpet did not change and evolve to it's present large bore version but stayed smaller bore with little to no lead-pipe, like they were in the 19th century, then there would be no real difference between the two in acoustics.
The sound of the two instruments is not the same. The trumpet is brighter and blasts louder and harsher then the trombone.
I play both instruments but usually prefer the Soprano trombone over the Slide trumpet both for ease of playing and sound.
It's a shame that many trumpet makers market their Slide trumpets as mini trombones or something like that. They are in fact clouding the issue. Most of the time they are quite ignorant that there is a difference.
By the way, the Eb sopranino trombones do not play any higher than the Bb soprano, so they do not contribute other than the novelty of them. There is also a very cute Bb Piccolo trombone.
Answer: The best definitions in my opinion (and after some considerable research) are:

A trumpet has a mouthpiece and bell that are located at opposite ends of the instrument.
A trombone is defined by a bell section that is located to the rear of the instrument, with a mouthpiece located near the center of gravity and grip location.

Thus, the trumpet will be held in front of the body, while the trombone will be supported closer to the player's center of gravity.
The instrument pictured (as well as any other instruments with a similar shape) is therefore a type of trombone. It happens to play in the same range as a Bb trumpet, but an instrument's name is not defined by its playing range.
The soprano trombone in particular has been historically referred to as a slide trumpet in certain cases, (it was a novelty of Louis Armstrong's) however, the name slide trumpet more accurately refers to certain natural trumpets in the Medieval through Baroque periods that had slide elements to their construction. In this context, the slide trumpet was a variation on a natural trumpet that used a small hand slide or sliding lead pipe to adjust which harmonic series the instrument was playing in, therefore increasing possibilities of chromaticism in trumpet playing.

http://en.wikipedia.org/wiki/Slide_trumpet
http://www.youtube.com/watch?v=Q5xEGS2GZyQ
http://www.youtube.com/watch?v=NHwVtOJV5IA

Many people will incorrectly refer to a soprano trombone as a slide trumpet because:

It is most often played by trumpeters.
It has a tone almost identical to a standard Bb valve trumpet.
The baroque slide trumpet is all but extinct.

Those who wish to pick nits are thus technically correct in doing so, but it's largely a pedantic distinction.
Comment: Got any images describing what you mean in your first two points?
Comment: @naught101 Just Google image search 'trumpet' and 'trombone' -- should be pretty self-explanatory given my descriptions.
Comment: Well, a [google image search](http://www.google.com/search?q=slide+trumpet&tbm=isch) returns images that are almost all soprano trombones, by your definition, apart from a couple of slide valved trumpets, and [some really old slide trumpets](http://www.crispiansteeleperkins.com/#/instruments/4545214560). Obviously some [instrument](http://www.samash.com/p/Jean%20Baptiste_JBSTP181%20Slide%20Trumpet_-49950655) [makers](http://www.kanstul.net/detail.php?pass_search=140&pass_instrument=Trumpet) are selling their soprano trombones as slide trumpets...
Comment: @naught101 That's my point--you should decide if an instrument truly is a trumpet or a trombone based on its construction. The reference images I suggested you google for would be vanilla [trumpet](http://www.google.com/search?q=trumpet&tbm=isch) or [trombone](http://www.google.com/search?q=trombone&tbm=isch). The images and YouTube links already included in the question and answer can supply less obvious examples.
Answer: I believe a lot of the kerfuffel is related to the fact that there are strong opinions and some sore toes around. No trumpet player wish to play the trombone and vice versa. The fact of the matter is that the sopranino trombone is fairly rare and there isn't a lot of material for it.
This means that there is also few sources to refer to when "trying to settle" this aged old debate.
In my own opinion, the sopranino trombone is perhaps where the slide trumpets and the "more regular" trombones meet in terms of size, pitch, etc. However, the mechanics of the instrument is still squarely in the trombone camp in the same way that keyed trombones are often regarded as in the bass trumpet camp...
Comment: Soprano ≠ Sopranino: A sopranino trombone would be in the range of a piccolo trumpet.
Comment: Wikipedia (untrustworthy as always) lists "The range of the E♭ sopranino trombone is A3 to E♭6; that of the B♭ piccolo trombone is E4 to F7." which is actually more or less the same as a trumpet (E3-*6)
Answer: As a trombone player I believe that it I a soprano trombone and a valve trombone. A bass trumpet is actually more like a baritone intact a baritones true name is baritone trumpet so with the shape of the other two they must both be considered trombones
Comment: I wasn't asking about the valve trombone and bass trumpet. Those two instruments are very well defined. I disagree that a baritone horn is the same as a baritone trumpet--logically, that instrument would be smaller than a bass trumpet, and furthermore, there are NO reliable results on Google for an instrument with that name.
Answer: It is much less the mechanics and shape of the instrument. It should be based off of its origins as a variation of the trumpet by Flemish musical inventors. This gives the origin to the trombone. As it evolved it became lower pitched. But this instrument as it is should be referred to as a slide trumpet.


Circular dependency between declaration of struct and function pointer

Question: I have a struct which has a function pointer as a member variable. The function pointer takes a pointer to the struct as one of its parameters.
By looking at solutions posted on here for such circular dependencies I used a forward declaration to be able to compile.
I still have the problem of not being able to initialize the struct. Posted below is the code and the output.
edit: My earlier MVCE didn't reproduce the problem correctly. I can get this to compile by naming the struct instead of just having a struct alias. Not exactly sure why though.
#include "stdio.h"

//Forward declaration
struct data;

typedef int(*funcPtr) (struct data* a);

typedef struct
{
    int a;
    int b;
    funcPtr foo;
}data;

int foo(data* pData)
{
    return 0;
}

static data testData[] = {{1,1,foo}, {0,2,foo},};

int main()
{
    printf("Just trying to compile this program\n");
    return 0;
}

Error output --
compileError.c:20:1: warning: initialization from incompatible pointer type [enabled by default]
static data testData[] = {{1,1,foo}, {0,2,foo},};
^
compileError.c:20:1: warning: (near initialization for \u2018testData[0].foo\u2019) [enabled by default]
compileError.c:20:1: warning: initialization from incompatible pointer type [enabled by default]
compileError.c:20:1: warning: (near initialization for \u2018testData[1].foo\u2019) [enabled by default

Comment: Side note: It doesn't show in your example code, but your struct isn't `struct data`. It is an unnamed struct type-aliassed to `data`.
Comment: Your `typedef struct { … } data;` defines an alias `data` for an untagged structure type.  That type is unrelated to the `struct data` you mentioned earlier.  You need `typedef struct data { … } data;` to get the code to compile.  As amended, this is a duplicate of quite a lot of other questions.  Understanding `struct tag { … }` vs `typedef struct { … } tag` seems to be a fairly common problem.
Comment: This actually solved the problem I had in my original code. This MVCE code just had a typo which led to other answers. Thank you!
Answer: Function foo is incompatible with funcPtr - it returns an int, not a void.
Also, your variable is declared as an array, but you initialize it with a single value - remove the [].
Comment: You can have arrays with one element, but you should fully brace your initializer: `data testData[] = { { 1, 1, foo }, };`.  This may be a side-effect of converting the real program into an MCVE.
Comment: @JonathanLeffler - It seems to me an array was not intentionally used here.
Comment: Yeah I should have probably used multiple values. My real program uses an array.
Comment: @coder_mario: ideally, you would have indicated that you intended an array by using the extra level of braces, or a comment such as `/* ... */` after the elements you provided. You did a good job on minimization; almost too good.
Comment: Thanks, though this MVCE kinda induced its own bug which didn't let me totally reproduce the issue I had. The comment on the question actually led me to the fix.
Answer: You define an array of struct data but initialize it with just one element. If this was unintentional, remove '[]':
data testData = {1,1,foo};

If an array is needed, initialize with a fully-braced array initializer:
data testData[] = { {1,1,foo} };

Also, check your member function signature. The declaration and the implementation should both return either void or int.


jQuery trigger event when form field is validated

Question: I'm trying to trigger a function to update the CSS of a progress bar...

But only after a field has been validated by the formValidation plugin (formvalidation.io)
$('form').formValidation({
    framework: 'bootstrap',
    fields: { ... }
});

When a field is validated, formValidation adds the has-success class to the field. I have created a function to count how many fields have this class, calculate a percentage width for the progress bar and update the CSS
$('.form-control').on('change keydown', function(){
    var fields = 9;
    var completedFields = $('.has-success').length;
    var percent = (completedFields / fields) * 100;
    $('.progress-bar').css('width', percent + '%');
});

The problem is, this only triggers after the second character is added into a text field or after a select is changed twice. I presume this is because the function fires before the has-success class has been added.
Is there another way to go about this?
Comment: use keypress instead of keydown
Answer: You could listen to the error and success event after validation to trigger an update of the progress bar.
See: http://formvalidation.io/settings/#event-form
.on('err.form.fv', function(e) {
  // The e parameter is same as one
  // in the prevalidate.form.fv event above

  updateProgressBar();
})

.on('success.form.fv', function(e) {
  // The e parameter is same as one
  // in the prevalidate.form.fv event above

  updateProgressBar();
})

PS: Why don't you use the getInvalidFields() method the plugin offers to count the number of invalid fields?


Recoverable fatal error when trying to run hook_query_TAG_alter()

Question: I used the approach provided here to reverse comments order in Drupal 8:
<code>    /** Implements hook_query_TAG_alter().
 *
 * Alter comments query to order by DESC as well as the default ASC.
 */
function MYMODULENAME_query_comment_filter_alter(QueryAlterableInterface $query) {
  $orderby = &$query->getOrderBy();

  // Sorting for threaded comments.
  if (isset($orderby['torder'])) {
    // Sort by root parent first, then normal threaded.
    $query->addExpression("SUBSTRING_INDEX(c.thread, '.', 1)", 'rparent');
    $orderby = array('rparent' => 'DESC') + $orderby;
  }
  // Sorting for flat comments.
  else if (isset($orderby['c.cid'])) {
    $direction = 'DESC';

    $orderby['c.cid'] = $direction;
    $orderby = array('c.created' => $direction) + $orderby;
  }
}
</code>
but I receive the followig error when run the module:

Recoverable fatal error: Argument 1 passed to
  mymd_query_comment_filter_alter() must be an instance of
  QueryAlterableInterface, instance of
  Drupal\Core\Database\Query\PagerSelectExtender given, called in
  D:\wamp95\www\drupal83\core\lib\Drupal\Core\Extension\ModuleHandler.php
  on line 501 and defined in mymd_query_comment_filter_alter()

what is the problem and how should I solve it?
Comment: I think I should use: Drupal\Core\Database\Query\AlterableInterface $query as argument.
Answer: I used Drupal\Core\Database\Query\AlterableInterface $query as argument.
It solved the problem.
Comment: Yes see the docs. It should be AlterableInterface. https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Database%21database.api.php/function/hook_query_TAG_alter/8.2.x
Comment: Yes, you need to use "AlterableInterface" instead of "QueryAlterableInterface".

`use Drupal\Core\Database\Query\AlterableInterface;
function MYMODULENAME_query_comment_filter_alter(AlterableInterface$query) {
//.....
}`


Erro depois de chamar o Evento

Question: Depois de chamar o Evento de clique no botão, o cálculo aparece sem resultado e o HTML que inseri através do JS some da tela logo após a chamada. PS: Ignore o CSS em desenvolvimento!

/*
    Forma de fazer números aleatórios em um intervalo;

    const num1 = 5
    const num2 = 10

    console.log(Math.floor(Math.random() * (num2 - num1)) + num1)
*/

// Pegar os dois números e inserir no cálculo ---------------------------------

const number1 = document.querySelector("#sorteador1").value
const number2 = document.querySelector("#sorteador2").value
const resultHtml = document.querySelector("#result")
const btn = document.querySelector("#btn")
let calculo = Math.floor(Math.random() * (number2 - number1)) + number1

//Evento de clique no Botão "Sortear" -----------------------------------------

function lucky() {
    return resultHtml.innerHTML = `<h3>O número sorteado foi: ${calculo}</h3>`
}

btn.addEventListener("click", lucky)
:root {
    --color-header-bg: #f8dbc9;
    --color-font: #033d68;
}

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    background-color: #ffe7d9;
}

header {
    background-color: var(--color-header-bg);
    border-bottom: 2px solid var(--color-font);
    padding-bottom: 15px;
}

img {
    transform: translateX(900px);
    border-radius: 30%;
    box-shadow: 3px 2px 0px 4px #F2D4C2;
}

form {
    text-align: center;
    margin: 205px 500px;
    padding: 30px 50px;
    border: 3px solid var(--color-font);
    border-radius: 5px;
    box-shadow: 3px 2px 0px 4px #F2D4C2;
    background-color: var(--color-header-bg)
}

span {
    font-size: 80px;
    font-weight: bold;
    color: var(--color-font);
    text-transform: uppercase;
    text-shadow: 5px 3px 0px #F2D4C2;
}

input {
    border: 1px solid var(--color-font);
    border-radius: 4px;
    height: 80px;
    padding-top: 40px;
}

button {
    border: 3px solid var(--color-font);
    border-radius: 4px;
    background-color: #fff;
    height: 80px;
    width: 790px;
    margin-top: 15px;
    text-align: center;
    position: absolute;
    top: 570px;
    left: 570px;
}

.sortear {
    font-size: 75px;
    font-weight: bold;
    color: var(--color-font);
    text-transform: uppercase;
    cursor: pointer;
}

button:hover {
    background-color: #F2D4C2;
    box-shadow: 3px 2px 0px 4px #F2D4C2;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="shortcut icon" href="Imagem/SORTEADOR-FAVICON.png" type="image/x-icon">
    <link rel="stylesheet" href="style.css">
    <title>Sorteador</title>

        <form id="formulary">
            Sortear de
                <input type="number" id="sorteador1" name="num1" min="1" max="10000">
             a
                <input type="number" id="sorteador2" name="num1" min="1" max="10000">
        </form>

        <button form="formulary" id="btn">
            Sortear</spa>
        </button>

Answer: Olá!
Bom, dois pontos principais:
Quanto a atualização da página, por padrão, o clique no botão criava um submit no seu formulário. Para impedir isso, no evento de clique do botão é necessário incluir um preventDefault();
Mais sobre o preventDefault(): https://www.w3schools.com/jsref/event_preventdefault.asp
Com relação a execução do sorteio, o código que pegava os valores e fazia o cálculo estava sendo executado quando a página era carregada, antes de o usuário colocar os valores ou apertar o botão. Nesse caso como você precisa dele apenas depois do preenchimento e do clique, ele deve ser chamado com o evento do clique.
Nesse caso, coloquei ele dentro da sua função lucky para testar. Para organizar mais seu código, você pode separar ele dentro de outra função depois.
Segue o código modificado abaixo

/*
    Forma de fazer números aleatórios em um intervalo;

    const num1 = 5
    const num2 = 10

    console.log(Math.floor(Math.random() * (num2 - num1)) + num1)
*/

//Evento de clique no Botão "Sortear" -----------------------------------------

function lucky(event) {

    event.preventDefault();

    // Pegar os dois números e inserir no cálculo ---------------------------------
    const number1 = parseInt(document.querySelector("#sorteador1").value);
    const number2 = parseInt(document.querySelector("#sorteador2").value);
    const resultHtml = document.querySelector("#result");
    const btn = document.querySelector("#btn");
    let calculo = Math.floor(Math.random() * (number2 - number1)) + number1;

    return resultHtml.innerHTML = `<h3>O número sorteado foi: ${calculo}</h3>`
}

btn.addEventListener("click", lucky)
:root {
    --color-header-bg: #f8dbc9;
    --color-font: #033d68;
}

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    background-color: #ffe7d9;
}

header {
    background-color: var(--color-header-bg);
    border-bottom: 2px solid var(--color-font);
    padding-bottom: 15px;
}

img {
    transform: translateX(900px);
    border-radius: 30%;
    box-shadow: 3px 2px 0px 4px #F2D4C2;
}

form {
    text-align: center;
    margin: 205px 500px;
    padding: 30px 50px;
    border: 3px solid var(--color-font);
    border-radius: 5px;
    box-shadow: 3px 2px 0px 4px #F2D4C2;
    background-color: var(--color-header-bg)
}

span {
    font-size: 80px;
    font-weight: bold;
    color: var(--color-font);
    text-transform: uppercase;
    text-shadow: 5px 3px 0px #F2D4C2;
}

input {
    border: 1px solid var(--color-font);
    border-radius: 4px;
    height: 80px;
    padding-top: 40px;
}

button {
    border: 3px solid var(--color-font);
    border-radius: 4px;
    background-color: #fff;
    height: 80px;
    width: 790px;
    margin-top: 15px;
    text-align: center;
    position: absolute;
    top: 570px;
    left: 570px;
}

.sortear {
    font-size: 75px;
    font-weight: bold;
    color: var(--color-font);
    text-transform: uppercase;
    cursor: pointer;
}

button:hover {
    background-color: #F2D4C2;
    box-shadow: 3px 2px 0px 4px #F2D4C2;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="shortcut icon" href="Imagem/SORTEADOR-FAVICON.png" type="image/x-icon">
    <link rel="stylesheet" href="style.css">
    <title>Sorteador</title>

        <form id="formulary">
            Sortear de
                <input type="number" id="sorteador1" name="num1" min="1" max="10000">
             a
                <input type="number" id="sorteador2" name="num1" min="1" max="10000">
        </form>

        <button form="formulary" id="btn">
            Sortear</spa>
        </button>

Abraço!

Erro depois de chamar o Evento


Which is a best Tag Cloud plugin to work with jquery?

Question: Which is the best tag cloud plugin to work with jquery?
Answer: http://benalman.com/code/projects/jquery-sphere3d/examples/tag-cloud/
Comment: How to use this plugin(Installation features)
Answer: I wrote a simple center weighted one the other day.
http://blog.onnerby.se/p/jdoecloud.html


Why does list.append() return None?

Question: I am trying to calculate a postfix expression using Python, but it did not work. I think this is maybe a Python-related problem.
Any suggestions?
expression = [12, 23, 3, '*', '+', 4, '-', 86, 2, '/', '+']

def add(a,b):
    return a + b
def multi(a,b):
    return a* b
def sub(a,b):
    return a - b
def div(a,b):
    return a/ b

def calc(opt,x,y):
    calculation  = {'+':lambda:add(x,y),
                     '*':lambda:multi(x,y),
                     '-':lambda:sub(x,y),
                     '/':lambda:div(x,y)}
    return calculation[opt]()

def eval_postfix(expression):
    a_list = []
    for one in expression:
        if type(one)==int:
            a_list.append(one)
        else:
            y=a_list.pop()
            x= a_list.pop()
            r = calc(one,x,y)
            a_list = a_list.append(r)
    return content

print eval_postfix(expression)

Comment: Totally unrelated to your question but 1/ you may want to read the doc for the `operator` module, and 2/ in your `calc` function you don't need lambdas at all - just map to the operator functions and pass arguments at call time, ie : `{"+": add, "-":sub,}[opt](x, y)`. This will also allow you to define the mapping globally hence avoiding building it again and again on each call to `calc`.
Comment: @brunodesthuilliers ,thanks, that`s wondeful!!!
Answer: Just replace a_list = a_list.append(r) with a_list.append(r).
Most functions, methods that change the items of sequence/mapping does return None: list.sort, list.append, dict.clear ...
Not directly related, but see Why doesn't list.sort() return the sorted list?.
Comment: Your link to the FAQ about the `list.sort()` method is very relevant. We can easily understand why append does not return a new list but directly modify the argument. (+1)
Comment: I disagree with `sorted`. It returns the sorted list.
Answer: The method append does not return anything:
>>> l=[]
>>> print l.append(2)
None

You must not write:
l = l.append(2)

But simply:
l.append(2)

In your example, replace:
a_list = a_list.append(r)

to
a_list.append(r)

Comment: thank you very much for your quick answer and related discussion.there is only one gree V I can click,,,
Answer: For return data on append use:
b = []
a = b.__add__(['your_data_here'])

Comment: That's nice  - and i just replace `.append` with .__add__` in my code. It's a PITA that these `list` methods are not chainable.   What would be the analogous equivalent of `.extend` ?
Answer: append function mutates the list and it returns None. This is the piece of code which does that http://hg.python.org/cpython/file/aa3a7d5e0478/Objects/listobject.c#l791
listappend(PyListObject *self, PyObject *v)
{
    if (app1(self, v) == 0)
        Py_RETURN_NONE;
    return NULL;
}

So, when you say
a_list = a_list.append(r)

you are actually assigning a_list with None. So, the next time when you refer to a_list, it is not pointing to the list but the None. So, as others have suggested, change
a_list = a_list.append(r)

to
a_list.append(r)

Answer: Functions like list.append(),list.sort() don't return anything.
e.g
def list_append(p):
    p+=[4]

function list_append doesn't have an return statement.so when you run following statements:
a=[1,2,3]
a=list_append(a)
print a
>>>None

but when you run following statements:
a=[1,2,3]
list_append(a)
print a
>>>[1,2,3,4]

That's it.so,hoping it can help you.
Answer: List methods can be divided in two types those who mutate the lists in place and return None (literally) and those who leave lists intact and return some value related to the list.
First category:
append
extend
insert
remove
sort
reverse

Second category:
count
index

The following example explains the differences.
lstb=list('Albert')
lstc=list('Einstein')

lstd=lstb+lstc
lstb.extend(lstc)
# Now lstd and lstb are same
print(lstd)
print(lstb)

lstd.insert(6,'|')
# These list-methods modify the lists in place. But the returned
# value is None if successful except for methods like count, pop.
print(lstd)
lstd.remove('|')
print(lstd)

# The following return the None value
lstf=lstd.insert(6,'|')
# Here lstf is not a list.
# Such assignment is incorrect in practice.
# Instead use lstd itself which is what you want.
print(lstf)

lstb.reverse()
print(lstb)

lstb.sort()
print(lstb)

c=lstb.count('n')
print(c)

i=lstb.index('r')
print(i)

pop method does both. It mutates the list as well as return a value.
popped_up=lstc.pop()
print(popped_up)
print(lstc)

Answer: just a thought, instead of those functions (which manipulates the actual data) returning None, they should have returned nothing.
Then atleast the user would have caught the issue as it would have throwed an error stating some assignment error!!
Comment your thoughts!!
Comment: In Python "returning nothing" means returning `None`.
Answer: Just in case somebody ends here, I encountered this behavior while trying to append on a return call
This works as expected
def fun():
  li = list(np.random.randint(0,101,4))
  li.append("string")
  return li

This returns None
def fun():
  li = list(np.random.randint(0,101,4))
  return li.append("string")

Why does list.append() return None?


Sending keystrokes using plink

Question: I'd like to execute a set of commands on a cisco device:
conf terminal
ip scp server enable

When performed manually using putty, this works fine. I'm trying to do the same using plink, but have been unsuccessful.
Attempt 1
plink -ssh firstname.lastname@example.com "conf terminal; ip scp server enable"

Attempt 2
plink -ssh email@example.com -m script.sh

It appears that an "Enter" keystroke must be sent after the configure terminal command. Others. have used VBScript to send the keystroke. Is it possible to do this natively in plink instead?
Answer: try using ' < ' insted of -m parameter.
The final command will look like this
plink -ssh firstname.lastname@example.com -pw password_something < do-stuff.txt  > output.txt

In this case, your do-stuff.txt can contain multiple lines and Newslines (Enter).
Answer: to avoid the "Enter" keystroke, you can add the -batch option :
plink -ssh firstname.lastname@example.com -batch "conf terminal; ip scp server enable"

Sending keystrokes using plink


What type of data analysis (ANOVA) should I run on this experiment?

Question: I am not sure how I would analyse this data:
The experiment is looking at the accuracy of emotion recognition in children with ADHD.  The children will be asked to identify what emotion a face is portraying (out of 6 expressions; happiness, sadness, fear, anger, disgust and neutral).  They will firstly be shown the photographs and asked to identify the emotion, then they will be instructed to focus on the eyes and asked to identify the emotions and then asked to focus on the mouth. (three conditions- free gaze, eye gaze and mouth gaze). The experiment involves 2 groups of participants, ADHD children and matched controls.  The DV is accuracy of emotion recognition.
How would I analyse this, would this be a repeated measures ANOVA to compare accuracy of emotion recognition by participant group (ADHD or controls) gaze condition (free, eye, mouth) and emotion type?  I think this will determine whether there was a significant difference in the accuracy of identifying emotions in the difference gaze conditions and types of emotion portrayed.  And  if significant, follow up Bonferroni tests will be conducted to show which emotions were recognised the least accurately?  t tests? planned comparisons? Im not too sure what design this is or what type of ANOVA should be conducted.  Would I do seperate ANOVAs for each emotion?  I am a bit confused!
Comment: could you post a graph of the distribution of the DV?  That would help me/us suggest the best test.
Answer: The form of your data is going to be a table giving each emotion three times (once for each gaze instruction) as columns two rows, control and ADHD, and the entries being the number of kids who got that identification correct (assuming the total number of children allocated to each group is identical). Do I have that right? If so, then you're looking at a contingency table. Here's a nice introduction.
But now we need to know exactly what hypotheses you want. The simplest one is just 'The children with ADHD correctly identify emotions less well than the children without.' Then you would just run your contingency table saying that the null hypothesis is that the two rows in each column have, on average, the same number of counts.
However, you probably want to pull apart more than that. Perhaps you also want to know whether different gaze instructions help more. You can just run the table again, but this time taking the three gaze types as the rows and the two groups of children for each emotion as additional columns.
Also, you can do much better than Bonferroni for corrections. Bonferroni makes no assumptions whatsoever about the hypotheses, so it's the most conservative possible use. Look into stepdown methods, or for hypotheses that are probably independent such as gaze instructions being helpful vs ADHD kids doing better or worse (are they independent? that's a theoretical question for the domain specialist) you can at least use the Šidák correction, which is far more powerful.
Answer: doing one anova for each emotion is a good idea. You might also want to check if any or both groups recognize emotions better than would be expected by chance, which might be accomplished by binomial tests or chisquare.
come to think about it, you could also do risk estimates and binomial regressions; how more, or how less, likely it is to recognize emotion if you have ADHD.


WPF - Columns don't hide properly when GridSplitter is moved

Question: I'm trying to hide a column in a Grid with a GridSplitter when a button is clicked (the button sets the visibility of all items in the third column to collapsed). If I don't move the GridSplitter it works properly and the third column disappear, but if I move the GridSplitter the content disappear but the others columns don't resize to fill the empty space.
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition Height="25"/>
    </Grid.RowDefinitions>

    <Grid.ColumnDefinitions>
        <ColumnDefinition x:Name="a" Width="*"/>
        <ColumnDefinition x:Name="b" Width="3"/>
        <ColumnDefinition x:Name="c" Width="Auto" MaxWidth="600"/>
    </Grid.ColumnDefinitions>
    <Border Grid.Column="0" Grid.Row="0" HorizontalAlignment="Stretch" Background="Green">
        <Image Source="te/Dante.png" Height="Auto" Margin="0,128,2,71"/>
    </Border>
    <Button Grid.Column="0" Grid.Row="0" Width="30" Height="30" Margin="0,10,10,0" HorizontalAlignment="Right" VerticalAlignment="Top" Click="Button_Click"></Button>
    <GridSplitter Width="5" Grid.Column="1" Grid.Row="0" Grid.RowSpan="2" ResizeDirection="Columns" HorizontalAlignment="Left" Background="White" BorderBrush="Black" BorderThickness="1,0" ResizeBehavior="PreviousAndCurrent"/>
    <WrapPanel x:Name="wpC" Grid.Column="2" Grid.Row="0" Grid.RowSpan="2" MinWidth="300" HorizontalAlignment="Stretch" Background="Aqua" Panel.ZIndex="-1"></WrapPanel>
</Grid>

Here is an example of my problem (gif):

How can i solve this problem? Possibly respecting MVVM pattern.
Comment: Show how exactly you *hide* something? Using `x:Name` is already not pure MVVM (I am assuming you are setting column definition width in code behind). Btw, you can use [ScreenToGif](https://screentogif.codeplex.com/) and capture few frames to demonstrate issue, see [my question](http://stackoverflow.com/q/36915180/1997232).
Comment: i've added the gif, up to now i made a solution using code behind. i would like to know if there is a way to solve this problem without using code behind
Answer: The problem is simple, you set GridSplitter ResizeBehavior="PreviousAndCurrent", but previous grid column width is * and as soon as you move splitter its width units will be changed to absolute (so it will not be able to resize when 3d column width is changed).
Simply set GridSplitter ResizeBehavior="PreviousAndNext" to solve the problem. If you do so the splitter will modify width of 3d column, but shouldn't touch first one anymore.
Btw, instead of using button and click event you can utilize ToggleButton (which IsChecked is bound to Visibility of container with content you want to hide), see this answer. Using converters with pure xaml view is better MVVM than the one with some code behind and x:Name.

Right, you have few layout problems, here is a complete solution:
<Window.Resources>
    <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
</Window.Resources>
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition />
        <ColumnDefinition Width="Auto" />
    </Grid.ColumnDefinitions>
    <Border Background="Green" />
    <ToggleButton x:Name="toggleButton"
                  Width="30"
                  Height="30"
                  Margin="0,10,10,0"
                  HorizontalAlignment="Right"
                  VerticalAlignment="Top" />
    <Grid Grid.Column="1"
          Visibility="{Binding IsChecked, ElementName=toggleButton, Converter={StaticResource BooleanToVisibilityConverter}}">
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
            <ColumnDefinition Width="300"
                              MinWidth="300"
                              MaxWidth="600" />
        </Grid.ColumnDefinitions>
        <GridSplitter Width="5"
                      ResizeBehavior="CurrentAndNext" />
        <WrapPanel Grid.Column="1"
                   Background="Aqua" />
    </Grid>
</Grid>

No need for code-behind, get converter from here.
Point are: 1) put splitter inside hide-able container 2) setup grid columns to have * and fixed width (splitter doesn't work well with auto columns).
Demo:
Comment: i setted ResizeBehavior to PreviousAndNext but it doesn't solve the problem. it seems that the 3rd column width change from Auto to a value and that value is kept even if the Visibility is setted to Collapsed.
I tried other ResizeBehavior but nothing works.
Comment: i'd never thought of turning this originally obvious 3 columns (or 3 rows) into nested ones this way.  this is *so much easier* than other things i was trying to do!
Comment: Thank you for helping me with the same issue (but with rows). Seems like there are many ways to attempt this, but this is much the cleanest solution (and not exactly obvious!)


MinHashing and Hash Digests/Signatures

Question: Nilsimsa and SimHash are two similarity hash algorithms that produce a single hash digest/signature per document. Comparing two documents is as simple as computing the hamming distance between two hash digests/signatures. Neither algorithm needs to know about other documents when computing a hash for any given document.
I've been looking for more algorithms that work this way. I came upon MinHash (AKA min-wise independent permutations) which on the surface appears to have these characteristics but everything I read says it needs a collection of documents in order to compute the hashes for any document in the collection. Is this correct? Is there anyway to get a single hash for a single document independent of the rest of the documents in the collection using MinHash?
Answer: That's not correct. MinHash is a function whose domain a set of elements (a single document) and whose range is a vector of integers (the digest or sketch). The MinHash of a single document is independent of all other documents that you may consider.

MinHashing and Hash Digests/Signatures


How do I cycle through a linked list to reduce a value?

Question: I have a class called SensorNode, which contains (among other things) a linked list of sensor objects.  The node has a data member for the amount of battery power it has left, and the sensors each have a data member for how much power they draw.  I have a function called processTimeClick that is supposed to go through the entire linked list of sensors in the node, and subtract the amount of power that they use from the battery that the node has left.  Unfortunately I get an "Error, bad access code" and I don't know why.  Here's the function I have, I was hoping someone could see where my logic is wrong.
void SensorNode::processTimeClick() {
    if (batt == 0) {

    }
    else {
        temp = mySensors;
        do {
            if (batt <=0) {
                cout << "\nThis node has run out of battery\n";
                func = 0;
                break;
            }
            batt = (batt - (temp->SensEl->getPC()));
            temp = temp->LLelement;

        } while (temp->LLelement != NULL); //My code stops here and says "Thread   1:EXC_BAD_ACCESS (code=1, address=0x0)
        }
    }

to make it easier to understand:
temp and mySensors are both pointers (declared in the SensorNode class) of type "SensorBlock" (which is the linked list object). batt is a float data member in the SnesorNode class.
Here's the declaration for the SensorBlock class:
class SensorBlock {

    friend class SensorNode;
    SensorBlock * LLelement;
    sensor * SensEl;
    SensorBlock(sensor* senspoint);
};
SensorBlock::SensorBlock(sensor* senspoint) {
    SensEl = senspoint;
    LLelement = NULL;
}

Thanks for the help!
Comment: You haven't done anything to make sure temp isn't null the first time through.
Comment: Oh, I forgot to mention that mySensors is initialized to NULL
Answer: I think you want your loop to look more like this:
    while (temp) {
        if (batt <=0) {
            cout << "\nThis node has run out of battery\n";
            func = 0;
            break;
        }
        batt = (batt - (temp->SensEl->getPC()));
        temp = temp->LLelement;

    }

This way, temp is checked to make sure it isn't null before you try to use it.
If you have a loop like this:
do {
  // use temp
  temp = temp->LLelement;
} while (temp->LLelement);

it is equivalent to
beginning_of_loop:
  // use temp -- oops it might be null!
  temp = temp->LLelement;
  // temp might be null here
  if (temp->LLelement) goto beginning_of_loop;

If you put the while at the top it is equivalent to this:
beginning_of_loop:
  if (!temp) goto end_of_loop:
  // use temp -- can't be null
  temp = temp->LLelement;
  // temp might be null here, but we aren't using it
  goto beginning_of_loop;
end_of_loop:

Comment: ^ That fixed it!  Would you mind explaining why though?  when will while(temp) stop running?  And why was while (temp->LLelement != NULL) not good? I'm just trying to learn this stuff a bit better.
Comment: `while` will stop when it's no longer `true`, or it hits a `break`. Also you could exit the block with a `return` statement, or by throwing an exception. Also, `goto`, but I won't mention that any further.
Comment: @Acoustic77: I added some explanation.


PDE $u_t = f - u_x - u$ of a heating system

Question: I found the following PDE in a book, describing a kind of a heating system:
$\partial_tu=f(t)-\partial_xu-u$
where $u=u(t,x)$ and $(t,x)\in(0,\infty)\times(0,1)$.
After own research i found out that is a special type of so called 'transport equation'. I tried to solve this by method of characteristics, but without success (i'm not familiar with transport equations). Then i tried to treat this equation as parabolic equation
$\partial_tu-Au=f(t), \text{ where } A:=-(\partial_x+\mathrm{id})$
but here also without success(i considered the associated semi group...).
So has someone any idea? Is this equation solvable at all?
I intentionally make no assumtion on the function $f$, i tried to solve the equation in classical sense. But if you have any proof in weak/sobolev sense, please share it with me. I also omit boundary conditions.
Thank you
Comment: Have you tried a separation of variables approach? Something along the lines of
$$u(x,t) = A(x)B(t)$$
such that for the homogeneous solution $$A\partial_tB+B\partial_xA+AB=0$$
After dividing by $AB\neq0$ we can separate.
Answer: The PDE $u_t + u_x = f-u$ is a non-homogeneous linear advection equation. Let us solve the initial value problem $u(x,0)=u_0(x)$ by using the method of characteristics. We introduce the parametrization $x(t)$ of $x$ such that the total time-derivative of $u(x(t),t)$ satisfies
$$
\frac{\text d u}{\text d t} = u_x \frac{\text d x}{\text d t}  + u_t = f-u \, .
$$
According to the PDE, we therefore choose $\frac{\text d x}{\text d t} = 1$. Hence, the characteristic curves $(x(t),t)$ are straight parallel lines $x(t) = t + x_0$ in the $x$-$t$ plane, along which $u$ is not constant. More precisely, $u(x(t),t)$ is obtained by integration of the above differential equation, with the initial condition $u(x_0,0) = u_0(x_0)$.
Finally, after elimination of $x_0 = x(t) - t$, we obtain
$$
u(x,t) = u_0(x-t)\, e^{-t} + \int_0^t e^{-(t-\tau)} f(\tau)\,\text d \tau\, .
$$
Comment: Thanks for the answer. I'll retry your solution.


Select com redirecionamento

Question: Não sei programar! mas consigo fazer pequenas alterações.
Estou precisando criar umselect e quando a pessoa escolher o item, ele seja redirecionado

<select>
  <option value="Vilhena">Vilhena</option>
  <option value="Cacoal">Cacoal</option>
  <option value="Cerejeiras">Cerejeiras</option>
</select>

Ai quando selecionar Vilhena, ser redirecionado para uma outra página.
Comment: Conseguiste resolver este problema? Alguma das perguntas ajudou a resolver?
Answer: Olá, você pode fazer da seguinte forma:
Elabore um javascript.
JavaScript

HTML
<select name="unidade" id="unidade" onChange="AbrirSecao(this.value)">
    <option value="">Selecione sua Cidade</option>
    <option value="http://www.google.com.br">Sua Cidade 1</option>
    <option value="http://www.google.com.br">Sua Cidade 2</option>
</select>

Com isto, ao selecionar a cidade, será redirecionado automaticamente pelo JavaScript.
Answer: Ou se quiser usar jQuery:
<select id="selecao">
    <option value="http://www.exemplo.com.br">Opção 1</option>
    <option value="http://www.exemplo.com.br">Opção 2</option>
    <option value="http://www.exemplo.com.br">Opção 3</option>
</select>

// requer jquery

Answer: Você pode também simplesmente colocar um onclick="location.href='seusite'" no evento onclick do elemento option

<select>
  <option value="Vilhena" onclick="location.href='seusite'">Vilhena</option>
  <option value="Cacoal" onclick="location.href='seusite'">Cacoal</option>
  <option value="Cerejeiras" onclick="location.href='seusite'">Cerejeiras</option>
</select>
Answer: Podes fazer isso usando JavaScript nativo. Ou seja, sem nenhuma biblioteca externa, e sem misturar JavaScript no HTML (que não é muito aconselhável).
Nesse caso precisas de ter em consideração 3 coisas:

o que colocar no HTML
o oscultador de eventos
onde colocar o JavaScript

No HTML a parte visível é o que está entre > e < de cada option. O que está no value é que é importante para a parte da programação. Assim em vez de teres o mesmo no value e o texto das option coloca no value o URL que pretendes. Por exemplo:
<option value="/Vilhena.html">Vilhena</option>

Para selecionares o elemento podes usar:
var select = document.querySelector('select');

Isto ^ vai funcionar bem se só tiveres 1 select na página. Se tiveres mais que um deve dar uma ID ao select (o HTML ficaria: <select id="meuSelect">) e podes selecioná-lo assim:
var select = document.getElementById('meuSelect');
// ou assim:
var select = document.querySelector('#meuSelect');

depois junta-lhe um oscultador de eventos para quando mudar:
select.addEventListener('change', function(){
    var valor = this.value;
    window.location.href = valor;
});

Por fim coloca o script no final da página, antes da tag . Dessa maneira o JavaScript é lido com o HTML já carregado na memória.
Answer: Uma solução simples que pegar o valor selecionado e seta no window location (que abre na mesma aba):

<select
  onchange="this.options[this.selectedIndex].value && (window.location = this.options[this.selectedIndex].value);"
>
  <option value="">Selecionar...</option>
  <option value="https://google.com">Google</option>
  <option value="https://stackoverflow.com/">Stack Overflow</option>
  <option value="https://www.youtube.com/">Youtube</option>
</select>

Ou você também pode usar o window open que abre em uma nova aba

<select
  onchange="this.options[this.selectedIndex].value && (window.open(this.options[this.selectedIndex].value, '_blank'));"
  target="_blanck"
>
  <option value="">Selecionar...</option>
  <option value="https://google.com">Google</option>
  <option value="https://stackoverflow.com/">Stack Overflow</option>
</select>

Select com redirecionamento


Expanding environment variables with double percent signs

Question: We received a VS2010 C# project that calls the function Environment.ExpandEnvironmentVariables();
I understand how to use this with a string such as "%variable%\something.exe", but the code we received uses this string - "%%variable%%\something.exe"
What is the purpose of having two percent signs surrounding the variable? is this a variable pointing to a variable? if so how can this work without calling ExpandEnvironmentVariables twice?
Comment: If you need to standardize it, why not string replace "%%" with "%"?
Comment: This is what I plan to do, they were calling Process.Start() on the result immediately after they expanded...
Answer: %%variable%%\something.exe will expand to %<value of variable>%\something.exe.
You don't necessarily need a second call to ExpandEnvironmentVariables: the resulting string might get passed to an API that expands environment variables or it might get written to the registry as a REG_EXPAND_SZ or whatever.


Android: Scoped Storage Moving App Folder from External Directory to Android/data/com.myapp

Question: I am planning to implement scoped storage for my existing app. All my app data is stored in External Memory in storage/emulated/0/MyAppName path. I have to move this data to private folder like Android/data/com.myapp. Can anyone provide some code snippet to help in this regard?
Comment: You mean `/storage/emulated/0/Android/data/com.myapp` !?
Answer: in this SO topic you have some examples how to move files to new directory (in short: use renameTo method from File class)
remember that when you update your targetSdkVersion and "turn on" Scoped Storage then you won't get access to old folder. at first release version with file-moving snippet, let users run your app for a while (most of active users will move files to new folder), then release new app version with Scoped Storage support
you have to take into account that some part of users may stay with (very) old app and some day will update straight to Scoped-Storage-supporting (targetSdkVersion bumped up), they will lose their data (file access in prev folder). longer you will keep version pre-Scoped-Storage with moving files code on market - smaller part of users will lose data
Answer: You can also use App-specific files.
first of all, let's consider your application id is com.myapp
now add the following to your manifiest file inside application attribute
<application...>
    <provider
        android:name="androidx.core.content.FileProvider"
        android:authorities="${applicationId}.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths" />
    </provider>
</application>

Now go to res directory in your project, right click on it and select new, then select Android Resource Directory.

Now select resource type as xml, write directory name as xml and sourece set as main src/main/res

Now create a new xml file inside the xml folder having name file_paths

And write following inside it.
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images"
    path="Android/data/com.myapp/files/Pictures" />
<external-path name="my_documents"
    path="Android/data/com.myapp/files/Documents" />
<external-path name="my_videos"
    path="Android/data/com.myapp/files/Movies" />
</paths>

Now to use it you can use the following code
private File createImageFile(String fileName) throws IOException {
    File storageDir = activity.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    File imageFile = File.createTempFile(fileName, ".jpg", storageDir);
    return imageFile;
}

public Uri getFileUri(String fileName, String imageString) {
    File imageFile = null;
    Uri uri = null;

    try {
        imageFile = createImageFile(fileName);

        imageFile.createNewFile();
        FileOutputStream fo = new FileOutputStream(imageFile.getPath());
        fo.write(imageString.getBytes());
        fo.flush();
        fo.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    if (imageFile != null) {
        uri = FileProvider.getUriForFile(activity, "com.myapp", imageFile);
    }
    return uri;
}

Comment: Nice answer. But sorry you posted it at the wrong question. Find your post and move your answer to it.


How does Server remember the cipher suite negotiated in handhake in TLS?

Question: I couldn't find a satisfactory answer to this question anywhere. Hoping to get some respite here!
Client and Server engages in handshake, decides upon a cipher suite to use say X.
Now, next time client sends a request (regular), it will be encrypted and then send.
Consider the diagram :-

Here, in Transaction1 cipher suite is negotiated? Request is sent in Transaction2. As http is a stateless protocol, Transaction2 will have no knowledge of Transaction1 then how does it know what was negotiated? Is it using session OR this information is sent with each request? In either case request has to be decrypted to findout sessionid OR cipher suite. So i dont think it is done either way.
Comment: HTTP sessions and TLS/SSL sessions are completely different things. A single TLS session can be kept open and used for multiple HTTP transactions.
Answer: When TLS session caching is used, the session ID is provided by the client in the clear, as part of the ClientHello message which starts the TLS handshake.  (Thus decryption is not needed to find out the TLS session ID.)  The server can then check its cache for that session ID, and find the previously negotiated SSL session information cached for that session ID, which will include (among other things) the cipher suite negotiated.
If, on the other hand, a TLS session ticket is used, then the TLS session information (including cipher suite) is encrypted by the server, and cached by the client (similar to a cookie).  When the client performs a TLS handshake next with that server, it will send this encrypted "session ticket"; the server decrypts the ticket, and obtains (among other things) the cipher suite negotiated.
Hope this helps!


Proving that a graph of minimum degree $\delta$ and girth $g$ has at least $n_0(\delta, g)$ vertices

Question: I am currently studying the textbook Graph Theory, fifth edition, by Reinhard Diestel. Chapter 1.3 Paths and cycles says the following:

Proposition 1.3.3. A graph $G$ of radius at most $k$ and maximum degree at most $d \ge 3$ has fewer than $\dfrac{d}{d - 2}(d - 1)^k$ vertices.
Proof. Let $z$ be a central vertex in $G$, and let $D_i$ denote the set of vertices of $G$ at distance $i$ from $z$. Then $V(G) = \bigcup_{i = 0}^k D_i$. Clearly $\lvert D_0 \rvert = 1$ and $\lvert D_1 \rvert \le d$. For $i \ge 1$ we have $\lvert D_{i + 1} \rvert \le (d - 1) \lvert D_i \rvert$, because every vertex in $D_{i + 1}$ is a neighbour of a vertex in $D_i$ (why?), and each vertex in $D_i$ has at most $d - 1$ neighbours in $D_{i + 1}$ (since it has another neighbour in $D_{i - 1}$). Thus $\lvert D_{i + 1} \rvert \le d(d - 1)^i$ for all $i < k$ by induction, giving
$$\lvert G \rvert \le 1 + d\sum_{i = 0}^{k - 1} (d - 1)^i = 1 + \dfrac{d}{d - 2}((d - 1)^k - 1) < \dfrac{d}{d - 2}(d - 1)^k. \square$$
Similarly, we can bound the order of $G$ from below by assuming that both its minimum degree and girth are large. For $d \in \mathbb{R}$ and $g \in \mathbb{N}$ let
$$n_0(d, g) := \begin{cases} 1 + d \sum\limits_{i = 0}^{r - 1} (d - 1)^i & \text{if $g =: 2r + 1$ is odd;} \\ 2 \sum\limits_{i = 0}^{r - 1} (d - 1)^i & \text{if $g =: 2r$ is even.} \end{cases}$$
It is not difficult to prove that a graph of minimum degree $\delta$ and girth $g$ has at least $n_0(\delta, g)$ vertices (Exercise 7). Interestingly, one can obtain the same bound for its average degree:
Theorem 1.3.4. (Alon, Hoory & Linial 2002)
Let $G$ be a graph. If $d(G) \ge d \ge 2$ and $g(G) \ge g \in \mathbb{N}$ then $\lvert G \rvert \ge n_0(d, g)$.
One aspect of Theorem 1.3.4 is that it guarantees the existence of a short cycle compared with $\lvert G \rvert$. Using just the easy minimum degree version of Exercise  7, we get the following rather general bound:
Corollary 1.3.5. If $\delta(G) \ge 3$ then $g(G) < 2 \log \lvert G \rvert$.
Proof. If $g := g(G)$ is even then
$$n_0(3, g) = 2 \dfrac{2^{g/2} - 1}{2 - 1} = 2^{g/2} + (2^{g/2} - 2) > 2^{g/2},$$
while if $g$ is odd then
$$n_0(3, g) = 1 + 3 \dfrac{2^{(g - 1)/2} - 1}{2 - 1} = \dfrac{3}{\sqrt{2}} 2^{g/2} - 2 > 2^{g/2}$$
As $\lvert G \rvert \ge n_0(3, g)$, the result follows. $\square$

The author says that "it is not difficult to prove that a graph of minimum degree $\delta$ and girth $g$ has at least $n_0(\delta, g)$ vertices (Exercise 7)." I've been working on this for 48 hours, but I cannot see how what the author has done here makes sense.
So we want to prove that
$$\lvert G \rvert \ge n_0(\delta, g) := \begin{cases} 1 + \delta \sum\limits_{i = 0}^{r - 1} (\delta - 1)^i & \text{if $g =: 2r + 1$ is odd;} \\ 2 \sum\limits_{i = 0}^{r - 1} (\delta - 1)^i & \text{if $g =: 2r$ is even.} \end{cases}$$
Start with a graph $G$, and let $d(G) \ge \delta \ge 2$ and $g(G) \ge g$. So, on the one hand, we have to derive
$$n_0(\delta, g) := \begin{cases} 1 + \delta \sum\limits_{i = 0}^{r - 1} (\delta - 1)^i & \text{if $g =: 2r + 1$ is odd;} \\ 2 \sum\limits_{i = 0}^{r - 1} (\delta - 1)^i & \text{if $g =: 2r$ is even.} \end{cases}$$
And, on the other hand, we have to prove that $\lvert G \rvert \ge n_0(\delta, g)$. The author describes this as "not difficult," but there is nothing in the information that the author has provided up to this point to indicate where $n_0(d, g)$ comes from, apart from the $1 + d \sum\limits_{i = 0}^{r - 1} (d - 1)^i$ expression, which is derived here but only for the general case (not any such odd-even split). I don't see any way to prove this, unless using information outside of what the author has introduced so far in the textbook.
Answer: $g$ is odd case
Suppose that $r$ is such that $g=2r+1$.
Let again $z$ be a central vertex and $D_i$ denote the set of vertices of distance $i$ from $z$. Now $|D_0|=1$ and obviously $|D_1|\geq \delta$ (since $z$ has $\delta(z)\geq \delta$ neighbors).
The important fact is that for $i\in[1,r-1]$ the following holds $|D_{i+1}|\geq (\delta-1)|D_i|$. Why?
For any $u\in D_i$ there is one edge from vertex in $D_{i-1}$ but $u$ will have at least $\delta(u) -1 \geq \delta -1$ edges  to other vertices not in $\bigcup_{j=0}^i D_j$ since if there was a $v\in D_j$, for some $j$, such that $(u,v)\in E(G)$ then there would be a cycle of length $L\leq j + i + 1\leq 2i+1\leq 2(r-1)+1<g$, contradiction. A similar argument shows that two vertices $u_1,u_2\in D_i$ can't both be connected with a vertex $v\in D_{i+1}$.
$|D_{i+1}|\geq (\delta-1)|D_i|$ implies $|D_{i+1}|\geq \delta (\delta-1)^i$.
The result follows
$$|G| = 1 + \sum_{i=1}^{r}|D_i| \geq 1 + \delta \sum_{i=0}^{r-1}(\delta-1)^i =n_0(\delta, g)$$

$g$ is even case
Suppose that $r$ is such that $g=2r$.
Now we can't choose a central vertex. So choose two vertices $z_1, z_2$ and join them together to $z$. Now $|D_0| = 2$ and $|D_1| \geq 2(\delta-1)$, since we have to account for the edge $(z_1,z_2)$.
Afterwards there can be a similar argument to prove $|D_{i+1}|\geq (\delta -1)|D_i|$ but now, because we to account for $(z_1, z_2)$, $i$ is not greater than $r-2$ since the inequality that bounds $i$ is given by $L\leq 2i+1+2= 2(i+1)+1$, so for $g$ to be surely greater than
$L$ we can choose $i+1 <r \iff i \leq r-2$ so that $2(i+1)+1\leq 2r - 1< g$.
Combining the above, $|D_{i+1}|\geq 2(\delta-1)^{i+1}$ but only for $i\in[1,r-2]$. So we can write $|D_{i}|\geq 2(\delta-1)^{i}$ ($i\in[2,r-1]$) but we can also write $|D_0|=2(\delta -1)^0$ and $|D_1|=2(\delta-1)^1$ so finally
$$|G| = 2 + \sum_{i=1}^{r}|D_i| \geq 2 \sum_{i=0}^{r-1}(\delta-1)^i =n_0(\delta, g)$$
Comment: How does the contradiction "For any $u\in D_i$ ..." prove that $|D_{i+1}|\geq (\delta-1)|D_i|$ for $i\in[1,r-1]$? And how does $|D_{i+1}|\geq (\delta-1)|D_i|$ imply $|D_{i+1}|\geq \delta (\delta-1)^i$?
Comment: @ThePointer $|D_{i+1}|\geq (\delta-1)|D_i|\geq (\delta-1)^2|D_{i-1}|\geq \cdots\geq (\delta-1)^i|D_1| = \delta(\delta-1)^i$  (one can prove this through induction). Also regarding $|D_{i+1}|\geq (\delta -1)|D_i|$, suppose you are at level $D_i$, then each vertex $u\in D_i$ has at least $\delta$ edges. One is joined with a vertex in $D_{i-1}$ (the previous from $u$ in the $z$-$u$ path) and all the other edges (which are at least $\delta -1$) lead to other vertices that you can't reach within a distance $i$ from $z$ (so they are new vertices that will be in $D_{i+1}$).
Comment: Ok, but what does any of that have to do with the contradiction part?
Comment: Also, why can't we choose a central vertex if $r$ is such that $g=2r$? I don't understand that part either.
Comment: @ThePointer The contradiction arises if from a vertex $u\in D_i$ there is an edge to a previous vertex (not including the one previoust to it in the $z$-$u$ path) since then we would have a cycle of length less that $g$, which is a contradiction from the definition of girth.
Also if $g =2r$ then you don't always have a central vertex. Think of a Path graph $P_n$ with $n=8$ nodes, there is not a single central vertex since there are two "middle" parts.
Comment: I do not think this proof is correct. You have this part: "The important fact is that for $i\in[1,r-1]$ the following holds $|D_{i+1}|\geq (\delta-1)|D_i|$. Why?" But then you never actually answer/prove why $|D_{i+1}|\geq (\delta-1)|D_i|$. This part comes afterwards:
Comment: "For any $u\in D_i$ there is one edge from vertex in $D_{i-1}$ but $u$ will have at least $\delta(u) -1 \geq \delta -1$ edges  to other vertices not in $\bigcup_{j=0}^i D_j$ since if there was a $v\in D_j$, for some $j$, such that $(u,v)\in E(G)$ then there would be a cycle of length $L\leq j + i + 1\leq 2i+1\leq 2(r-1)+1<g$, contradiction."
Comment: But, as far as I can tell, this doesn't actually answer/prove why $|D_{i+1}|\geq (\delta-1)|D_i|$. Also, how can there be "other vertices not in $\bigcup_{j=0}^i D_j$"? $\bigcup_{j=0}^i D_j$ would be all of the vertices in the graph, so it doesn't make sense to talk about "vertices not in $\bigcup_{j=0}^i D_j$." In fact, notice that this https://math.stackexchange.com/a/4650423/356308 answer uses the fact that $\bigcup_{j=0}^i D_j$ would be all of the vertices in the graph in the part $$|G| = |D_0| + |D_1| + \dots + |D_k| = |D_0| + \sum_{i=0}^{k-1} |D_{i+1}|.$$
Comment: @ThePointer If every vertex in $D_i$ (with $i\in[1, r-1]$) contributes for at least $\delta -1$ vertices in $D_{i+1}$ then $|D_{i+1}|\geq (\delta -1)|D_i|$. Also suppose $i\leq r-1$, if there is an edge from $u\in D_i$ to $v\in D_j$ (for $j \leq i$) different than the one in the previous from $u$ in the $z$-$u$ path then $z\dots uv\dots z$ would be a cycle (or contain more cycles) of length at most $i + 1 + j\leq 2(r-1) + 1 < g$, which is the contradiction (by the definition of girth).
Comment: Where is the proof for $L\leq 2i+1+2= 2(i+1)+1$? Again, this isn't proving anything – it is simply an assertion without justification.
Answer: To recap: In Graph Theory by Diestel, Theorem 1.3.3, uses the radius and maximum degree of a graph $G$ to obtain an upper bound on the number of vertices (the order $|G|$) of $G$. A full proof is given. The reader is then supposed to prove a similar looking lower bound on $|G|$, using the girth $g$ and the minimum degree $\delta$. The lower bound is given by the expression $n_0(\delta, g)$.
(When Diestel says that "this is not hard" to do, I think he means that one should not need to invent an entirely new proof method; but that can re-use some of the ideas from the proof of Theorem 1.3.3. This is indeed the case.)
We first prove a lower bound which is valid for all $g$, and then improve this bound to obtain the separate expression valid when $g$ is even.
First bound
The general idea is as follows: We start at an arbitraty vertex $v$ of $G$. One step at a time, we walk away from this vertex in all possible directions. For each further step we count how many additional vertices we can be sure that this extra step allows us to reach.
The minimum degree $\delta$ says that for most steps (all except the first and up to a certain number, see below) we should be able to reach at least a factor of $\delta-1$ new vertices. The "minus one" is there since we are not allowed to go backwards. For the first step, there is no backwards, so we have at least $\delta$ different vertices to go to.
The girth $g$ (the length of the shortest cycle) guarantees that as long as we don't walk too far out, we will not double count any vertices. Thus, our expression will indeed be a lower bound. So what is "too far out", exactly? We can not risk double counting any vertex, so just before the risk arises that we might reach and count an already reached vertex, we need to stop! Exactly how many steps out does the risk of double counting start?
Obviously, we cannot go $g$ steps away from our starting vertex, since at that point we risk coming right back to $v$. However, we actually need to stop much earlier, just before $g/2$ steps (which might not be an integer). Consider that if we count vertices which are $g/2$ steps or more away from $v$, we run the risk of having gone one path that runs along one half of a cycle to a vertex $u$ and another path which goes the along the other half of the same cycle to the same vertex $u$. That is, we would risk counting $u$ twice.
We are close to the key realization: that every unique path less than $g/2$ steps away from $v$ leads to a unique vertex. We prove this by contradiction. Suppose that we have two different paths, each shorter than $g/2$, which lead from $v$ to $u$. Since the paths differ, they diverge at some point, say $a$ (which might be the same vertex as $v$), and at some vertex along the way to $u$, say at $b$ (which might or might not be the same as $u$), they reunite. We now have two distinct paths from $a$ to $b$. Put together, the two paths form a cycle. Since each of the two parts are strictly shorter than $g/2$, the cycle is strictly shorter than $g$. This is a contradiction.
So, how many unique paths strictly less than $g/2$ steps away from $v$ are there? The largest integer strictly less than $g/2$ is $\lceil g/2 \rceil -1$. And for each permitted path length $i$, we have argued that there are at least $\delta(\delta-1)^{i-1}$ different $i$-paths. Counting $v$ itself as the "zero path", and summing over the permitted lengths, there is at least
$$1 + \delta \sum\limits_{i = 0}^{\lceil g/2 \rceil - 2} (\delta - 1)^i $$
such paths. They all start at $v$, have length less than $g/2$, and, crucially, they each end at a different vertex. Thus, the above expression gives a lower bound for $|G|$. When $g$ is odd, $g=2r+1$, we have $\lceil (2r+1)/2 \rceil - 2 = r-1$, so the expression implies
$$ |G| \geq 1 + \delta \sum\limits_{i = 0}^{r-1} (\delta - 1)^i \,.$$
The right hand side equals our given $n_0(\delta, g)$ when $g=2r+1$. Thus, our bound, which is valid for any $g$, exactly matches what we want for odd $g$.
Improving the bound when $g$ is even
If $g$ is even, we can be a little clever and improve the bound. Suppose that $g=2r$. We have already shown
$$|G|\geq 1 + \delta \sum\limits_{i = 0}^{r - 2} (\delta - 1)^i\,.$$
Now, instead of starting at the chosen vertex $v$, let us start at any two neighbouring vertices $v_1$ and $v_2$. The key insight now is that every unique path of length $r-1$ or less, starting at either $v_1$ or $v_2$, leads to a unique vertex.
For, like before, suppose that we have two different paths of length $r-1$ or less, leading to the same vertex $u$. Then the symmetric difference of the edge sets of these paths (all the edges that belong to just one of the paths), possibly with the addition of the edge $v_1v_2$, would form a cycle. The length of the cycle would be at most $(r-1)+(r-1)+1 = 2r-1 < g$, a contradiction!
Thus, as a lower bound for $|G|$, we obtain a lower bound on the number of paths of length $r-1$ or less which start at either $v_1$ or $v_2$. For each vertex, we have one path of length zero, then there are at least $\delta-1$ choices for the first step, then at least $\delta-1$ for the second, etc.
$$|G|\geq 2(1+ \sum_{i=1}^{r-1}(\delta-1)^i)
= \sum_{i=0}^{r-1}2(\delta-1)^i) \,.$$
The rhs equals $n_0(\delta, g)$ when $g=2r$, and we are done.
However, we might want to check that the new bound for $g=2r$ is actually stronger than the one we obtained before. To see this, consider that the number of terms in both expressions is $r$, and notice that every term of the latter bound is strictly larger than the corresponding term of the former bound. (This comparison boils down to $\delta \geq 3$. Which of course is true, since a cycle of length 2 or less makes no sense for simple graphs.)
Comment: "And for each permitted path length $i$, we have argued that there are at least $\delta(\delta-1)^{i-1}$ different $i$-paths." – what is your argument for this? Because I don't see any such argument in your answer.
Comment: @ThePointer "First bound", second section. Multiplication principle.


How to set programmatically Line Item Price?

Question: I just managed to add programmatically a line item (type: product) to my order.
I struggle to set the price for this item now.
How can I set the price at the same time when adding such an item (and having the total calculated accordingly)?
This is how I can successfully add a product:
 $product_id = XXX;

// Load whatever product represents the item the customer will be
// paying for and create a line item for it.
$product = commerce_product_load($product_id);
commerce_product_save( $product );

$line_item = commerce_product_line_item_new($product, 1, $order->order_id);

// Save the line item to get its ID.
commerce_line_item_save($line_item);

// Add the line item to the order
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$order_wrapper->commerce_line_items[] = $line_item;

// Save the order again to update its line item reference field.
commerce_order_save($order);

Answer: I have struggled a bit with this, as have others apparently, but i found the solution in another thread.
Every time an order object is loaded the following function is fired:
commerce_cart_line_item_refresh()
In this function the unit price of the Line Item is set to the current price of the original product, so even if you change the unit price, when you create the line item, its changed back to the original price the next time you load the order object.
So rather than setting the unit price of a line item, when you create it, you have to do it every time it's refreshed - For this Drupal Commerce offers the following hook:
HOOK_commerce_cart_line_item_refresh($line_item, $order_wrapper)
Heres a coding example:
function YOUR_MODULE_commerce_cart_line_item_refresh($line_item, $order_wrapper){

$line_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);

$label = $line_wrapper->line_item_label->value();

//Only alter price for a specific product type (you could choose other selection critirias here)
if ( $label == 'YOUR PRODUCT TYPE'){
    $new_price = calculate_new_price(); //I use a function to calculate a price, you could set a static price instead

    if(!empty($new_price)){
        $line_wrapper->commerce_unit_price->amount->set($new_price);
        $line_item->commerce_unit_price['und'][0]['data']['components'][0]['price']['amount'] = $new_price;
        $line_wrapper->save();
    }

}

}
function calculate_new_price(){

//Do what ever pricing logic you need here

//Here a static price of one dollor
$price = 100;

return $price;

}
Answer: Once you've added it to the order, the standard product pricing system takes over to derive the price of the line item from the price of the product (well, depending on the order status). So if this order is a cart order, it should get its price automatically on the subsequent order load that triggers price calculation.
If you're wanting to set it to something other than the calculated sell price, you'll need some strategy that involves storing the price directly on the line item object (either in the data array or a custom field) and then setting the unit price of the line item to that stored price during the sell price calculation process.
Comment: Can you provide a link for an example for such a custom strategy?d
Answer: try to following code..
 //update line_item amount
  $amount = XXXX;
  $order_id = XXX;

  $line_item_id = db_select('commerce_line_item', 'li')
            ->fields('li',array('line_item_id'))
            ->condition('li.order_id', $order_id, '=')
            ->execute()->fetchField();
  $line_item = commerce_line_item_load($line_item_id);

  $line_item->commerce_unit_price[LANGUAGE_NONE][0]['amount'] = $amount;
  $line_item->commerce_unit_price[LANGUAGE_NONE][0]['data']['components'][0]['price']['amount'] = $amount;
  commerce_line_item_save($line_item);

Thank You