How can we save blob url into (.webm) video in my server using javascript and php

Question: I am using RecordRTC for screen recording,
Here is my code,

<title>Screen Recording</title>

Screen Recording

<button id="btn-start-recording">Start Recording</button>
<button id="btn-stop-recording" disabled>Stop Recording</button>

<video controls autoplay playsinline></video>

This is working fine means I can able to record when I click the start recording button after that if I click stop recording then I can see that video(what ever I recorded) at <video controls autoplay playsinline></video> if I want download then there is a download button in <video></video> then I can download upto here it working fine (This is I am doing in server).
But here when I click stop recording button that recorded video I need to download automatically in to my server folder(recordedFiles) as a MP4 .
What I was tried ,there is a function called stopRecordingCallback() ,in that function video.src is generating one video blob url like   blob:https://server_ip/f4d27a7d-48f1-4499-9613-7953ef01edfe. This url I need to convert in to base64 and again save as (.webm)MP4
Here is My code what ever I tried in JS:
  let blob = new Blob(["blob:http://localhost/166d7686-4500-4a4a-993f-3b743d3afcb4"], { type: "video/webm" });
        // The full Blob Object can be seen
        // in the Console of the Browser
        console.log('Blob - ', blob);

        var reader = new FileReader();
        reader.readAsDataURL(blob);
        reader.onloadend = function () {
        var base64String = reader.result;
        console.log('Base64 String - ', base64String);

        // Simply Print the Base64 Encoded String,
        // without additional data: Attributes.
        console.log('Base64 String without Tags- ',base64String.substr(base64String.indexOf(', ') + 1));
        }

This is not working at all .
How can I save that recorded file into my server folder using that blob url by using javascript or PHP.
Please help on this.
Thanks
Comment: exactly what error are you getting?
Comment: I am not getting error ,I got this url ```blob:http://localhost/a7dcebe0-ed6d-44ca-90ff-05274f71097a``` ,in this ```stopRecordingCallback()```,I am not understand how can I convert this ```blob``` url to (.webm)video(mp4) and save in one folder,or can we convert first blob url to base64 then (.webm) we need to convert ,plz help me in this .
Comment: You said it's working in your own PC but not in others? So presumably there is some error or other unexpected behaviour when it runs in those situations. But we need more detailed and specific information than simply "not working". That could mean 100 different things. Precisely _what_ isn't working, and what happens instead? How much debugging have you done?
Comment: when I recorded in my PC i got this blob url ```blob:http://localhost/a7dcebe0-ed6d-44ca-90ff-05274f71097a``` ,this url if i try in another PC, it was not running ,it was telling like ```your file was not found``` ,but it is woriking in my PC
Comment: My problem is can we save this blob url into my PC folder with extension (.webm) or mp4 when click stop recording ,i am new to JS. Or can we convert blob url to base64 from base64 can we convert mp4 file is it possible ,if it is possible kindly let me know thanks
Comment: "it was telling "...what was? Instead of vaguely mentioning part of an error message, state clearly where you saw this message, which line of code you were on, and exactly what the full message says, including a stack trace if there is one provided by the browser.
Comment: "My problem is"...I thought your problem was that you can't generate the blob URL sometimes? Now you're asking about saving it - but you can't save something which doesn't exist, so you'll have to fix that first. Concentrate on one problem at a time, otherwise it will get confusing.
Comment: @ADyson Thanks for your response ,when i start my screen recording it working fine and it is recording then I click stop recording button then I can see my recorded video  at `````` after that i can download the video by click download button instead of that one, if I click stop recording button ,i need to save that video in to my server folder automatically .this thing how can i do .
Comment: ",i need to save that video in to my server folder"...you need to send it via AJAX.
Comment: There are a lot of questions, blogs, articles etc about this topic online already - just google "send blob url video to server". Here are some examples of the results from that simple search: https://stackoverflow.com/questions/52782256/record-video-stream-from-webcam-and-upload-blob-to-server, https://stackoverflow.com/questions/46880339/cant-save-uploaded-videos-blob-url-at-the-backend-server-using-ajax-call . Those might help you understand what you need to do.
Comment: P.S. if you google "send blob url to server" then you get even more useful results. The process is fairly generic, I don't think the fact that it's a video will make much difference (other than the file size might be larger than other types of file, so you might have to consider how to deal with that).
Answer: In recordRTC use mimeType: 'video/webm; codecs=vp9' it will work in Google chrome, Mozilla Firefox and Microsoft Edge.
const recorder = RecordRTC(stream, {
    type: 'video',

    // audio/webm
    // video/webm;codecs=vp9
    // video/webm;codecs=vp8
    // video/webm;codecs=h264
    // video/x-matroska;codecs=avc1
    // video/mpeg -- NOT supported by any browser, yet
    // video/mp4  -- NOT supported by any browser, yet
    // audio/wav
    // audio/ogg  -- ONLY Firefox
    // demo: simple-demos/isTypeSupported.html
    mimeType: 'video/webm;codecs=vp9'
})

Answer: I suggest make an XML POST request to a PHP script and use the video "file object" and not the blob element.
let request = new XMLHttpRequest();
let url = "your form treatment file path here" ;

var video = your video file object; // i don't know output gived by recorder but if you can have blob you sure can access the raw js file object

var formData = new FormData();
formData.append("upload_video", file);

request.open("POST", url, true);

request.onload = function () {
    saveResponse = request.responseText;

        var result = document.getElementById('result'); // add an element with an id to display your PHP script return (to debug or display something once the video is uploaded)
        result.innerHTML = saveResponse;

}
request.send(data);

Then you can access your file with PHP $_FILES['upload_video'] and do what you want with it.


A quadratic cyclotomic extension

Question: Let $\zeta_n$ be a primitive $n$-th root of unity with $n > 2$.
How to show (supposedly using Galois theory) that the extension $\mathbb{Q}(\zeta_n)/\mathbb{Q}(\zeta_n+\zeta_n^{-1})$ has degree $2$, meaning : $$[\mathbb{Q}(\zeta_n):\mathbb{Q}(\zeta_n+\zeta_n^{-1})]=2$$
Answer: The polynomial
$$X^2-(\zeta _n+\zeta_n ^{-1})X+1$$ is the minimal polynomial of $\zeta _n$ on $\mathbb Q(\zeta _n+\zeta _n^{-1})$. It's easy to check that it's an annihilator polynomial. The irreducibility come from that fact that if $\zeta _n+\zeta_n ^{-1}\in \mathbb R$ whereas $\zeta _n\notin \mathbb R$, and thus $$[\mathbb Q(\zeta _n):\mathbb Q(\zeta _n+\zeta _n^{-1})]= 2.$$

A quadratic cyclotomic extension


Can spinnaker use local storage such as mysql database?

Question: I want to deploy spinnaker for my team. But I encounter a problem. The document of spinnaker said:

Before you can deploy Spinnaker, you must configure it to use one of the supported storage types.

Azure Storage
Google Cloud Storage
Redis
S3

Can spinnaker use local storage such as mysql database?
Answer: The Spinnaker microservice responsible for persisting your pipeline configs and application metadata, front50, has support for the storage systems you listed. One could add support for additional systems like mysql by extending front50, but that support does not exist today.
Some folks have had success configuring front50 to use s3 and pointing it at a minio installation.


Como adicionar e remover elementos com Javascript

Question: Olá, gostaria de saber como eu poderia adicionar e remover elementos ao html utilizando javascript (não é permitido utilizar algo como jQuery), meu codigo é o seguinte:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Pedidos</title>
    <link rel="stylesheet" href="main.css">

Faça seu pedido

        <form action="">

                Nome:
                <input id="nome" type="text">

                Fone:
                <textarea name="textarea" cols="40" rows="5"></textarea>

                Endereço:
                <input id="endereco" type="text">

                Pedido
                <select name="" id="pedido">
                    <option value="n001">Pedido Doidao 001</option>
                    <option value="n002">Pedido Doidao 002</option>
                    <option value="n003">Pedido Doidao 003</option>
                    <option value="n004">Pedido Doidao 004</option>
                </select>
                Pão
                <select name="" id="pao">
                    <option value="pao1">Pão 1</option>
                    <option value="pao2">Pão 2</option>
                    <option value="pao3">Pão 3</option>
                    <option value="pao4">Pão 4</option>
                </select>
                Quantidade
                <input id="qtd" type="number">
                <button onclick="adicionar()">Adicionar</button>

        </form>

                    Quantidade

                    Sanduíche

                    20

                    Sanduíche Brabissimo

                    <button onclick="remover()">X</button>

        <button class="enviar">Enviar</button>

CSS:
body{
    background: orange;
}
*{
    margin: 0;
    padding: 0;
    color: black;
}
h1{
    margin-bottom: 20px;
    text-align: center;
}
button{
    padding:4px;
}
.container{
    width: 70%;
    margin-right: auto;
    margin-left: auto;
}
.content{
    margin-bottom: 10px;
    display: flex;
}
.sanduiche{
    margin-bottom: 10px;
    display: flex;
}
.content > input{
    width: 100%;
    height: 25px;
    border: solid 1px;
    background: white;
    color: black;
    border: 0px;
    border-radius: 2px;
    margin-left: 10px;
}
.content > textarea{
    width: 100%;
    border: solid 1px;
    background: white;
    color: black;
    border: 0px;
    border-radius: 2px;
    margin-left: 10px;
}
#fone{
    height: 70px;
}
.sanduiche > label{
    margin-right: 15px;
}
.sanduiche > select{
    width: 30%;
    height: 25px;
    margin-right: 15px;
}
.sanduiche > input{
    width: 30%;
    height: 25px;
    border: solid 1px;
    background: white;
    color: black;
    border: 0px;
    border-radius: 2px;
}
#qtd{
    margin-right: 10px;
}
.adicionados{
    border: solid 2px white;
}
.rowtabela{
    display: flex;
}
.item{
    margin-right: 15%;
    margin-left: 15%;
}
.enviar{
    width: 100%;
    margin-top: 5px;
}

Answer: A forma mais simples que conheço é com innerHTML:

document.getElementById('criar').addEventListener('click', function(){
  document.getElementById('div').innerHTML = 'Testo criado';
});

document.getElementById('destruir').addEventListener('click', function(){
  document.getElementById('div').innerHTML = '';
});
<button id='criar'>CRIAR</button>
<button id='destruir'>DESTRUIR</button>

Você atribui uma string ao innerHTML com texto e/ou código HTML, se for atribuir apenas texto pode usar também innerText
Mas existem outras formas
Answer: Resolvi reformular seu código por ter muitos problemas de sintaxe e complicações desnecessárias. Basicamente é usar innerHTML para adicionar novos elementos e outerHTML = '' para removê-los (em lugar do remove() que não tem suporte em navegadores anteriores ao IE 11, como visto aqui: https://caniuse.com/#feat=childnode-remove).
Logo o código ficou assim:

function adicionar(){

   var tabela = document.getElementById('tabela');
   var tp = document.getElementById("pedido");
   tp = tp.options[tp.selectedIndex].textContent;
   var qtd = document.getElementById("qtd").value;

   var ped_id = document.body.querySelectorAll(".rowtabela").length;

   var novo_item = '
'
   +'
'+qtd+'
'
   +'
'+tp+'
'
   +'
'
   +'<button onclick="remover(this)">X</button>'
   +'

';

   tabela.innerHTML += novo_item;

}

function remover(e){
   e.parentNode.parentNode.outerHTML = '';
}
   body{
    background: orange;
}
*{
    margin: 0;
    padding: 0;
    color: black;
}
h1{
    margin-bottom: 20px;
    text-align: center;
}
button{
    padding:4px;
}
.container{
    width: 70%;
    margin-right: auto;
    margin-left: auto;
}
.content{
    margin-bottom: 10px;
    display: flex;
}
.sanduiche{
    margin-bottom: 10px;
    display: flex;
}
.content > input{
    width: 100%;
    height: 25px;
    border: solid 1px;
    background: white;
    color: black;
    border: 0px;
    border-radius: 2px;
    margin-left: 10px;
}
.content > textarea{
    width: 100%;
    border: solid 1px;
    background: white;
    color: black;
    border: 0px;
    border-radius: 2px;
    margin-left: 10px;
}
#fone{
    height: 70px;
}
.sanduiche > label{
    margin-right: 15px;
}
.sanduiche > select{
    width: 30%;
    height: 25px;
    margin-right: 15px;
}
.sanduiche > input{
    width: 30%;
    height: 25px;
    border: solid 1px;
    background: white;
    color: black;
    border: 0px;
    border-radius: 2px;
}
#qtd{
    margin-right: 10px;
}
.adicionados{
    border: solid 2px white;
}
.rowtabela{
    display: flex;
}
.item{
    margin-right: 15%;
    margin-left: 15%;
}
.enviar{
    width: 100%;
    margin-top: 5px;
}

Faça seu pedido

        <form action="">

                Nome:
                <input id="nome" type="text">

                Fone:
                <textarea name="textarea" cols="40" rows="5"></textarea>

                Endereço:
                <input id="endereco" type="text">

                Pedido
                <select name="" id="pedido">
                    <option value="n001">Pedido Doidao 001</option>
                    <option value="n002">Pedido Doidao 002</option>
                    <option value="n003">Pedido Doidao 003</option>
                    <option value="n004">Pedido Doidao 004</option>
                </select>
                Pão
                <select name="" id="pao">
                    <option value="pao1">Pão 1</option>
                    <option value="pao2">Pão 2</option>
                    <option value="pao3">Pão 3</option>
                    <option value="pao4">Pão 4</option>
                </select>
                Quantidade
                <input id="qtd" type="number">
                <button type="button" onclick="adicionar()">Adicionar</button>

        </form>

                    Quantidade

                    Sanduíche

                    20

                    Sanduíche Brabissimo

                    <button onclick="remover(this)">X</button>

        <button class="enviar">Enviar</button>

Comment: Tem que alertar o rapaz que o button `Adicionar` tem que ser `type="button"`. Você parece que não sei, rs :)
Comment: pois eh, esqueci rs, mas na resposta eu coloquei
Comment: Eu vi, mas ele continuou a não colocar, veja https://pt.stackoverflow.com/questions/294353/javascript-exibir-quantidade/294446#294446


Chamar evento da GridView na Activity

Question: Tenho um GridView adapter e nele possuo um ImageButton para excluir os itens. Ele está excluindo corretamente, porém, toda vez que um item for excluído preciso setar a quantidade atual em um TextView que está em uma outra Activity. Não consigo pegar o evento do GridView diretamente, pois, como ele possui outros componentes clicáveis, seu toque ficou desabilitado:
Segue o trecho de código em que excluo o item e tento passar a quantidade atual de itens para o TextView presente na minha Activity:
holder.imgDelete.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                Integer position = (Integer)v.getTag();

                Produto_Valor newList[] = new Produto_Valor[values.length - 1];
                int count = 0;
                for (int i = 0; i < values.length; i++) {
                    if (values.length - 1 > 0) {
                        if (values[i] == values[1]) {
                        } else {
                            newList[count] = values[i];
                            count++;
                        }
                    }
                }
                values = newList;
                notifyDataSetChanged();

                LayoutInflater inflater = (LayoutInflater) context
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View view = inflater.inflate(R.layout.activity_pedidos, null);
            final TextView txtTotal = (TextView) view.findViewById(R.id.lbl_QtdeDados);

            new Thread (new Runnable(){
                @Override

                public void run(){

                    txtTotal.setText(String.valueOf(values.length));
                }
            }).start();

            }
        });

Comment: Conseguiu resolver o problema Fabio, ou precisa de mais alguma informação?
Answer: Olá,
Eu acho que uma solução que pode te ajudar é utilizar o método startActivityForResult, você pode ir na documentação do Android ou dar uma lida neste tutorial em pt-br: http://celeiroandroid.blogspot.com.br/2011/03/atividades.html, no final do tutorial é explicado o que é e como utilizar o startActivityForResult.
Para o seu problema acredito que você deseja duas Activities uma com a lista de itens e outra que possui este TextView com a quantidade de itens removidos. Você irá retornar a quantidade de itens de uma Activity para outra, não será necessário utilizar o método inflate para o item TextView na Activity de listagem dos itens.
Comment: Na verdade, tenho uma Activity e um Adapter, que extends  de BaseAdapter. Implementei da forma como você sugeriu, mas obtive o seguinte erro: java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{aplicativo.App/aplicativo.App.GridViewAdapter_ItensPedido}: java.lang.ClassCastException: aplicativo.App.GridViewAdapter_ItensPedido cannot be cast to android.app.Activity
Answer: Você pode criar uma função na sua activity para atualizar o TextView, por exemplo atualizaTextView(String value). Aí no momento em que você chamar seu imgDelete.setOnClickListener você executa o método desta forma:
((MinhaActivity)context).atualizaTextView(value);

Boa sorte.
Answer: Você pode abrir a activity do GridView, deletar os itens e depois retornar a quantidade de itens para a activity do TextView.
Na activity com o GridView (irei nomear GridViewActivity) deve chamar o método setResult(int resultCode, Intent data) no encerramento. Substitua o finish() em GridViewActivity como a seguir:
@Override
public void finish() {
    Intent data = new Intent();
    // insere a quantidade de itens no Intent
    data.putExtra("TamanhoDaLista", tamanhoDaLista);
    setResult(RESULT_OK, data);
    super.finish();
}

Na activity que contém o TextView (vou chamar de TextViewActivity), coloque a constante no topo que será usada para identificar a GridViewActivity quando ela for finalizada:
private static final int REQUEST_DELETE_ITENS = 0; // zero é só um exemplo

Quando iniciar a GridViewActivity, use:
startActivityForResult(REQUEST_CODE, intent);

Substitua o método onActivityResult (int requestCode, int resultCode, Intent data):
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // verifica se o código de retorno é a GridViewActivity
    if (requestCode == REQUEST_DELETE_ITENS) {
        // verifica se a activity retornou com sucesso (talvez tenha um botão cancelar)
        if (resultCode == RESULT_OK) {
            // -1 se o valor não extiver presente no Intent (talvez esqueceu do putExtra?)
            textView.setText(data.getLongExtra("TamanhoDaLista", -1));
        }
    }
}

Se na GriViewActivity tiver um botão cancelar e salvar, coloque o código do finish() em salvar e no cancelar use setResult(RESULT_CANCELED).
Answer: Você pode criar uma interface na GridViewAdapter:
    public class SeuAdapter extends RecyclerView.Adapter<SeuAdapter.SeuViewHolder> {

       private SeuAdapter.SeuOnClickListener SeuOnClickListener;

        /**
         * construtor
         * @param context
         * @param seuOnClickListener
         */
        public MesaAdapter(Context context, SeuAdapter.SeuOnClickListener seuOnClickListener) {
            this.seuOnClickListener = seuOnClickListener;
        }

//interface
            public  interface GridViewOnClickListener{
                public  void onClickGridView(View view, int idx);
            }

    //no metodo onBindViewHolder:

        @Override
            public void onBindViewHolder(final MesaAdapter.MesaViewHolder holder, final int position) {

               ...

                if (gridOnClickListener != null){
                    holder.itemView.setOnClickListener(new View.OnClickListener(){

                        @Override
                        public void onClick(View v) {
                            gridOnClickListener.onClickSeu(holder.itemView, position);
                        }
                    });
                }
            }

Ai na outra classe que chama e controla o GridView você faz a declaracao da interface;
    private SeuAdapter.SeuOnClickListener onClickSeu(){
        return  new SeuAdapter.SeuOnClickListener(){
            @Override
            public void onClickSeu(View view, int idx) {
                //execucao
            }
        };
    }

Chamar evento da GridView na Activity


If two graphs are planar, will the cartesian product between them be planar?

Question: I think this question is false, but I am not sure how to prove it. I found the product of two 3-cycles (see diagram). But I don't know how to prove it can't be planar. It passes Euler's formula. I have tried looking for subgraphs that fail the test, but am not finding any.
Comment: Sorry, I'm not sure how to make the diagram smaller.
Comment: I can find a subdivision of a $K_5$ in your graph.  Four of the edges are subdivided.  Remember that in [Kuratowski's theorem](https://en.wikipedia.org/wiki/Kuratowski's_theorem) we need not find a $K_5$ subgraph, merely a subdivision of a $K_5$ to conclude that it is not planar.
Comment: I wasn't taught Kuratowski's theorem. I'm not sure what a subdivision is. Is there a way to prove it without using this theorem?
Comment: A subdivision of a graph is a graph where some number of subdivisions have taken place: a new vertex $x$ is added and an edge $(u,v)$ is removed and replaced by two edges $(u,x)$ and $(x,v)$.  Think of it like taking an edge and drawing additional vertices along it.  What do you mean you weren't taught Kuratowski's theorem?  That is usually one of the very first things mentioned when talking about planar graphs.  Have you at least seen some direct proof that $K_5$ is not planar?
Comment: We did discuss $K_5$ not being planar because the number of edges, $10 \nleq 3(5)-6$.
Comment: You mention Euler's Formula.  You can reason that $K_5$ does not pass the criterion and therefore is not planar.  You can then reason that any graph which contains $K_5$ cannot be planar, and then any graph which contains a subdivision of $K_5$ cannot be planar.  This will then prove the result you want, and is a partial proof to Kuratowski's theorem.  The more difficult part of proving the theorem is that this is in fact an if and only if statement, that not only having a $K_5$ or $K_{3,3}$ subdivision makes it nonplanar, but all non-planar graphs have a subdivision of $K_{3,3}$ or $K_5$.
Comment: The reason being, if a graph containing a subdivision of $K_5$ *were* planar, then using that drawing and removing unnecessary vertices and edges and contracting edges (*the reverse of the subdivision process*) would yield a planar drawing of $K_5$.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/70123/discussion-between-maggy-wood-and-jmoravitz).
Answer: I can find a subdivision of a $K_5$ in your graph.  Four of the edges are subdivided.  Remember that in Kuratowski's theorem we need not find a $K_5$ subgraph, merely a subdivision of a $K_5$ to conclude that it is not planar.  Labeling the vertices $a,b,c,\dots$ instead and removing unnecessary edges:

As there is a $K_5$ subdivision as a subgraph, your original graph too therefore cannot be planar.
Answer: Another counterexample is the hypercube $Q_{d}$ for $d \geq 4$. We note that $Q_{d} = \prod_{i=1}^{d} K_{2}$. In particular, $Q_{4} = Q_{3} \times K_{2}$, and both $Q_{3}, K_{2}$ are planar.
Answer: If we take the Cartesian product of $K_4$ and $K_2$ (both planar), then by identifying the vertices in one of the copies of $K_4$, we get a $K_5$ minor.  Wagner's theorem thus implies it's non-planar.
Another counterexample is the Cartesian product of $K_4$ and $K_4$.  It has $v=16$ vertices and $e=48$ edges, but this does not satisfy $e \leq 3v-6$, which is required by Euler's formula for planar graphs.


Android View fields name convention

Question: For example i have view which have id :
<ImageButton
        android:id="@+id/imageButtonStart"
        android:layout_width="100dp"
        android:layout_height="100dp" />

Does i need made private field with the same name, like this:
private ImageButton imageButtonStart;

Comment: What is the best name convention between xml id and class field?
Answer:
Do I need a private field with the same name?

No, the android:id in the layout xml file does not require you to have a variable with the same name in your code.
But you need to use the exact name if you search for the id
View randomName = findViewById(R.id.imageButtonStart);

Naming is a lot of personal preference. You should chose names that clearly define what the named thing represents. And you should stay consistent with your naming scheme.
How long that name should be is debatable, some people would chose startBtn over imageButtonStart because it's shorter and less annoying in your code. If the fact that the button is an ImageButton is irrelevant to your code, you don't need to name it imageButton, just button would be enough to make it's meaning clear.
Some people like to use names with a hierarchical scheme where the most important distinguisher comes first. Like the Java & Android package names com.google.market instead of market.google.com.
Instead of startButton and endButton, they'd chose buttonStart and buttonEnd. The reason behind this is that way you can use auto-completion more efficient. If you can't remember if you named your end button endButton or stopButton you need to look trough the whole list of proposals. Using the buttonXYZ scheme you can start typing button since you know that it's a button and will get only a few proposals.
Above is also a good example why you should stay consisten. If you name one button buttonStart and the other clickablethingStop the whole scheme is useless. Inconsistent naming requires more time to find the correct thing and can lead to bugs if you chose the wrong thing.
Another thing is the language you use for names. It is perfectly okay to use your own language if you write code just for yourself or people that speak the language. But once you want to share it with others stay with english. Even incorrect english naming is easier to read and understand than names in a language that you don't understand at all.
There are also a lot of other naming conventions out there: WP:Naming conventions
For example Android coding syle guide states:

Non-public, non-static field names start with m.
Static field names start with s.
Other fields start with a lower case letter.
Public static final fields (constants) are ALL_CAPS_WITH_UNDERSCORES.

It would be private ImageButton mButtonStart; or private static sSingletonThing;
That convention is by the way only required to be used if you want to contribute to the Android sourcecode, you can write your own apps in any style.
The only naming convention that you should really follow is the general Java Class/Method/variable schema: (from above wikipedia link)

Class names: UpperCamelCase
Method names: lowerCamelCase
Variable names: lowerCamelCase
Constants: ALL_CAPS

It starts to get very confusing for other people if they read your code and you have lowercase class names etc.
Comment: What is the better name for class fields in that case.
Comment: @testCoder Using the same name is a good approach. The names you use in your code are completely up to you. But you can help yourself if you use names that don't confuse you. Just `startButton` for example should be clear that it is the start button in your layout.
Answer: Although it is good practice to keep things consistent and use the same name for your variable, you do not need to call your class variable the same as the id within your XML, as you'll manually connect these up within your code such as:
ImageButton imageButtonNotStart = (ImageButton) this.findViewById(R.id.imageButtonStart);

My personal preference is use to the format componentTypeDescriptiveName such as imageButtonStart within the XML, but within code I prefer a more English driven approach, such as startButton.
Typically I end up with
<ImageButton
        android:id="@+id/imageButtonStart"
        android:layout_width="100dp"
        android:layout_height="100dp" />

ImageButton startButton = (ImageButton) this.findViewById(R.id.imageButtonStart);

Android View fields name convention


Integration of a rational function

Question: Evaluate the following integral.
$$ \int \frac{x^4}{x^2-16}\ dx $$
My try :
I did the long division and I got $ \frac{x^4}{x^2-16} = x^2+16 + \frac{256}{x^2-16} $
$$ \int \frac{x^4}{x^2-16}\ dx $$
$$ \int x^2\ dx + \int 16\ dx +\ 256\int \frac{1}{x^2-16}\ dx$$
$$ \frac{x^3}{3} + 16x + 256\  ln\ |x^2-16| + C $$
But the answer in the book is
$$ \frac{x^3}{3} + 16x + 32\ \ln\ |x-4| - 32\ \ln\ |x+4| + C $$
What did I do wrong ?
Comment: Please elaborate the long division. Do you assert $\frac{x^4}{x^2 - 16} = \frac{256}{x^2 - 16}$?
Comment: No Sorry that was a mistake. I edited it. $ \frac{x^4}{x^2-16} = x^2+16+ \frac{256}{x^2-16}$
Answer: Try partial fractions:
$\frac{x^4}{x^2-16} = x^2 +16-\frac{32}{x+4}+\frac{32}{x-4}$.
Comment: How is  $ \frac{256}{x^2-16} = -\frac{32}{x+4}+ \frac{32}{x-4}$ ?
Comment: Just multiply the right hand side out, and notice that $x^2-16=(x+4)(x-4)$.
Comment: I don't understand. Why don't i just take the 256 outside of the integral sign and then integrate $ \frac{1}{x^2-16} $ which will equal $ ln\ |x^2-16|$ ?
Comment: One reason is that integrating ${ 1\over x^2 -16}$ will not result in $\ln |x^2-16|$.
Comment: Since $\frac{256}{x^2-16} = -\frac{32}{x+4}+ \frac{32}{x-4}$, you have $\int \frac{256}{x^2-16}dx = -32 \ln |x+4| + 32 \ln |x-4| +C$.
Answer: your method is right but in integration of
  $$\int\frac{1}{x^2-16}dx=\int\frac{1}{(x-4)(x+4)}dx=\int\frac{1}{8}[\frac{1}{x-4}-\frac{1}{x+4}]dx$$
$$=\frac{1}{8}[ln(x-4)-ln(x+4)]$$
Hence $$\int\frac{x^4}{x^2-16}=\frac{x^3}{3} + 16x + 256.\frac{1}{8}[ln(x-4)-ln(x+4)]+C$$
$$=\frac{x^3}{3} + 16x +32ln(x-4)-32ln(x+4)+C$$
THANKS
Comment: That was what I stated in my answer?
Comment: How did you get from $ \int \frac{1}{(x-4)(x+4)}\ dx $ to $ \int \frac{1}{8}[\frac{1}{x-4}-\frac{1}{x+4}\] dx $ ?
Comment: Partial fractions.

Integration of a rational function


On a module Issue page, how do you tell what version the patch has been applied in?

Question: Much of the time, take this field collection migration issue for example, when I find an issue with a drupal module, there has already been an issue filed, and in some cases the issue has a status of Closed (fixed).  In the sidebar there is a version mentioned.  It seems likely that that version is the one you set when you file the issue, specifying which branch of the code you saw the issue in.
When the issue has been Closed (fixed), does that mean that if you grab the specified version, that the code will include the patch?  Is there any way of knowing when a fix has reached the stable branch?
Comment: Patches are always applied to the dev branch (8.x-1.x). I can't remember the rules regarding your follow-up.
Comment: A closed issue does not mean that any patch provided on the issue queue has been applied anywhere. Also, fixes and patches are applied to any branch not only to the stable one.
Comment: I would have assumed that closed **(fixed)** means that if there was a successful patch in the thread that it has been applied to the branch.
Answer: As mentionned by Eyal a patch is always applied to the -dev version of the module. That's already a good stuff to know.
So yes, if a patch is committed you can download the -dev version specified in the issue (or apply the patch separately if needed).
Usually the patches included in a new release are listed in the changelog:
.
note:
normally once a patch is committed the issue status becomes "closed (fixed)" and you will ind this kind of details in the latest issue comments:

In the sidebar of the presentation page of the module the "View pending patches" can be helpful to check if the issue you are looking for is still opened or fixed. There is also the "Views commits" link for a quick overview. this page provides a detailed list of the patches implemented (issue date, version , description, id).
--
The official doc https://www.drupal.org/issue-queue/status could also help you to understand the process.
Comment: Thanks this is useful, do I need to ask a seperate question to find out about how to tell when a fix goes into the stable branch?
Comment: you can enable the "update manager" module on your drupal website to be notified of new release (stable or dev). From there you can access the changelog and see if the patch you are looking for has been added.  A patch committed to the dev is generally added in the next release. If not there is probably an explanation on the issue comments. It is also good to know that for every issue you can clik the "follow" button (below the summary block on the right sidebar). You will find the list of followed issues in your dashboard on drupal.org. This is one way..there are others (with git for eg).
Comment: The thing is, when I find an issue that has been closed (fixed) I would like to know the status. Is it still just in dev or has isn't made it to stable already.
Comment: by reading the changelog. You can also compare the date of the release and the patch. The version number of a module helps you too. ex the patches of fieldcollection 7.x-1.0-beta9 have probably been included in the 7.x-1.0-beta10. Maybe this out of the scope  but It worth to mention that GIT is your friend for this kind of questions.
Answer: Patches are not always applied to the dev branch. This is not the case always although it would be. For example there may be 2.x and 1.x version or maybe the stable release is 1 year ahead from the dev branch etc.
The official rules for submitting patches can be found here: Submitting patches.
In reality the patches refer to the version (release or branch) that issued the patch. See the example. And the naming rules say that you should add the project branch in the patch name too!
When you create an issue on D.O. you are obligated to enter the project version that issued the issue. So any patches submitted there refer to the "version of the issue". When the branch is the dev branch which changes often the patch need to change often too! That's why you see so many patches for an issue if it is not closed soon.
Also, D.O. has a special bot that takes patches from issues and apply them to the project so every patch has a pass status. See more at Drupal.org Testbots.

D.O. : Drupal.org
Comment: If the issue refers to a stable branch (let's say 7.x-1.0) the patch should refer to that branch too (7.x-1.0). Saying that someone should apply the patch only for the current stable release (7.x-1.0) and testing etc will happen for this release (7.x-1.0). In practice someone downloads (or clones from git) the 7.x-1.0 version of the module and then applies the patch. The same to create the patch.
Comment: It depends to the workflow of each module and the development process each module maintainer follows. It would be nice to have fix-dev->dev->stable but this does not happen always. The most **critical point for patches** is to work properly (have (simplytest) tests to verify that and have too many users also to verify that the patch is working normally) so maintainers can use them on the future releases.
Comment: I'm not sure I entirely follow.  If I filed a bug against the stable branch, how would patching go?
Comment: So does that mean a fix is more likely to be released on the stable branch quickly if it was reported against the stable branch?  Or is the process generally to merge the dev branch back into stable before making the next stable release?


Stream pdfs from url and add it to Zip

Question: I have a mvc 4.5 application where I show a grid. The first column of the grid is a document name. The document name is an hyper link to the actual document that is hosted on our site and is available via a url. The documents can be pdf or doc or ppt. I can access these documents only via url and I do not have access to the actual physical document on our server.
I am providing users an option to select one or many of these documents from the grid and then they can download them. What I am trying to achieve is read each of the selected documents via the url and write it to a zip file and make the zip file downloadable. So users will be downloading one file instead of multiple files.
I have tried to stream the documents via url in memory and then add it to the zip file using ZipArchive Library from Microsoft. This is not working for me.
I was able to add documents that was on disk to zip file using Zip Archive and it works great. But I do not have access to the physical document as I can access the documents only through URL. My next option is to download each of these documents into a temp location on server and then add it to zip file using Zip Archive.But I am trying to avoid downloading files into a temp location
Please suggest how I can achieve reading documents via url in memory and adding each of these document to zip file and make zip file downloadable.
Any help will be appreciated.
Comment: You can feed data directly into `ZipArchive::addFromString` – so all you need to do is get the contents from the URL into a string variable first (and that should be trivial, resp. easy enough to research.) Should you be handling files that are so large that they don't fit into memory, then you might need a different approach though. Plus, even though you are against downloading the files to your server first – that might be more efficient, than downloading the same file over and over again each time a user requests it (which will also mean longer waiting time for the user.)
Answer: Thank you Cbroe for commenting. I figured the answer. The problem was I was reading the pdf from the url and convert it to a memory stream and then was trying to add the memory stream to ZipArchive which was not working but instead I extracted the byte array out of the memory stream and then added it to the zip archive and it worked.
Here is the code snippet that might be useful for some one. My first contribution to Stack OverFlow.
<code>public FileResult DownloadZip()
    {
        MemoryStream memoryStream = new MemoryStream();

            using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
            {
                var demoFile = archive.CreateEntry("Pdf123.pdf");
                var convertedStream = ConvertTobyte("http://www.example.com/Pdf123.pdf");

                using (var entryStream = demoFile.Open())
                {
                    entryStream.Write(convertedStream, 0, convertedStream.Length);
                }

                demoFile = archive.CreateEntry("Pdf456.pdf");
                convertedStream = ConvertTobyte("http://www.example.com/Pdf456.pdf");

                using (var entryStream = demoFile.Open())
                {
                    entryStream.Write(convertedStream, 0, convertedStream.Length);
                }
            }
//This option is to write the zip to your local disk
            using (var fileStream = new FileStream(@"C:\Temp\test.zip", FileMode.Create))
            {
                memoryStream.Seek(0, SeekOrigin.Begin);
                memoryStream.CopyTo(fileStream);
            }
//This option is to donload the zip via browser
            memoryStream.Seek(0, SeekOrigin.Begin);
            return new FileStreamResult(memoryStream, "application/zip")
            {
                FileDownloadName = "Archive.zip"
            };
    }

    private static byte[] ConvertTobyte(string fileUrl)
    {
        byte[] imageData = null;
        using (var wc = new System.Net.WebClient())
            imageData = wc.DownloadData(fileUrl);
        return imageData;
    }
</code>

Stream pdfs from url and add it to Zip


Angular 2 hide component selectors

Question: When examining Angular 2 Apps like Google Maps or YouTube i never see any component selectors like  or  in html source.
Is this default for production build? Or is it always needed for Angular 2 to work?
I got three problems with this:

They dont look good (minor)
They reveal my app is Angular 2 (minor)
They break the CSS layout e.g. when using flexbox (major)
Answer: It's always needed. Google Maps and YouTube are not made with angular. Check https://material.angular.io/. This site from google/angular is made with angular. If you inspect the elements you see all the selectors: <app-homepage>, <router-outlet>.. etc. That's just how it works. They are not going to port such big code bases as Google Maps or YouTube to a new framework :)

It actually gives a nice semantic structure if you ask me, instead of a random div you get a component selector. So you know exactly what that component is doing.
Yes, you are using the latest technology out there, can't really be a negative :)
In what way are they breaking your layout? If they are, it kinda means you are not using it right, or you are expecting a different result than given. Perhaps post a code example or a fiddle where it 'breaks' for you?
Comment: There are some questions out there for #3. And I don't like the workarounds tbh.
Comment: I use flex throughout my entire application, and never had issues with it. Or at least, the html acted like i expect it to act. Perhaps you can use [**this**](https://github.com/angular/flex-layout)?
Comment: If a container has display:flex and the child ist  instead of the real child the flex-layout is broken.

Angular 2 hide component selectors


Como apontar para um arquivo FXML no javafx

Question: Criei um projeto do zero, estava sem nenhuma pasta e abria a janela perfeitamente, porém quando eu coloquei dentro de 7 pastas e então começou a não carregar. Alguém sabe como eu apontaria? Estou utilizando o Scene Builder tambem.
A arvore é assim:
projeto
└───src
    └───br
        └───com
            └───mask
                └───tarefas
                    └───login
                        └───LoginSystem (arquivo que tem que apontar para o FXML)
                        |
                        └───layout
                            └───LoginFXML (ArquivoFXML que tem que ser apontado)

A classe que aponta é essa:
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class LoginSystem extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("LoginFXML.fxml"));

        Scene scene = new Scene(root);

        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

Comment: Em que pasta o arquivo ```LoginFXML.fxml``` está?
Comment: Esta na ultima pasta,layout, ja o System que chama ele esta uma pasta antes, login
Answer: Bom, resolvi apontando o arquivo controller dentro do arquivo FXML
<AnchorPane id="AnchorPane" prefHeight="200" prefWidth="320" xmlns:fx="http://javafx.com/fxml/1"
            fx:controller="br.com.mask.tarefas.login.layout.LoginFXMLController">

E logo depois criei uma URL dentro do arquivo LoginSystem(arquivo que aponta para o FXML) e coloquei ele dentro do Pane ao inves de criar la dentro.
URL arquivoFXML = getClass().getResource("/br/com/mask/tarefas/login/layout/LoginFXML.fxml");

    @Override
    public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(arquivoFXML);

Comment: Recomendo vc criar uma classe utilitária que tenha um método em que vc passe ```"LoginFXML.fxml"``` e ele retorne ```"/br/com/mask/tarefas/login/layout/LoginFXML.fxml"```, se não você vai ter que repetir esse caminho toda vez que você for carregar um arquivo FXML.


Optimizing logistic regression with a custom penalty using gradient descent

Question: I'm trying to fit a logistic regression model on a certain dataset. I want to ensure the learned model is smooth, that is samples which belong to the same cluster/group according to a prior knowledge/graph get similar output. I'm also looking for a model with a sparse coefficients. Hence I have come up with the following loss function that takes into account the above requirements:
$$
\mathfrak{L(\mathbf{\beta })} = \underbrace{-\sum_{i=1}^{m}y_{i}\beta^{T}x_{i} + \log{(1 + e^{\beta^{T}x_{i}})}}_{logloss} \ + \ \lambda_{1}\left\|\beta \right\|_{1} + \lambda_{2}f^{T}Lf
$$
In above equation, the smoothness penalty is the $f^{T}Lf$ term, whereas $\lambda_{1}$ and $\lambda_{2}$ are regularization terms. $L$ is a Laplacian matrix of the graph formed from the samples and $ f = sigmoid(\mathbf{\beta}^{T}\mathbf{X})$. If the loss function was made up of only the log loss and the smoothness penalty, I can easily use gradient descent to optimize it since these functions are convex functions (because $L$ is positive definite matrix). But with the addition of the L1 penalty ($\left\|\beta \right\|_{1}$), the whole loss funciton can not be optimized using gradient optimization as $\left\|\beta \right\|_{1}$ is not a smooth function.
How can I use gradient descent in this case? or are there any alternative suggestions to optimize the above loss function?
Comment: See [this example](https://web.stanford.edu/class/ee364b/lectures/subgradients_slides.pdf) of the subgradient for $f(x) = |x|$, slide 6; [this](https://web.stanford.edu/class/ee364b/lectures/subgrad_method_slides.pdf) provides a primer on subgradient methods, which should look familiar if you've seen standard gradient descent.
Comment: Compare with elastic net.
Comment: Adding the $\lVert \beta \rVert_1$ term maintains convexity, no? Since the $\ell_1$ penalty still has a well-defined *subgradient,* this should still converge with subgradient descent (same as gradient descent, except at $\beta = 0$) given appropriate initialization and learning rate schedule.
Comment: Thanks for your suggestions. I was able to find a solution as explained in my answer below
Answer: I used the methodology in this paper where they improve upon GLMNET to solve L1 regularized logistic regression. Since $f^{T}Lf$ is twice differentiable, I added its gradient and hessian to the solution in equation 11 of the paper. Someone has already implemented the code for the paper here which I've built upon. You can find my changes here


Update table row using JQuery with textbox checking and I need to check the textbox values

Question: This is my JQuery while button click I append the table row in that table having textbox I need to check that textbox value while focus out please some one help me friends
My html Code friend

                Receied From

                <%: Html.TextBox("RecFrom", null, new { @class = "onlyname", id="RFrom" })%>

                 Received Date

                <%: Html.TextBox("RecDate", null, new { @class = "date", id="Rdate", @readonly = "readonly" })%>

                <%: Html.Label("External Referance") %>
                <input type='text' id='Exref' name='ExternalReferance'>

                <%: Html.Label("Referance Date") %>
                <input type='text' id='RefDate' class='date' readonly='readonly'>

                <%: Html.Label("Impact Of Payment") %>
                <select id='Impact' name='Impact' class='dropdown'><option>NO</option><option>YES</option></select>

                <%: Html.Label("Impact By Date") %>
                <input type='text' id='impactdate' name='Impactdate' class='date' readonly='readonly'>

                <%: Html.Label("Impact By Amount") %>
                <input type='text' id='Amount' name='ImpactAmount' class='Number'>

         <input type="Submit" value="Next" id="btn"/>

My JQuery is
     $(document).ready(function ()
         $('#btn').click(function (){
             $('#ProductRecipt tbody').append("
" + ItemCode + "<input type='hidden' name='ItemCode' value='" + ItemCode + "'/>	" + $('#Cat').val() + "<input type='hidden' name='ItemName' value='" + $('#Cat').val() + "'/>	" + $('#RFrom').val() + "<input type='hidden' name='ReceviedFrom' value='" + $('#RFrom').val() + "'/>	" + $('#Rdate').val() + "<input type='hidden' name='ReceviedDate' value='" + $('#Rdate').val() + "'/>	" + result.Quantity + "<input type='hidden' class='TotalQuantity' value= '"+ result.Quantity +"'>	<input type='text' class='Rqty' name='ReceviedQuantity'>	<input type='text' name='Remarks' style='widht : 75px;'>	<input type='button' class='remove' value='remove'/>
");
           });
       $('#ProductRecipt tbody').on('focusout', '.Rqty', function () {
        var qty = $(this).parent($('#ProductRecipt tbody .TotalQuantity').val());
        alert(qty);
        var rqy = (this).val();
        alert(rqy);
        if (qty > rqy) {
            alert('Enter Minimum Quantity');
            return false;
            $(this).focus();
        }
      });
   });

Answer: Try this:
$(document.body).on('mouseout', '#ProductRecipt tbody .Rqty', function() {
 var qty = $(this).parent($('.TotalQuantity').val());
    alert(qty);
    var rqy = ('.Rqty').val();
    if (qty > rqy) {
        alert('Enter Minimum Quantity');
        return false;
        $(this).focus();
});

Comment: Friend document.body means it can get all table body tags may i right
Comment: I have modified the selector.Please check now
Comment: @Dinesh:would be great if you create some fiddle
Comment: How to Create fiddle friend
Comment: put your code at http://jsfiddle.net/. run and check the output. then save and give the link.
Comment: Ya friend i put it but it does not save and i cannot view the result also
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/45103/discussion-between-milind-anantwar-and-dinesh)
Answer: I think that this is what you need:
$(document).on("focusout", ".Rqty", function() {
    alert($(this).val());  // do the validation here
});

Comment: I having 2 textbox which textbox value is getting
Comment: The one that is focused out.
For example if you click on the textbox and then click out or pres tab or leave the box somehow it will trigger the event.
$(this).val() - represents the value of the text box
Comment: ok then how to compare the value at the same row but another textbox value
Comment: If you have only one field of a given class on the same row you could do something like this:

var the_value_of_the_other_box = $(this).parents('tr').find('.your_class_name').val();
alert(the_value_of_the_other_box);
Comment: You don't need to use the "tbody" selector when operating with tables on jQuery. This should work just fine:
$('#ProductRecipt').append('your_html_code');


Como apresentar o resultado de um formulário na mesma pagina?

Question: Tenho um formulário que me dá o resultado em outra página, mas gostaria que o resultado aparecesse na mesma página.
 <form name="calc" method="get" enctype="multipart/form-data" action="resultado.php"> <input type="text" id="Peso" name="peso" required="">
        <input type="text" id="Altura" name="altura" required="">
        <input type="text" id="Peso" name="peso" required="">
        <input type="submit" class="button-green" value="CALCULAR">
</form>

resultado.php

        <?php
$peso = $_GET['peso'];
$altura = $_GET['altura'];

$conta1 = $altura*$altura;
$conta2 = $peso/$conta1;

$resultado = number_format($conta2);

if(isset($resultado) && $resultado != '0'){;
echo '
Seu IMC é:
';
echo '
'.$resultado.'
';
}else{
echo '
Por favor, utilize apenas numeros!
';
}
?>

Answer: Você precisa:

Adicionar o código de resultado.php no mesmo arquivo do formulario.
Deixar o action vazio ou colocar # no form.
Verificar se existe algum valor em $_GET, use empty() para isso.

Um exemplo simples:
<?php
ini_set('display_errors', true);
error_reporting(E_ALL|E_STRICT);

if(!empty($_GET) && $_SERVER['REQUEST_METHOD'] == 'GET'){
    $nome = $_GET['nome'];
    echo 'valor recebido: '. $nome;
}
?>

<form action="#">
    <input type="text" name="nome" />
    <input type="submit" />
</form>

Answer: Você pode utilizar o método PHP_SELF, mas é preciso alterar mais alguns detalhes no seu código:
1 - Utilizei o método post, (mas você pode usar o GET) e verifiquei com isset se a variável $_POST não estava vazia, pois, caso contrário, como disse o @rray, já na primeira vez que abrir a página vai aparecer o resultado considerando os campos com 0 e 0.
2 - Pelo que entendi, tem um campo a mais no seu HTML (duas vezes o campo peso).
3 - A formatação da saída com o number format requer 3 parâmetros, e você não estava passando nenhum.
Segue abaixo o código normalizado com o que acho que é o comportamento que você espera:
<form name="calc" method="post" enctype="multipart/form-data" action="<?php $_SERVER['PHP_SELF'] ?>">
     Peso
    <input type="text" id="Peso" name="peso" required="">

     Altura
    <input type="text" id="Altura" name="altura" required="">

    <input type="submit" class="button-green" value="CALCULAR">
</form>

    <?php
    if (isset ($_POST)) {
        $peso = isset($_POST['peso']) ? $_POST['peso'] : false;
        $altura = isset($_POST['altura']) ? $_POST['altura'] : false;
        if (isset($peso) && $peso > 0 && isset($altura) && $altura > 0) {
            $conta1 = $altura * $altura;
            $conta2 = $peso / $conta1;
            $resultado = number_format($conta2, 2, ".", ",");

            var_dump($altura);
            var_dump($peso);

            if (isset($resultado) && $resultado != '0') {
                ;
                echo '
Seu IMC é:
';
                echo '
' . $resultado . '
';
            }
            if (isset($resultado) && $resultado < 17) {
                echo 'é menor que 17';
            } else {
                echo '
Por favor, utilize apenas numeros!
';
            }
        }
    }
    ?>

Veja no Ideone o IMC de um magricelo. :)
Comment: Então, isso é praticamente outra pergunta... De qualquer forma, eu falei sobre isso na resposta (dá uma olhada no código)... Você colocou os parâmetros do `number format`? A variável `$resultado` está assim: `$resultado = number_format($conta2, 2, ".", ",");` ? Detalhe importante: Na entrada (no campo `input`) tem que estar com `.` e não com `,`...
Comment: Então, mas tem que estar assim: `$resultado = number_format($conta2, 2, ".", ",");`.
Comment: :P olhe como está o `method` do seu form. Lembre de validar se vem algo na requisição, se não ao acessar a primeira vez é gera um warning de undefined index: x. De resto é isso ai :) +1
Comment: Então @kaiquemix, é melhor você criar outra pergunta. O SOpt funciona como um repositório de dúvidas sobre programação, e foi idealizado para ajudar outros usuários que tenham as mesmas dúvidas. Mas não se acanhe, pode fazer quantas perguntas quiser, desde que elas sejam objetivas, bem formatadas, etc... da forma como você fez esta. :)
Comment: É difícil responder em comentário, o melhor é você criar outra pergunta, mas tenta `if (isset($resultado) && $resultado < 17) { echo 'é menor que 17'; }`...
Comment: hehe Sim, eu tava vendo isso depois que li a sua resposta... vou editar aqui  valeu +1
Comment: obrigado amigo deu certo :)
Comment: tenho outra duvida para colocar if com botão radio podemos ir chat?
Comment: eu estou tentando fazer algo assim:
    if (isset($resultado) < 17) {
        echo 'é menor que 17';
    }

porem não aparece nada..
Comment: @gustavox como faço para o resultado tbm ser numero quebrado pois posso colocar 1.80 e 50.0 e o resultado só aparece inteiro
Comment: ta assim:  $resultado = number_format($conta2);
Comment: coloquei obrigado :)
Answer: Tente:

<?php

if ( count( $_GET ) && isset( $_GET['peso'] ) && isset( $_GET['peso'] ) ) { ?>
    // Digite o código do cálculo do resultado aqui
    Fazer novo cálculo
<?php } else { ?>
    // Digite o código do formulário aqui
}


If $a_{n_k}$ denotes a subsequence of $a_n$. Why is $n_k \geq k$ for all $k$.?

Question: I am trying to prove that If a sequence converges, then every subsequence converges to the same limit. Now going in the backwards direction, I know it is true because the sequence is a subsequence of itself. But what about proving if a sequence converges then every subsequence converges to the same limit.
I do not understand the notation $a_{n_k}$, $a_n$, $n_k$ and $k$
I know that subsequence need to be in order just like in the original sequence. Can someone please clarify the notation and explain why  $n_k \geq k$ for all $k$.?
Comment: the indexes of the subsequence are strictly increasing, thus $n_{k+1}-n_{k}\ge 1$ summing this telescoping sum gives $n_k\ge k$.
Comment: Pigeonhole principle.
Answer: I will assume that the indices of the original sequence start at $0$; the proof is almost identical if they start at $1$ (or indeed at any other integer). Clearly $n_0$, the index of the first term of the subsequence, must be at least $0$: $n_0\ge 0$. Now suppose that $n_k\ge k$ for some $k$. We must have $n_{k+1}>n_k$, and $n_{k+1}$ and $n_k$ are both integers, so $n_{k+1}\ge n_k+1$. Finally, $n_k\ge k$, so $n_{k+1}\ge n_k+1\ge k+1$. By induction we conclude that $n_k\ge k$ for all $k\in\Bbb N$. (For me $\Bbb N$ includes $0$.)
Comment: Hi professor Scott, thanks for answering. so $n$ is the index of the sequence, $n_k$ is the index of the subsequence then what is $k$?
Comment: @Negrawh: The subsequence is $\langle a_{n_0},a_{n_1},a_{n_2},\ldots\rangle$, so $k$ is the index of the term in the subsequence, and $n_k$ is the index of that same term in the original sequence. And $\langle n_k:k\in\Bbb N\rangle=\langle n_0,n_1,n_2,\ldots\rangle$ is the sequence consisting of the indices of the terms in the original sequence that we are keeping in the subsequence.
Answer: The $n_k$ ($k=1,2,3,\ldots$) are a subsequence of $\Bbb N$, i.e., $n_1\ge 1$ and for all $k$, $n_{k+1}>n_k$. Then $n_k\ge k$ follows by induction.


What function describes this problem of every possible breeding of a set of dogs?

Question: If I have n dogs [a, b, c, ...], and I want to breed them in every possible combination (every possible binary tree made of nodes [a, b, c, ...]), how many different end-result puppies are possible? (edit: gender doesn't matter, any dog can breed with any dog, so, unrealistic, but more general.)
I can't quite wrap my head around it, but I started thinking there are n! possible puppies with exactly the same parents, but bred in a different order.
I get that by taking every permutation of n dogs, and each couplet's offspring breeds with the next couplet's offspring, and so on. But that doesn't quite answer it since, given the same starting permutation, I can have many binary trees (ex some deep, some wide). I'm thinking that there are log2 n different binary trees for one given permutation. But that doesn't always give whole numbers...
So, the best I've got is n! * log2(n), but that can't be right.
Thoughts?
(PS, not homework, I'm a nerd, and my wife and I are buying a puppy :) )
edit2: a note on genetics, obviously, the exact same tree will yield different puppies every single time because of how genes/meiosis/crossover works. I'm really interested in the general case. How many different trees are there, with each parent represented once.
edit3: Is the correct answer the Catalan numbers? (IE every possible binary tree given a set of count=n) (2n)!/(n!(n+1)!) oeis.org/A000108 and https://stackoverflow.com/a/16004841/3884713?
Comment: You need to know how many males and females there are. If for example there is 1 male then there are n-1 possibilities while for 2 males there are 2.(n-2).
Comment: @TomCollinge: good point, I can't believe I missed *that*. I edited it. To make it more general, what if we considered that any dog can breed with any dog.
Comment: Well I suppose this is the world we live in today !
Comment: You need to think about the restrictions a bit.  It doesn't seem that order should matter-should abcd be different from dcba?  At the first round you probably want to prevent a dog from breeding with itself, so you can't have aa in an odd/even location.  After that it should be ok, as you could have two ab's in the first round, so you could get abab in the second.
Comment: @RossMillikan: good point on ordering, I think that since I want to count the possible end result puppies, surely "flipping" the tree doesn't make a difference, any isomorphic tree will yield the same end puppy (or I guess, the same distribution of puppies). Is my intent unclear in the wording?
Comment: Your use of $n!$ seems to say we should care about order.  Note that a $k^{th}$ generation dog will have $2^k$ parents, which solves your $\log_2$ being non-integral.  I think we have a partition problem if we ignore the first round same parent issue.
Comment: upon further research, is the correct answer this: https://oeis.org/A000108 ?
Comment: I don't think it can be that sequence because it has to depend on two variables-the generation and the number of starting dogs.  That sequence only depends on one.  It seems to me that aabc should be different from abcc because the first has twice as many genes from a
Comment: @RossMillikan: one parent shouldn't be represented twice though, right? If that's not what you meant, could you clarify?
Comment: Yes, I think it can be.  Maybe a and b mate to make ab and a and c mate to make ac in the first round.  Then if these two mate, you get half your genes from a and one quarter from b and c. That would be different from getting half from c and a quarter from a and b.  But that is my reading of the question and there are other reasonable ones.
Answer: It seems that you are concerned about fractions of the parentage that each of the $n$ dogs contribute to a given puppy.  A $k^{\text{th}}$ generation puppy will have $2^k$ ancestors, who may be repeated.  You are looking at weak compositions of $2^k$ into $n$ parts-you express $2^k=A+B+C+\dots N$ where the capital letters represent how many of that type of parent there are.  There are ${2^k+n-1 \choose n-1}$ of these.
A subtlety is that you probably don't want the same dog breeding with itself in the first round.  After the first you don't worry, because there could be two ab puppies in the first round to breed together.  This will impose the restriction that no part can be larger than $2^{k-1}$ but all others will be possible.  We can note that only one part can be larger than that, so compute the number of strings that have too many a's and subtract $n$ times that.  The number of compositions that have $i$ a's is just the number of weak compositions of $2^k-i$ into $n-1$ pieces, so ${2^k-i+n-2 \choose n-2}$  We have to sum this from $i=2^{k-1}+1$ to $i=2^k$, so we have
$${2^k+n-1 \choose n-1}-n\sum_{i=2^{k-1}+1}^n{2^k-i+n-2 \choose n-2}$$
Comment: Your answer's a little beyond me, and I will study it. To make sure our understanding is aligned, if I have [A B C D E], and I breed A+B to make AB, now A and B cannot breed any more, and I'm looking at all trees possible with [AB  C  D  E]. And find all of those. Is that your understanding of the problem?
Comment: So, is this the way you're thinking? `[AAAA BBBB CCCC] -> [AABC, ABBC, ABCC]`, or is that the right way of thinking about it?
Comment: Or parents = `[8A 8B 8C 8D]`, and end-results of `[4A-2B-1C-1D, 4A-1B-2C-1D, 4A-1B-1C-2D, 2A-4B-1C-1D, ...]`
Comment: Once you mentioned thinking in strings, and fractions of parentage, that makes me to think of the above, where each parent's fraction is represented by the count of their corresponding letter. But you mention no parent can have more than `2^(k-1)` genes represented, but shouldn't it simply be that they can't have more than `1/2`?
Comment: As a fraction it can't be more than 1/2, if you have discrete generations. I was working with the number of characters. If your starting population has a number of a's that restriction goes away and it gets easier


Getting child node value of child's child

Question: Below I have code to find the node value of 'TheNode'. I need to adapt that code so that it gets the node value of <Child>. How can this be done?
XML:
<BigParent>
    <Parent>
        <Child>Please get my value!!!</Child>
    </Parent>
</BigParent>

JavaScript (that needs changing (so I can find <Child> value)):
$(data).find('TheNode').each(function() {
  var childNode = this.childNodes[0];
  var childNodeValue = childNode.nodeValue;
});

Thanks
Answer: $(data).find('TheNode').children().first().text();
Comment: You may prefer to use `.text()` instead of `.html()`.
Comment: Afaik `html()` fails on XML documents.
Comment: And what happens if I need say the 7th value rather than the first? (Just out of interest)
Comment: @JoelKidd instead of using .first() you could do .get(7) to get the 7th element in his answer
Comment: Joel: you can use `.eq(7)` or `.eq(n)` instead of `.first()`
Comment: @HamzaKubba Thanks very much. Shall select as best answer when the timer is up. :)
Comment: Frank: `.get(7)` may work but it note that it doesn't return a jQuery object:
http://stackoverflow.com/questions/4709660/jquery-eq-vs-get
Answer: jQuery("<BigParent><Parent><Child>Please get my value!!!</Child></Parent></BigParent>").find("Child").text()

returns the value


Let $a,b>0$ be real numbers satisfying $a^2+b^2=2$. Prove that $a+b \leq 2$.

Question: I've tried messing around with some AM-GM stuff but I can't think of anything else for this. Can I get a proof for Real numbers? (I had a proof for rationals but can't work for reals).
Comment: Hint:

$$2(a^2+b^2)=(a+b)^2+(a-b)^2\ge(a+b)^2$$
Answer: Let $a^2+b^2\le 2$, then
by AM-RMS inequality $$\frac{a+b}{2} \le \sqrt{\frac{a^2+b^2}{2}} = 1 \implies (a+b) \le 2.$$
Answer: Use C-S,
$$
2(a^2 + b^2) \geqslant (a + b)^2\Rightarrow4\geqslant (a + b)^2 \Rightarrow2\geqslant a + b
$$
This is true for all real numbers.
Answer: Just another graphic approach.
If you plot $x^2+y^2=2$ you'll get the circumference of center the origin and radius $\sqrt2$.
If you calculate the tangent of this curve at $(1,1)$, you'll get $x+y=2$.
So the whole circle $x^2+y^2=2$ lies on the semiplane $x+y\le2$ (in fact, the circle on "touch" the line). So $x^2+y^2=2$ implies $x+y\le 2$.
MOREOVER.
With the same technique, plotting the tamnget line to the circle at $(-1,-1)$, you'll get $x+y=-2$. So $x^2+y^2=2$ implies $|x+y|\le 2$ and the equality olds if and only if $x=y$.
ANALITICALLY:
$x^2+y^2=2$ $\iff$ $2x^2+2y^2\pm 2xy =4$ $\iff$ $(x^2+y^2+2xy)+(x^2+y^2-2xy)=4$ $\iff$ $(x+y)^2+(x-y)^2=4$.
But $(x+y)^2\le (x+y)^2+(x-y)^2=4$, so $(x+y)^2\le 4$ whence $-2\le x+y\le 2$ and you're (another time), done.
Answer: Polar coordinates.
Let $a=r\sin t;$ $y=r \cos t,$ where $r=√2.$
Maximize $a+b= r(\sin t +\cos t);$
$√2(\sin t +\cos t)=$
$√2(√2(\sin (π/4+t)) \le 2 \cdot 1.$


Class imbalance, Random Over/Undersampling and the use of Class Weights and bias

Question: I was looking at the Tensorflow tutorial on "Classification on Imbalanced Data". Now they first show how to apply some approaches to deal with imbalance using model weights and a pre-initialized bias that conforms to the level of imbalance in the dataset. The tutorial uses logistic regression.
The second approach that they show involves Random Oversampling of the data to include more of the minority class. This approach seems very promising since I have a very very imbalanced dataset.
My question was, if I am training using Random Over/Undersampling, should I keep the class weights in the loss function? Should I keep the bias initializer, or not? I was not sure whether having class weights and biases would impair the over/undersampling? Seems like this would just make the system learn the weights faster, but it might also promote overfitting if the classes are more balanced.?
Answer: No. After you use resampling, you get 50% positive and 50% negative samples. If you calculate the bias and class_weight, the bias should be zero and the class_weight is (0.5,0.5). Hence they are indeed useless in your optimization.
Answer: You should adjust the weights/bias according to the final class balance in your model. In other words, if you correctly balance the classes by over/under sampling, you do not need to adjust the weights or bias.


Rolling Window of Local Minima/Maxima

Question: I've made a script (shown below) that helps determine local maxima points using historical stock data. It uses the daily highs to mark out local resistance levels. Works great, but what I would like is, for any given point in time (or row in the stock data), I want to know what the most recent resistance level was just prior to that point. I want this in it's own column in the dataset. So for instance:

The top grey line is the highs for each day, and the bottom grey line was the close of each day. So roughly speaking, the dataset for that section would look like this:
High            Close
216.8099976     216.3399963
215.1499939     213.2299957
214.6999969     213.1499939
215.7299957     215.2799988 <- First blue dot at high
213.6900024     213.3699951
214.8800049     213.4100037 <- 2nd blue dot at high
214.5899963     213.4199982
216.0299988     215.8200073
217.5299988     217.1799927 <- 3rd blue dot at high
216.8800049     215.9900055
215.2299957     214.2400055
215.6799927     215.5700073
....

Right now, this script looks at the entire dataset at once to determine the local maxima indexes for the highs, and then for any given point in the stock history (i.e. any given row), it looks for the NEXT maxima in the list of all maximas found. This would be a way to determine where the next resistance level is, but I don't want that due to a look ahead bias. I just want to have a column of the most recent past resistance level or maybe even the latest 2 recent points in 2 columns. That would be ideal actually.
So my final output would look like this for the 1 column:
High            Close           Most_Rec_Max
216.8099976     216.3399963     0
215.1499939     213.2299957     0
214.6999969     213.1499939     0
215.7299957     215.2799988     0
213.6900024     213.3699951     215.7299957
214.8800049     213.4100037     215.7299957
214.5899963     213.4199982     214.8800049
216.0299988     215.8200073     214.8800049
217.5299988     217.1799927     214.8800049
216.8800049     215.9900055     217.5299988
215.2299957     214.2400055     217.5299988
215.6799927     215.5700073     217.5299988
....

You'll notice that the dot only shows up in most recent column after it has already been discovered.
Here is the code I am using:
real_close_prices = df['Close'].to_numpy()

highs = df['High'].to_numpy()

max_indexes = (np.diff(np.sign(np.diff(highs))) < 0).nonzero()[0] + 1 # local max
# +1 due to the fact that diff reduces the original index number

max_values_at_indexes = highs[max_indexes]
curr_high = [c for c in highs]
max_values_at_indexes.sort()
for m in max_values_at_indexes:
    for i, c in enumerate(highs):
        if m > c and curr_high[i] == c:
            curr_high[i] = m
#print(nextbig)
df['High_Resistance'] = curr_high

# plot
plt.figure(figsize=(12, 5))
plt.plot(x, highs, color='grey')
plt.plot(x, real_close_prices, color='grey')
plt.plot(x[max_indexes], highs[max_indexes], "o", label="max", color='b')
plt.show()

Hoping someone will be able to help me out with this. Thanks!
Comment: It would help if you could clarify the definition of the "resistance level", and possibly provide an example.
Comment: A resistance level in this case is wherever there's a blue dot. So the new column should have the Y of whatever the most recent blue dot was. Example is provided. Thanks! @hilberts_drinking_problem
Answer: Here is one approach. Once you know where the peaks are, you can store peak indices in p_ids and peak values in p_vals. To assign the k'th most recent peak, note that p_vals[:-k] will occur at p_ids[k:]. The rest is forward filling.
# find all local maxima in the series by comparing to shifted values
peaks = (df.High > df.High.shift(1)) & (df.High > df.High.shift(-1))
# pass peak value if peak is achieved and NaN otherwise
# forward fill with previous peak value & handle leading NaNs with fillna
df['Most_Rec_Max'] = (df.High * peaks.replace(False, np.nan)).ffill().fillna(0)

# for finding n-most recent peak
p_ids, = np.where(peaks)
p_vals = df.High[p_ids].values
for n in [1,2]:
  col_name = f'{n+1}_Most_Rec_Max'
  df[col_name] = np.nan
  df.loc[p_ids[n:], col_name] = p_vals[:-n]
  df[col_name].ffill(inplace=True)
  df[col_name].fillna(0, inplace=True)

#           High       Close  Most_Rec_Max  2_Most_Rec_Max  3_Most_Rec_Max
# 0   216.809998  216.339996      0.000000        0.000000        0.000000
# 1   215.149994  213.229996      0.000000        0.000000        0.000000
# 2   214.699997  213.149994      0.000000        0.000000        0.000000
# 3   215.729996  215.279999    215.729996        0.000000        0.000000
# 4   213.690002  213.369995    215.729996        0.000000        0.000000
# 5   214.880005  213.410004    214.880005      215.729996        0.000000
# 6   214.589996  213.419998    214.880005      215.729996        0.000000
# 7   216.029999  215.820007    214.880005      215.729996        0.000000
# 8   217.529999  217.179993    217.529999      214.880005      215.729996
# 9   216.880005  215.990006    217.529999      214.880005      215.729996
# 10  215.229996  214.240006    217.529999      214.880005      215.729996
# 11  215.679993  215.570007    217.529999      214.880005      215.729996

Comment: This is exactly what I was after. Thanks a lot! I just didn't know how to ffill the recent values. And you solved my adding extra columns question too. Much appreciated!
Answer: I just came across this function that might help you a lot: scipy.signal.find_peaks.
Based on your sample dataframe, we can do the following:
from scipy.signal import find_peaks

## Grab the minimum high value as a threshold.
min_high = df["High"].min()

### Run the High values through the function. The docs explain more,
### but we can set our height to the minimum high value.
### We just need one out of two return values.

peaks, _ = find_peaks(df["High"], height=min_high)

### Do some maintenance and add a column to mark peaks

# Merge on our index values
df1 = df.merge(peaks_df, how="left", left_index=True, right_index=True)

# Set non-null values to 1 and null values to 0; Convert column to integer type.
df1.loc[~df1["local_high"].isna(), "local_high"] = 1
df1.loc[df1["local_high"].isna(), "local_high"] = 0
df1["local_high"] = df1["local_high"].astype(int)

Then, your dataframe should look like the following:
          High         Low  local_high
0   216.809998  216.339996           0
1   215.149994  213.229996           0
2   214.699997  213.149994           0
3   215.729996  215.279999           1
4   213.690002  213.369995           0
5   214.880005  213.410004           1
6   214.589996  213.419998           0
7   216.029999  215.820007           0
8   217.529999  217.179993           1
9   216.880005  215.990005           0
10  215.229996  214.240005           0
11  215.679993  215.570007           0

Comment: Thanks Mark. I did see the peaks scipy page, but unfortunately I will need to inverse this function for the lows as well, and that local_high number isn't a price which was what I was after. Question was answered above. Thanks for pointing this out though!

Rolling Window of Local Minima/Maxima


Multiple accounts heroku keys mixed up

Question: I have multiple accounts on heroku and I think my ssh keys got messed up but I have no idea how to fix it.
When i try 'git push heroku master' i get the error 'your account ***** does not have access to *****'
How do I fix my keys so that I can push to heroku?
Comment: A simple search will lead you to the heroku SSH documentation. Stackoverflow has no way of knowing exactly what needs to be corrected in your personal setup. What exactly are you hoping for here?
Answer: Heroku wont allow to share ssh key between 2 heroku accounts.
I will help you to get through this by a hacky fix
1.First go to .ssh/ directory in your home folder
2.Move all the files and keep it in any other folder(Don't delete it)
3.Open the terminal and Login  to heroku using "heroku login" command and login to your heroku account which you want to push now.
4.After sucessfully logging in to your account enter "heroku keys:add" command. it will create a new ssh keys for your account. you can now push to your account easily.
Suppose if you want to push to any application using your old account replace the .ssh/ folder files to backuped files. (Backup your current .ssh/ to any folder)
or you can repeat same step 1-4 for that account.
I hope this will solve your problem.

Multiple accounts heroku keys mixed up


How to print time difference in accuracy of milliseconds and nanoseconds from C in Linux?

Question: I have this program which prints the time difference between 2 different instances, but it prints in accuracy of seconds. I want to print it in milliseconds and another in nanoseconds difference.
//Prints in accuracy of seconds

#include <stdio.h>
#include <time.h>

int main(void)
{
    time_t now, later;
    double seconds;

    time(&now);
    sleep(2);

    time(&later);
    seconds = difftime(later, now);

    printf("%.f seconds difference", seconds);
}

How can I accomplish that?
Comment: this might help: http://stackoverflow.com/questions/13610471/calculating-function-time-in-nanoseconds-in-c-code
Comment: What platform are you on?
Comment: You can't have nanoseconds precision. http://stackoverflow.com/questions/13610471/calculating-function-time-in-nanoseconds-in-c-code
Comment: @interjay: Sorry i should have mentioned that, it's Linux. gcc compiler.
Comment: @georgesl you _can_ get time to nanosecond precision on Linux. This is not guaranteed to be nanosecond accurate though as I believe that it may be an interpolation between two microsecond values based on the CPU's internal clock on most architectures. You can always use `clock_getres` to find it though.
Comment: @Will : even if you have nanoseconds resolution with CPU's internal clock, FSB's speed is only a fraction of that (typically 100-500 Mhz) so you have to pray for your loop to stay within L1 cache.
Comment: @georgesl indeed. The value returned may be very precise but wildly inaccurate.
Answer: Read first the time(7) man page.
Then, you can use clock_gettime(2) syscall (you may need to link -lrt to get it).
So you could try
    struct timespec tstart={0,0}, tend={0,0};
    clock_gettime(CLOCK_MONOTONIC, &tstart);
    some_long_computation();
    clock_gettime(CLOCK_MONOTONIC, &tend);
    printf("some_long_computation took about %.5f seconds\n",
           ((double)tend.tv_sec + 1.0e-9*tend.tv_nsec) -
           ((double)tstart.tv_sec + 1.0e-9*tstart.tv_nsec));

Don't expect the hardware timers to have a nanosecond accuracy, even if they give a nanosecond resolution. And don't try to measure time durations less than several milliseconds: the hardware is not faithful enough. You may also want to use clock_getres to query the resolution of some clock.
Comment: For computational benchmarking it is better to use CLOCK_PROCESS_CPUTIME_ID instead of CLOCK_MONOTONIC
Comment: I would reorder the computation to minimize rounding errors:  `(double) (tend.tv_sec - tstart.tv_sec) + 1.0e-9 * (double) (tend.tv_nsec - tstart.tv_nsec)`
Comment: thats true its work for me. thank you very much @Basile
Comment: The hardware not being "faithful enough" to measure sub-ms intervals is a doubtful assertion. If true, it would require an explanation given the accuracy of crystal oscillators.
Comment: I am not sure that the typical clock on a typical consumer PC has a relative precision of 1e-10. Most clocks are not that precise. Those that do cost probably more than a car. I cannot even name the provider of such high-precision clocks.
Answer: timespec_get from C11
This function returns up to nanoseconds, rounded to the resolution of the implementation.
Example from: http://en.cppreference.com/w/c/chrono/timespec_get :
#include <stdio.h>
#include <time.h>

int main(void)
{
    struct timespec ts;
    timespec_get(&ts, TIME_UTC);
    char buff[100];
    strftime(buff, sizeof buff, "%D %T", gmtime(&ts.tv_sec));
    printf("Current time: %s.%09ld UTC\n", buff, ts.tv_nsec);
}

Output:
Current time: 02/18/15 14:34:03.048508855 UTC

More details here: https://stackoverflow.com/a/36095407/895245
Comment: This is great. Is there an easy way to concatenate buff and ts.tv_sec into a single string? I attempted to use .append() in cpp with no success.
Comment: @p.luck not sure I understand the question. Do you mean concatenate `ts.tv_sec` and `ts.nsec` in a single string? For that something along `strftime %D %T %s` + a second `snprintf` call: https://stackoverflow.com/questions/3774417/sprintf-with-automatic-memory-allocation
Answer: here is a simple macro to deal with it
#include <time.h>
#define CHECK_TIME(x) {\
    struct timespec start,end;\
    clock_gettime(CLOCK_REALTIME, &start);\
    x;\
    clock_gettime(CLOCK_REALTIME, &end);\
    double f = ((double)end.tv_sec*1e9 + end.tv_nsec) - ((double)start.tv_sec*1e9 + start.tv_nsec); \
    printf("time %f ms\n",f/1000000); \
    }

and here is how to use it:
CHECK_TIME(foo(a,b,c))


Check if cookie is set

Question: To let my users logged in, I have something like this :

The user logs in
If it is OK, I create $_SESSION and set a cookie :
setcookie ('test', sha1($_POST['username']), time()+604800);
Then I insert in a cookie table : the hashed username, the IP address and the browser version.

But, in order to check if a user is logged in (and keep him logged), I have a query on EACH page :

I check if $_SESSION['ID'] exists (it is mainly with this variable that a user is logged in)
If it exists, nothing happens.
If it doesn't, I check if $_COOKIE['cookie'] exists
If it does, I get the user's IP address and browser version
With a SELECT query, I check if the actual IP address and the browser is the same as in the table.
If it is the same, I reset a $_SESSION (so he is logged in)

Now, here's the code :
FORM :
    <form method="post" action="http://localhost/test/login.php">
        Username :
        <input type="text" name="username" id="user" maxlength="20" placeholder="Username">

        Password :
        <input type="password" name="password" id="pass" placeholder="Password">

        <input type="checkbox" name="cookie" value="cookie">Remember me ?
        <input type="submit" name="login" value="ok">
    </form>

FUNCTIONS :
function get_ip() {
    if (isset($_SERVER['HTTP_CLIENT_IP'])) {
    return $_SERVER['HTTP_CLIENT_IP'];
    }
    elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    return $_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else {
    return (isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '');
    }
}

function getBrowser()
{
$u_agent = $_SERVER['HTTP_USER_AGENT'];
$bname = 'Unknown';
$platform = 'Unknown';
$version= "";

if (preg_match('/linux/i', $u_agent)) {
    $platform = 'linux';
}
elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
    $platform = 'mac';
}
elseif (preg_match('/windows|win32/i', $u_agent)) {
    $platform = 'windows';
}

if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent))
{
    $bname = 'Internet Explorer';
    $ub = "MSIE";
}
elseif(preg_match('/Firefox/i',$u_agent))
{
    $bname = 'Mozilla Firefox';
    $ub = "Firefox";
}
elseif(preg_match('/Chrome/i',$u_agent))
{
    $bname = 'Google Chrome';
    $ub = "Chrome";
}
elseif(preg_match('/Safari/i',$u_agent))
{
    $bname = 'Apple Safari';
    $ub = "Safari";
}
elseif(preg_match('/Opera/i',$u_agent))
{
    $bname = 'Opera';
    $ub = "Opera";
}
elseif(preg_match('/Netscape/i',$u_agent))
{
    $bname = 'Netscape';
    $ub = "Netscape";
}

$known = array('Version', $ub, 'other');
$pattern = '#(?<browser>' . join('|', $known) .
')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
if (!preg_match_all($pattern, $u_agent, $matches)) {
}

$i = count($matches['browser']);
if ($i != 1) {
    if (strripos($u_agent,"Version") < strripos($u_agent,$ub)){
        $version= $matches['version'][0];
    }
    else {
        $version= $matches['version'][1];
    }
}
else {
    $version= $matches['version'][0];
}

if ($version==null || $version=="") {$version="?";}

return array(
    'userAgent' => $u_agent,
    'name'      => $bname,
    'version'   => $version,
    'platform'  => $platform,
    'pattern'    => $pattern
);
}

ON SUBMIT :
if (!empty($_POST['pseudo']) && !empty($_POST['password']))
{
$salt = "salt_test";

$req = $bdd->prepare('SELECT * FROM users WHERE username = :username AND pass = :pass');
$req->execute(array('username' => $_POST['username'], 'pass' => md5(sha1($_POST['pass'].$salt))));
    if ($data = $req->fetch())
    {
        if ($data['stat'] != 0)
        {
        $_SESSION['ID'] = $data['ID'];
        $_SESSION['username'] = $data['username'];
        $_SESSION['stat'] = $data['stat'];

        $req = $bdd->prepare('UPDATE cookies SET last_co = CURRENT_TIMESTAMP WHERE ID_user = :ID');
        $req->execute(array('ID' => $data['ID']));
        $req->closeCursor();

            if(!empty($_POST['cookie']))
            {
            setcookie ('cookie', md5($_POST['username']), time()+604800);

            $ua = getBrowser();
            $yourbrowser= $ua['name']. " " .$ua['version'];

            $req = $bdd->prepare('UPDATE cookies SET hash_username = :hash_username, IP = :IP, browser = :browser WHERE ID_user = :ID');
            $req->execute(array('hash_username' => md5($_SESSION['pseudo']), 'IP' => get_ip(), 'browser' => $yourbrowser, 'ID' => $_SESSION['ID']));
            $req->closeCursor();
            }

        ?><META HTTP-EQUIV="Refresh" CONTENT="0.1; URL=http://localhost/test/" /><?php
        }
        elseif ($data['stat'] == 5)
        {
        $error = 2;
        }
    }
    else
    {
        $error = 1;
    }
$req->closeCursor();
}

ON MEMBERS PAGE :
if (isset($_SESSION['ID']))
{
        if (isset($_COOKIE['cookie'])
        {
        $ip = get_ip();
        $yourbrowser= $ua['name']. " " .$ua['version'];

        $req = $bdd->prepare('SELECT * FROM cookies WHERE hash_username = :hash, IP = :IP, browser = :browser');
        $req->execute(array('hash_username' => md5($_SESSION['username']), 'IP' => $ip, 'browser' => $yourbrowser));
            if ($req->fetch())
        {
            $_SESSION['ID'] = $data['ID'];
            $_SESSION['username'] = $data['username'];
            $_SESSION['stat'] = $data['stat'];
        }
        $req->closeCursor();
    }
}

So, is this method OK and is it heavy for performance. Don't you think that it is "useless" to make a query every time ?
Comment: no one wants to read 100 lines of spaghetti code. `Check if cookie is set` => use $_COOKIE (s. http://php.net/manual/de/reserved.variables.cookies.php)
Comment: One question per question please.
Comment: @Aitch Thank you for your answer. This is what I used in my code. I just want to know if my method is right or if I have to improve something..
Comment: @RiggsFolly I have deleted the other questions.
Answer: make a new page with this code
    if (isset($_SESSION['ID']))
{
        if (isset($_COOKIE['cookie'])
        {
        $ip = get_ip();
        $yourbrowser= $ua['name']. " " .$ua['version'];

        $req = $bdd->prepare('SELECT * FROM cookies WHERE hash_username = :hash, IP = :IP, browser = :browser');
        $req->execute(array('hash_username' => md5($_SESSION['username']), 'IP' => $ip, 'browser' => $yourbrowser));
            if ($req->fetch())
        {
            $_SESSION['ID'] = $data['ID'];
            $_SESSION['username'] = $data['username'];
            $_SESSION['stat'] = $data['stat'];
        }
        $req->closeCursor();
    }
}

and include it in every page . after that you will not need to write your code again and again.

Check if cookie is set


Is it useful to define the hazard function of distributions with support in the real line?

Question: The hazard function is commonly used in models using distributions with positive support (gamma, weibull, lognormal, etcetera). However, I have not seen this concept (hazard) being used in the context of models using distributions with support on the entire real line, like the normal, Student-t, logistic, laplace, etcetera.
Is there any use of the hazard function associated with distributions with support on the real line?
EDIT: I just came across the concept of Inverse Mills ratio. It seems like the hazard function of distributions with support of the real line appears, implicitly, through this concept (en.wikipedia.org/wiki/Mills_ratio).
Answer: As @whuber notes in a comment on another answer, there is no reason to restrict hazard functions to distributions having only non-negative support. Although a Wikipedia page suggests that restriction, a survival function $S(x)$ can be taken in general to be the complement of a corresponding cumulative distribution $F(x)$, with $S(x)=1-F(x)$. For any value of $x$ for which $f(x)$ is defined and $S(x)$ isn't 0, there is a defined value of the hazard $h(x)=f(x)/S(x)$.
A survival function defined over the entire real line can be useful in evaluating a parametric survival model fit, as explained for example in Chapters 18 and 19 of Frank Harrell's Regression Modeling Strategies. A Kaplan-Meier survival plot of censored, standardized residuals over the real line can help evaluate whether the distribution of residuals matches that expected for a particular choice of parametric family (e.g., standard minimum extreme value, defined over the entire real line, for a Weibull model).
Furthermore, survival analysis with left-censored survival times can be thought of as allowing for negative survival times. In R, a left-censored observation at time $x$ can be coded as Surv(-Inf, x, event).
Survival functions defined over the entire real line thus can be useful.
The question, however, is how useful a hazard function is for distributions with support over the entire real line. The hazard function is perhaps most useful as describing the probability of an event at time $x$ given that there hasn't yet been an event. In practice for analysis of event times, it's useful to define a time origin such that $f(x)=0$ (and thus $F(x)=0$) for $x \le 0$. In that case, $h(x)=0$ for $x \le 0$. I suppose there might be circumstances in which a different time origin might make sense, but it's hard to think of one.
Comment: I just came across the concept of Inverse Mills ratio. It seems like the hazard function of distributions with support of the real line appears, implicitly, through this concept (https://en.wikipedia.org/wiki/Mills_ratio).
Answer: The hazard function is a function of time so a non-negative support is required.
In survival analysis, the hazard function is the probability of dying at time $t$ given that you survived until time $t$.
Comment: That's perfectly circular: by *your* definition $f$ has non-negative support, therefore "non-negative support is required"!
Comment: Sure it does: it makes perfect sense, and works perfectly well, to shift the time coordinate by any constant amount.  Moreover, that formula for $h$ works provided $f$ exists and $S$ is nonzero; and even for positive random variables it's not defined when $S$ is zero.
Comment: Your logic is unconvincing, because there's no mathematical obstacle to defining a hazard function for any (absolutely continuous) distribution, nor must people always measure time as positive values.
Comment: @whuber The hazard function can be defined as $$h(t) = \frac{f(t)}{S(t)}$$ where $f(t)$ is a probability density function defined on the interval $[0,\infty]$ and $S(t)$ is the corresponding Survival function, i.e. $S(t)=1-F(t)$.
It does not make sense to perform survival analysis with time being negative.
Comment: By definition $f(t)$ is on the interval $[0,\infty]$. Using something like a Gaussian would require truncation. Obviously when $S$ is 0 the survival analsyis is complete?


Question about curvature

Question: that is my trouble:

Let $\alpha : I \rightarrow R^3 $ a regular curve parameterized by its
arc lenght, that is contained in the unit sphere.
If $k(s)>0$ and $\tau(s)\neq 0$ , $\forall s \in I$ then
$$ \frac{1}{k^2(s)} + \frac{(k'(s))^2}{k^4(s) \tau^2(s)} = 1 $$

my efforts were useless
Answer: We may easily generalize to the case in which $\alpha(s)$ lies in the sphere of radius $R$ centered at some point $C \in \Bbb R^3$, that is, to
$(\alpha(s) - C) \cdot (\alpha(s) - C) = R^2. \tag 1$
The key idea here is to express $\alpha(s) - C$ itself in terms of $T(s)$, $N(s)$, and $B(s)$, the Frenet frame of the curve $\alpha(s)$.  We obtain, upon differentiating (1) with respect to the arc-length $s$,
$(\alpha(s) - C)' \cdot (\alpha(s) - C) = 0, \tag 2$
or
$\dot \alpha(s) \cdot (\alpha(s) - C) = 0; \tag 3$
since
$\dot \alpha(s) = T(s), \tag 4$
(3) becomes
$T(s) \cdot (\alpha(s) - C) = 0, \tag 5$
which shows that the $T(s)$ component of $\alpha(s) - C$
is zero.  We next differentiate (5):
$\dot T(s) \cdot (\alpha(s) - C) + T(s) \cdot T(s) = 0, \tag 6$
and using the first Frenet-Serret equation
$\dot T(s) = \kappa(s) N(s) \tag 7$
and the fact that $T(s)$ is a unit vector,
$T(s) \cdot T(s) = 1, \tag 8$
we transform (6) into
$\kappa(s) N(s) \cdot (\alpha(s) - C) + 1 = 0, \tag 9$
and readily express the $N(s)$ component of $\alpha(s) - C$ as
$N(s) \cdot (\alpha(s) - C) = -\dfrac{1}{\kappa(s)}; \tag{10}$
taking the $s$ derivative of this equation yields
$\dot N(s) \cdot (\alpha(s) - C) + N(s) \cdot T(s) = \dfrac{\dot \kappa(s)}{\kappa^2(s)}; \tag{11}$
since
$N(s) \cdot T(s) = 0, \tag{12}$
and the second Frenet-Serret equation affirms that
$\dot N(s) = -\kappa(s) T(s) + \tau(s) B(s), \tag{13}$
we may now write (11) in the form
$(-\kappa(s) T(s) + \tau(s) B(s)) \cdot (\alpha(s) - C) = \dfrac{\dot \kappa(s)}{\kappa^2(s)}, \tag{14}$
and so by virtue of (5),
$ \tau(s) B(s) \cdot (\alpha(s) - C) = \dfrac{\dot \kappa(s)}{\kappa^2(s)}, \tag{15}$
immediately leading to
$B(s) \cdot (\alpha(s) - C) = \dfrac{\dot \kappa(s)}{\kappa^2(s) \tau(s)}, \tag{16}$
the $B(s)$ component of $\alpha(s) - C$; we combine (5), (10) and (16) and arrive at
$\alpha(s) - C = -\dfrac{1}{\kappa(s)} N(s) +  \dfrac{\dot \kappa(s)}{\kappa^2(s) \tau(s)} B(s), \tag{17}$
now using
$N(s) \cdot B(s) = 0, \tag{18}$
it follows from (1) and (17) that
$R^2 = (\alpha(s) - C) \cdot (\alpha(s) - C) = \dfrac{1}{\kappa^2(s)} +  \dfrac{(\dot \kappa(s))^2}{\kappa^4(s) \tau^2(s)}, \tag{19}$
the requested formula; we observe that when $R = 1$ we obtain the exact relationship given in the text of the question itself. $OE\Delta$.
See also this question.
Comment: You've posted this same solution at least a dozen times :) I just link to my previous solution rather than continuing to retype. Admittedly, this one isn't quite the usual post.
Comment: I've personally seen well over six. :) I think we should just tell all these people that there's one and only one technique: Expand the position vector as a linear combination of the Frenet frame vectors. Let them work on it.
Comment: @TedShifrin:  OK Ted, I know you are speaking hyperbolically (to borrow a term from geometry) when you say "at least a dozen times".  I didn't even remember my previous solution until I found it in a file I keep which has the text of all my answers.  But thanks.  ***Cheers!!!***
Comment: @Ted Shifrin:  Oh come on, six?  Would you mind showing me the links?  But perhaps you're right about a "generic technique".
Comment: I'm not going to do all that work. Just search your answers under  user:67071 [differential-geometry]
Comment: @TedShifrin:  OK Ted, I did a quick preliminary search (by the way your seach syntax (user:67071 [differential-geometry] was new to me, so thanks for that as well) and went back about 60 posts (I'll look more later) and only found this and the one I linked.  Now I'm curious to search more.

Question about curvature


How to extract the first and last 3 columns of a data frame in R

Question: I have some dataframes and I would like to extract the first 3 and the last 3 column from them separately. And the column names and the column amount of them are different. Could any one give me a tip that how can I do that? Thank you in advance ; )
df <- matrix(sample(1:10, 100, replace = TRUE), 10)
df <- as.data.frame(df)
#I know we can do something like this
df[,c(1:3,5:6)]
#but I dont know how to select last 3 columns

Answer: Use ncol()
df[,c(1:3, (ncol(df) - 2):ncol(df))]
#   V1 V2 V3 V8 V9 V10
#1   2  3  8  9 10   1
#2   7  7  7  9  3   6
#3   8  2 10  7  7   4
#4   1  1  3  5  8   5
#5   1  5  8  9  1   1
#6   7 10  5  8  7   1
#7   5  3  3  3 10   4
#8   8  9  1  3  5   6
#9   6  1  6  8  7   7
#10  7  2  9 10 10   9

Or length()
idx <- length(df)
df[,c(1:3, (idx - 2):idx)]

Comment: Although it's great for readability, I think it's better to use `length` inline rather than give it a variable. Just my novice suggestion. Not sure but wouldn't `n` mask say `n()`?!
Answer: We can use head and tail on the column names
df[, c(head(names(df), 3), tail(names(df), 3))]