Getting Error: UIInstructions cannot be cast to org.primefaces.model.menu.MenuElement

Question: I am trying to run the code of that is taken directly from primefaces website, but i am getting an error of UIInstructions cannot be cast to org.primefaces.model.menu.MenuElement
/This is my AddUser.xhtml code/
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<h:head>
        <title>Getting User Information</title>

</h:head>
<h:body>
<h:form>

        <f:facet name="options">

        </f:facet>

</h:form>
</h:body>

/This is my web.xml file/
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>UserWebApp</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>/faces/*</url-pattern>
     <url-pattern>*.xhtml</url-pattern>
    <url-pattern>*.jsf</url-pattern>

  </servlet-mapping>

   <context-param>
    <param-name>primefaces.THEME</param-name>
    <param-value>afterdark</param-value>
    </context-param>

    <context-param>
    <param-name>facelets.SKIP_COMMENTS</param-name>
    <param-value>true</param-value>
    </context-param>

    <context-param>
    <param-name>javax.faces.FACELETS_LIBRARIES</param-name>
    <param-value>/WEB-INF/my.taglib.xml</param-value>
</context-param>

</web-app>

/And my jar file is also placed in webInf/lib/

I have tried everything available online but still unable o solve it
Thanks in advance
Answer: I figured out the problem. I was copying the MenuBar code directly from primefaces website (https://www.primefaces.org/showcase/ui/menu/menubar.xhtml)
And then i realized that there are invisible characters/stuff present between each line of code. (i figured this out when i copied/paste java class code),
once these invisible stuff id deleted and my code works perfectly.
/Following code is also the primefaces website code but free of invisible characters/
<h:form>

<f:facet name="options">

</f:facet>

</h:form>

Answer: This error can happen also for using HTML comments inside
 between
, which cause the error

UIInstructions cannot be cast to org.primefaces.model.menu.MenuElement


RSA modulus and exponent from public key

Question: I basically have the same problem as in this question, but I'm having trouble filling in the apparently trivial parts left out from the accepted answer. I'm doing this in C# with Mono.
I have a CA root certificate, and from that I can get a byte[] holding a public key. I then get an untrusted certificate I need to verify. From what I understand, RSACryptoServiceProvider.VerifyData should do the trick, but first I need to set RSAParameters with the modulus and exponent from the public key.
(Edit: The following repeats some things already apparent from the question I linked to above.)
The piece of code that should do what I need and validate a server's certificate with a root certificate I trust is as follows:
RSACryptoServiceProvider publicKey = new RSACryptoServiceProvider();
RSAParameters publicKeyParams = new RSAParameters();
publicKeyParams.Modulus = GetPublicKeyModulus();
publicKeyParams.Exponent = GetPublicKeyExponent();
publicKey.ImportParameters(publicKeyParams);
return publicKey.VerifyData(SignedValue(), CryptoConfig.MapNameToOID("SHA1"), Signature());

My problem is the contents of the GetPublicKeyModulus() and GetPublicKeyExponent(). In the accepted answer they are left out as apparently trivial, with just a comment saying the modulus is the value of the first TLV in my public key, and the exponent is the second TLV in the public key. I don't fully understand  what that means.
byte[] GetPublicKeyExponent()
{
  // The value of the second TLV in your Public Key
}

byte[] GetPublicKeyModulus()
{
  // The value of the first TLV in your Public Key
}
byte[] SignedValue()
{
  // The first TLV in your Ceritificate
}

byte[] Signature()
{
  // The value of the third TLV in your Certificate
}

My question is what do these "first TLV"/"second TLV" exactly mean and how do I get those values from the byte array I have?
From what I understand, TLV stands for type-length-value. So if I have it correct, first bits of the byte array containing the public key have information about how many bits the modulus data is. Using that information I'm supposed to copy that amount of bits from the public key into another array, and set RSAParameters.Modulus to that value. After the modulus in the  public key comes the exponent, and I should do the same operation with that. But I can't find information about in how many bits and in what format is the "TL" part of a TLV in the public key data contained.
I found information elsewhere saying the modulus is the first 1024 bits in the public key, and the exponent is the remainder, but that gave me an error about size when copying data between the byte arrays.
At the moment my code that I've been forming based on the accepted answer in the question I linked looks basically like this:
using System;
using System.Net;
using System.Security.Cryptography.X509Certificates;

X509Certificate2 trustedRootCertificate = new X509Certificate2(X509Certificate2.CreateFromCertFile(filename));
ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate;
.
.
public bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
  .
  .
  byte[] publicKeyBytes = trustedRootCertificate.GetPublicKey();
  byte[] modulusData = // The value of the first TLV in the Public Key??
  byte[] exponentData = // The value of the second TLV in the Public Key??

  RSAParameters publicKeyParams = new RSAParameters();
  publicKeyParams.Modulus = modulusData;
  publicKeyParams.Exponent = exponentData;
  RSACryptoServiceProvider publicKey = new RSACryptoServiceProvider();
  publicKey.ImportParameters(publicKeyParams);

  byte[] certificateData = certificate.GetRawCertData();
  byte[] signedValue = // The first TLV in the certificate??
  byte[] encryptedSignature = // The third TLV in the certificate??

  return publicKey.VerifyData(certificateData, HashAlgorithm.Create("SHA1"), encryptedSignature);
}

Or should I be using certificateData (the return value of certificate.GetRawCertData()) in the VerifyData call?
Elsewhere I've found that the encrypted signature part is the last 256 bits in the certificateData, I'm not sure if that's the same as "the third TLV in the certificate". If not, I'd be doing
byte[] certificateData = certificate.GetRawCertData();
byte[] encryptedSignature = new byte[256];
System.Array.Copy(certificateData, certificateData.Length - 256, encryptedSignature, 0, 256);

and then using encryptedSignature as the last parameter in the VerifyData call.
Instead of all this TLV business I've also tried simply
RSACryptoServiceProvider publicKey = trustedRootCertificate.PublicKey.Key as RSACryptoServiceProvider;

as the person in the question I linked to above, but using this the VerifyData call then returned false when I thought it shouldn't. The certificate the application gets from the server has trustedRootCertificate as its root cert, I should be able to do this with that, correct? The root's public key should be able to verify the server's cert?
It's very much possible I just have the very basics of certificate verification wrong from the start. If that's not the case, then my question is how do I get these values
// The value of the second TLV in your Public Key
..
// The value of the first TLV in your Public Key

from the public key of the trusted root cert I have.
Edit: I've also verified that the root certificate loaded from the file and the certificate the app gets from the server are what they're supposed to be by printing out their information, so the problem is not at least in the certificates being wrong. I just don't know how to use them correctly.
Comment: I don't know if I have understood your question clearly, but still have you gone through this:: http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/4282dda1-4803-435a-b63a-65e2d5ac9941
Comment: Yes, that is exactly where I got the trustedRootCertificate.PublicKey.Key as RSACryptoServiceProvider approach from. As for understanding the question, the post as it is now pretty much assumes the question linked in the first sentence is read, too. I'll edit my question to be more independent.
Answer: With RSACryptoServiceProvider:
X509Certificate2 certificate = Certificate.CreateFromBase64String(stringCert);
RSACryptoServiceProvider key = certificate.PublicKey.Key as RSACryptoServiceProvider;
if(key != null)
{
    RSAParameters parameters = key.ExportParameters(false);
    byte[] expoenet = parameters.Exponent;
    byte[] modulus = parameters.Modulus;
}

https://social.msdn.microsoft.com/Forums/vstudio/en-US/4282dda1-4803-435a-b63a-65e2d5ac9941/get-modulus-exponent-from-certificate-public-key?forum=netfxbcl
Answer: Lets say that you encountered with BIT STRING type containing the following Length - Value::
03(T - BIT STRING)
82(Read next 2 Bytes for actual Length)
01 0F(Actual Length of whole BIT STRING)

---BIT STRING Value Starts Here---
00(First Byte Of BIT STRING specifies the number of bits left unused in the final byte of BIT STRING which in this case is 0)

30(T - SEQUENCE)
82(Read next 2 Bytes for actual Length)
01 0A(Actual Length of whole SEQUENCE)

---SEQUENCE Value Starts Here---
02(T - INTEGER)
82(Read next 2 Bytes for actual Length)
01 01(Actual Length of whole INTEGER)

(Value starts from here till "Actual Length of whole INTEGER above")
---INTEGER Value Starts Here---
---Exponent Starts Here---
00 A9  CA B2 A4 CC CD 20 AF 0A
7D 89 AC 87 75 F0 B4 4E  F1 DF C1 0F BF 67 61 BD
A3 64 1C DA BB F9 CA 33  AB 84 30 89 58 7E 8C DB
6B DD 36 9E 0F BF D1 EC  78 F2 77 A6 7E 6F 3C BF
93 AF 0D BA 68 F4 6C 94  CA BD 52 2D AB 48 3D F5
B6 D5 5D 5F 1B 02 9F FA  2F 6B 1E A4 F7 A3 9A A6
1A C8 02 E1 7F 4C 52 E3  0E 60 EC 40 1C 7E B9 0D
DE 3F C7 B4 DF 87 BD 5F  7A 6A 31 2E 03 99 81 13
A8 47 20 CE 31 73 0D 57  2D CD 78 34 33 95 12 99
12 B9 DE 68 2F AA E6 E3  C2 8A 8C 2A C3 8B 21 87
66 BD 83 58 57 6F 75 BF  3C AA 26 87 5D CA 10 15
3C 9F 84 EA 54 C1 0A 6E  C4 FE C5 4A DD B9 07 11
97 22 7C DB 3E 27 D1 1E  78 EC 9F 31 C9 F1 E6 22
19 DB C4 B3 47 43 9A 1A  5F A0 1E 90 E4 5E F5 EE
7C F1 7D AB 62 01 8F F5  4D 0B DE D0 22 56 A8 95
CD AE 88 76 AE EE BA 0D  F3 E4 4D D9 A0 FB 68 A0
AE 14 3B B3 87 C1 BB
-----Exponent Ends Here----
---INTEGER Value Ends Here---

02(T - INTEGER)
03(Actual Length cuz 8th Bit Not Set here, so this byte shows the actual length)

---INTEGER Value Starts Here---
----Mod Starts Here---
01 00 01
---Mod Ends Here---
---INTEGER Value Ends Here---

---SEQUENCE Value Ends Here---
---BIT STRING Value Ends Here---

You might want to read ASN.1 Format
Comment: Oh man, thanks! I feel I'm almost there, but I still don't get something - how do I know 03 means a bit string, 30 a sequence, 02 an integer, and so on and so forth?
Comment: Those are constants described in RFCs. Read the link above and this:: http://msdn.microsoft.com/en-us/library/windows/desktop/bb648642(v=vs.85).aspx.
Comment: Read your edit, fantastic, thank you so much! I'll accept the answer as soon as I get the chance to write some quick tests to see it working in practice (this might take another day).


Uncaught TypeError: class heritage this.MyClass is not an object or null

Question: I'm trying to extend one class from another inside the module. The code looks like that:

let af = {

    MyClass: class {
      constructor() {
        console.log("constructor of my class");
      }
    },

    myNextClass: class extends this.MyClass {    // *
      constructor() {
        console.log("constructor of the next class");
      }
    },

    myOtherClass: class extends this.MyClass {
      constructor() {
        console.log("constructor of the other class");
      }
    },
}

in the result console throws the TypeError:
Uncaught TypeError: class heritage this.MyClass is not an object or null referring to line *. Could you help me to fix that?
Comment: Don't use an arrow function if you need to use `this`.
Comment: No, it is not the inconsistency of m/M, that's the typo only here, I'm sorry for that (edited)
Comment: @Barmar this is very good advice, thank you! But unfortunately, it does not solve my problem.
Comment: You can't use `this` outside of a call to a method. There's no `this` available when you're creating the object.
Answer: this is only set when you're calling a method of the object, it's not available when you're initializing an object.
You also can't refer to the variable af until after the assignment, not during the creation of the literal.
So you need to split this up. Define the first class in the object literal, the rest require assignments so they can refer to the variable.

let af = {
  MyClass: class {
    constructor() {
      console.log("constructor of my class");
    }
  }
};

af.myNextClass = class extends af.MyClass {
  constructor() {
    super();
    console.log("constructor of the next class");
  }
};

af.myOtherClass = class extends af.MyClass {
  constructor() {
    super();
    console.log("constructor of the other class");
  }
};

new af.MyClass();
new af.myNextClass();
new af.myOtherClass();


Qual a boa prática ao lançar exceção dentro de if?

Question: Qual a melhor prática neste caso, utilizar o else mesmo sabendo que o if vai lançar exceção ou não?
opção 1 (com else):
if (condicao){
  throw new RuntimeException("Mensagem");
}else{
  System.out.println("Não deu exception");
}

opção 2 (sem else):
if (condicao){
  throw new RuntimeException("Mensagem");
}
System.out.println("Não deu exception");

Comment: Só "descompilando" o *bytecode* pra saber... Eu acredito que ambas as formas são equivalentes, de modo que um critério para escolher entre um e outro seria subjetivo e/ou variaria caso a caso.
Comment: @karlphillip provavelmente se um dia tivermos um codereview em pt, ela será migrada.
Comment: @Bacco Em outras palavras, o que você está sugerindo é que o pt.SO abrigue perguntas que seriam próprias para Code Review, Programmers, Signal Processing, Superuser, Serverfault, Webmasters e Game Development só porque não existe um fórum dedicado para cada tema em português? Isso vai virar uma confusão enorme...
Comment: @karlphillip Mas eu não sugeri nada! :). Quanto a essa discussão, foi bem extensa tanto no meta quanto na área 51, sugiro uma olhada em ambos, em especial o http://meta.br.stackoverflow.com/questions/1/aqui-no-o-stackoverflow-com. Em resumo, aqui os limites são mais amplos, mas algumas questões realmente fora de tópico já foram fechadas até. De qualquer forma a comunidade ainda está procurando seu ponto de equilíbrio, e você pode com certeza contribuir no meta ( http://meta.br.stackoverflow.com ) com sua opinião, que é o melhor caminho.
Comment: @Bacco Thank you very much, Sir. ;)
Comment: Essa pergunta ficaria melhor no [CodeReview](https://codereview.stackexchange.com/).
Comment: Apenas uma sugestão, se você estiver lançando `IllegalArgumentException` e similares, vale a pena usar uma biblioteca de pré-condições como o [Preconditions do Guava](https://code.google.com/p/guava-libraries/wiki/PreconditionsExplained) ou [Validate do Apache Commons](http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/Validate.html). Essa bibliotecas removem a necessidade do if e tornam o código bem mais legível.
Answer: Embora isso esteja propenso a um forte senso de opinião pessoal, eu acredito que a melhor prática é não utilizar bloco o else.
As razões são as seguintes:
Legibilidade do código
Acrescentar blocos aninhados, embora neste pequeno exemplo não cause um grande impacto, somente irá dificultar a leitura do código e torná-lo mais complexo.
Na prática, isso pode levar a situações com vários níveis de validação, como eu já vi por vezes em sistemas por aí:
if (condicao1){
    throw new RuntimeException("Mensagem 1");
}else{
    System.out.println("Não deu exception 1");
    if (condicao1){
        throw new RuntimeException("Mensagem 2");
    }else{
        System.out.println("Ainda não deu exception 2");
        if (condicao1){
            throw new RuntimeException("Mensagem 3");
        }else{
            System.out.println("Ainda não deu exception 3");
        }
    }
}

Para quem pensa que estou exagerando, não foram uma ou duas vezes que vi métodos com validações de 5, 6 ou mais níveis em métodos de sistemas financeiros com regras de negócio um tanto complexas.
Não é necessário
Uma condição que inclua um lançamento de exceção, ou outra instrução que venha a interromper a execução do método não precisa deste tipo de construção. Código desnecessário é perda de tempo.
É melhor separar as validações iniciais
As validações iniciais de um método não precisam e provavelmente não devem influenciar na lógica principal do método.
public int meuMetodo(String parametro) {

    if (parametro == null || parametro.isEmpty())
        throw new IllegalArgumentException("Parâmetro não informado!");

    //lógica aqui
    return 123;

}

Comment: Questão de *coding style*! É perfeitamente aceitável **não** usar chaves quando o `if` deve executar apenas um comando, e o *coding style* da pessoa exige que ela pule uma linha logo após as instruções do `if`, como foi o caso do exemplo acima.
Comment: Nâo é boa prática deixar um if sem {}. Inclusive no livro Java Coding Guidelines pode levar a problemas de segurança.
Comment: @uaiHebert Concordo, geralmente eu não faço isso. Pra falar a verdade eu nem reparei enquanto digitava. Em Java isso pode levar, por exemplo, a pensarmos que a indentação vai colocar dois comando dentro do `if`. O problema é que estou estudando Python, então já viu... :S
Answer: Do ponto de vista da performance, não há razões para se escolher entre uma e outra, a diferença deve ser negligível. Ainda que a representação das duas formas no bytecode seja distinta, a performance será muitíssimo semelhante, com diferença de uns poucos ciclos quando muito (em contraste, um cache miss na L1 "desperdiça" 10-40 ciclos, na L2 mais de 600).
Do ponto de vista da legibilidade, creio que vai depender da semântica do seu programa. Se a condição if se refere a um caso excepcional, creio que o ideal é omitir o else:
if ( denominador == 0 )
    throw new RuntimeException("Não pode dividir por zero");
quociente = numerador / denominador;

Por outro lado, se a condição if fizer parte de um conjunto mutuamente excludente, então creio que seria interessante incluir o else (ou talvez até mesmo um else if):
if ( x < 10 )
    return foo(x);
else if ( 10 <= x && x <= 20 )
    throw new RuntimeException("x não pode estar dentro do intervalo");
else if ( 20 < x )
    return bar(x);
// else
//     throw new RuntimeException("Isso nunca deve acontecer");

Comment: @uaiHebert Prefiro deixar cada um escolher seu próprio estilo de codificação. Pessoalmente, essa sintaxe me desagrada, mas se a comunidade Java tiver isso como consenso (não saberia dizer, pois faz anos que não trabalho com essa linguagem) sintam-se livres para editar meu código de exemplo.
Comment: @mgibsonbr até entendo o que você disse, e inclusive eu as vezes distraio quando misturo por exemplo, Harbour e C no mesmo source, e esqueço o ";" na parte C. Agora, dizer que usar if sem {} não é boa prática ja me soa um tanto prepotente. É como usar OOP ou não. Não tem melhor, quem sabe usar os dois usa no lugar certo e do jeito certo, conforme a linguagem permite, e fica bom.
Comment: Nâo é boa prática deixar um if sem {}. Inclusive no livro Java Coding Guidelines pode levar a problemas de segurança.
Comment: @Bacco Eu normalmente trabalho com Python, que não possui `{ }` e usa a edentação para definir blocos. Se eu hoje fosse programar em Java, provavelmente ia esquecer que `{ }` existe (da mesma forma que costumo esquecer de colocar `;` no final das instruções) e criaria um `if` com múltiplas instruções. O problema é: somente a primeira estará dentro do `if`, as demais estarão fora. Isso é um erro comum, e muita gente sugere nunca omitir o `{ }` por causa disso (concordar ou não é outra história). Essa é uma razão, embora não saiba a que o uaiHibert se refere quando diz "problemas de segurança".
Answer: O seu if é uma "guard clause": uma cláusula que, se verdadeira, impede a execução do resto do código do método (ou de um loop). Guard clauses sempre contêm código de "pulo", como return, throw, break ou continue. Elas servem como pré-condições para execução de certos blocos de código.
Minha opinião pessoal é de que essas cláusulas não precisam de else, já que o código vai "pular" fora mesmo:
if (condicao) throw new RuntimeException("Oops");

.... resto do código

Imagine um método com muitas pré-condições, usando else faria o código mais ilegível.
Note que também faço o seguinte para "Guard Clauses":

deixo o código do if e do "pulo" na mesma linha
não uso um bloco delimitado com {}

Veja uma resposta a uma pergunta semelhante que fiz no SO.
No clássico livro Refactoring de Martin Fowler, existe uma refatoração para transformar de condicionais aninhados para guard clauses.
Answer: Na minha opinião, quanto menos contexto melhor. Em geral, um contexto diferente é iniciado com { e finalizado com }, e do ponto de vista de quem lê o código, equivale a coisas do passado que devem ser lembradas para que o código possa ser compreendido.
Por exemplo:
public int metodo(int parametro) {
    if (parametero < 0) {
        throw new IllegalArgumentException();
    } else {
        // Estamos no contexto do else que está dentro do contexto do método.
        // Ou seja, você tem que ter estes dois contextos em mente.
        return 42 + parametro;
    }
}

Já aqui:
public int metodo(int parametro) {
    if (parametero < 0) {
        throw new IllegalArgumentException();
    }

    // Estamos no contexto do método, fora de qualquer if ou else.
    return 42 + parametro;
}

Isso se torna bastante evidente em códigos como este:
public boolean validaCPF(String cpf) {
    if (cpf == null || cpf.length() != 11) {
        return false;
    } else {
        int a = 0, b = 0;
        for (int i = 0; i < 9; i++) {
            int c = cpf.charAt(i) - '0';
            if (c < 0 || c > 9) {
                return false;
            } else {
                a += c * (i + 1);
                b += c * (9 - i);
            }
        }
        a = (a % 11) % 10;
        b = (b % 11) % 10;
        if (cpf.charAt(9) - '0' == a && cpf.charAt(10) - '0' == b) {
            return true;
        } else {
            return false;
        }
    }
}

Que fica muito melhor assim:
public boolean validaCPF(String cpf) {
    if (cpf == null || cpf.length() != 11) return false;

    int a = 0, b = 0;
    for (int i = 0; i < 9; i++) {
        int c = cpf.charAt(i) - '0';
        if (c < 0 || c > 9) return false;
        a += c * (i + 1);
        b += c * (9 - i);
    }
    a = (a % 11) % 10;
    b = (b % 11) % 10;
    return cpf.charAt(9) - '0' == a && cpf.charAt(10) - '0' == b;
}

Isso demonstra que se o else puder ser evitado, o código fica mais limpo.


Vuetify Autocomplete Links

Question: I am wondering how I can attach links to items within a Vuetify autocomplete. I would like to do this so that it would act as a search bar. As of right now, I can attach links to the v-list-item but the link won't cover the entire width of the container. It appears to just form a link around the text instead of the entire item. I've tried to wrap the entire component but that doesn't seem to work either. I've also tried looking at the docs (https://vuetifyjs.com/en/components/autocompletes/) but I can't seem to find anything on making items links there either. Thanks for any help in advance.

      <v-autocomplete
        v-model="model"
        :items="users"
        :loading="isLoading"
        :search-input.sync="search"
        clearable
        hide-details
        hide-selected
        item-text="username"
        item-value="symbol"
        placeholder="Search"
        flat
        solo
        dense
      >
        <template v-slot:item="{ item }">
          <v-list>
            <v-list-item-group v-model="item">
              <v-list-item-content>
                <v-list-item link :to="'users/' + item.id">
                  {{item.username}}
                </v-list-item>
              </v-list-item-content>
            </v-list-item-group>
          </v-list>
        </template>
      </v-autocomplete>

Answer: The item slot should be <v-list-item/> only since the wrapping element of those item slots are <v-list/> already by default.
<v-autocomplete
...
>

  <template v-slot:item="{ item }">
    <v-list-item link :to="'users/' + item.id">{{item.username}}</v-list-item>
  </template>

</v-autocomplete>

Here's a demo.
Comment: @avimimoun, that's true because the demo does not have vue-router configured. That's why the `:to` prop of v-list-item does not work. More info on the `:to` prop here: https://router.vuejs.org/api/#to
Comment: This results in a link, but does not redirect. The drop-down menu remains
Comment: @avimimoun in his demo that's true yeah, I tried locally on my project and link seems to work - redirects to any page normally when clicked

Vuetify Autocomplete Links


Vim inner tag blocks for Django templates

Question: Does a plugin exist which provides these text objects for Django templates? For example, in HTML/XML if I have the following text

This is some text.

and my  cursor is positioned anywhere inside the tags, I can use cit to change the text inside the tags. I'm looking for something similar for Django templates. For example, with the text
{% block title %}This is the title{% endblock %}

I'd like the same behavior. If nothing exists, any vimscripters out there know if this is possible and willing to give some hints?
Thanks!
Comment: @RandyMorris Cleaning up old questions. Could you post that as an answer? It's the closest I have to a solution.
Comment: Done, and thank you for revisiting old questions.  We need more like you.
Answer: Have a look on the official Django documentation.
There is a "Using Vim with Django" section.
https://code.djangoproject.com/wiki/UsingVimWithDjango
and a surround mapping part.

Here is an extract :
let b:surround_{char2nr("v")} = "{{ \r }}"
let b:surround_{char2nr("{")} = "{{ \r }}"
let b:surround_{char2nr("%")} = "{% \r %}"
let b:surround_{char2nr("b")} = "{% block \1block name: \1 %}\r{% endblock \1\1 %}"
let b:surround_{char2nr("i")} = "{% if \1condition: \1 %}\r{% endif %}"
let b:surround_{char2nr("w")} = "{% with \1with: \1 %}\r{% endwith %}"
let b:surround_{char2nr("f")} = "{% for \1for loop: \1 %}\r{% endfor %}"
let b:surround_{char2nr("c")} = "{% comment %}\r{% endcomment %}"

Put the above in ~/.vim/ftplugin/htmldjango.vim.
Examples in visual mode (select some text first):

type Sv or S{ for a variable
type Sb for a block
type Si for an if statement
type Sw for a with statement
type Sc for a comment
type Sf for a for statement
type S% for other template tags

PS : another possibility is the use of eclim (vim + eclipse) which supports Django project and template editing http://eclim.org/vim/python/django.html but that's a lot heavier.
Comment: Yes. I've seen this before, but this what I was asking about. Still nice though. Thanks :)
Answer: The django-template-textobjects plugin (https://github.com/mjbrownie/django-template-textobjects) allows you to achieve this.  It adds a series of text objects (for example db for Django block, df for Django for loop, etc).
For example, cidb would allow you to change the contents of:
{% block stylesheets %}My stylesheets here{% endblock %}

The plugin depends upon another plugin, vim-textobj-user (https://github.com/kana/vim-textobj-user), so remember to install that first.
Answer: You're probably going to have to write your own text-object for this. See textobj-rubyblock and vim-indent-object for examples of how to accomplish this.
Comment: Thanks Randy! Haven't gotten around to doing this, but if I do, I'll post here.


Como concatenar variável com fórmula no Excel?

Question: Está correto eu concatenar uma variável a uma fórmula do Excel?
O Excel reclama no fechamento da concatenação:
Sheets("FATURA").Select
Dim variavel As Double
variavel = InputBox("Digite Valor da Tarifa caso nao souber Digite 0,35")
MsgBox ("Valor sem desconto: " & variavel)
Range("Z2:Z" & Range("I1048576").End(xlUp).Row).Formula = "=RC[-1]&IF(RC[-2]< " &variavel& ,""M"",""O"")"

Comment: Tentei formatar teu código, mas não faço ideia se tá certo. Você pode clicar em [edit] e formatá-lo.
Answer: Marcio, boa tarde!
Na  minha visão sim é possível e esta certo, pois se faz necessário  conforme sua necessidade de dinamismo ao construir a fórmula. Então sege minha sugestão de como creio que funcionará:
Sheets("FATURA").Select

Dim variavel As Double

variavel = InputBox("Digite Valor da Tarifa caso não souber Digite 0,35")

MsgBox ("Valor sem desconto: " & variavel)

Range("Z2:Z" & Range("I1048576").End(xlUp).Row).Formula = "=RC[-1]&IF(RC[-2]< " & variavel & ," & chr(34) & "M" & chr34) & "," & chr(34) & "O" & chr(34) & ")"

Comment: Bacana amigo vou testar
Comment: Joguei o Resultado em uma célula e fiz o calculo a partir da mesmo q resolveu meu problema


Proving the orthogonality of $\sin\frac{2\pi x}{\pi-e}$ and $\cos\frac{2\pi x}{\pi-e}$

Question:
I want to prove the orthogonality of the functions: $\sin\left(\dfrac{2\pi x}{b-a}\right)$ and $\cos\left(\dfrac{2\pi x}{b-a}\right)$, where $b=\pi$ and $a = e$

My work:
$$\begin{align}
\int^{\pi}_{e} \frac{1}{2} \sin\left(\frac{4\pi x}{\pi - e}\right)dx
&= -\frac{\pi - e}{8 \pi} \left[\cos\left(\frac{4\pi x}{\pi - e} \right)\right]^{\pi}_e \tag{1}\\[6pt]
&= \frac{e-\pi}{8\pi}\left[\cos\left(\frac{4\pi^2}{\pi - e} \right) - \cos\left(\frac{4\pi e}{\pi - e}\right) \right] \tag{2}\\[6pt]
&= \frac{\pi - e}{4\pi} \left[\sin\left(\frac{2\pi (\pi - e)}{\pi - e} \right)\sin\left(\frac{2\pi (\pi + e)}{\pi - e} \right) \right] \tag{3}\\[6pt] = 0
\end{align}$$
Haven't I made any mistake?
Comment: Step $(2)$ to $(3)$ is incorrect. You cannot factor the cosine arguments like that. (That is, $\cos(pq)-\cos(pr) \neq \cos(p)(q-r)$.) What you *can*  do is apply the [sum-to-product  identity](https://en.wikipedia.org/wiki/List_of_trigonometric_identities#Product-to-sum_and_sum-to-product_identities) $$\cos a - \cos b = -2\sin\left(\frac{a+b}{2}\right)\sin\left(\frac{a-b}{2}\right)$$ Then you can see about simplifying the individual arguments within the sines.
Comment: @Blue Ok, now I corrected the third equation and I get that the functions are orthogonal.
Comment: That's it. Congratulations! :)
Answer: No mistake.
In general, the two functions $f$ & $g$ are said to be orthogonal if the integral of their product (treating as dot or inner product of two vectors) over some arbitrary interval is zero
$$\langle f,g\rangle =\int f(x)g(x)dx=0$$


How do I show that the zeroes of $f(z) = z^4 -2\cos(2\theta) z^2 +1$ are $e^{i\theta}$, $e^{-i\theta}$, $-e^{i\theta}$, $-e^{-i\theta}$?

Question: N.B. $z$ is a complex number.
This is what I have so far:
$$f(z) = z^{4} -2 \cos(2\theta) z^2 +1 =R^4 (\cos(4\theta)+i\sin(4\theta))-2R^2\cos(2\theta)(\cos(2\theta)+i\sin(2\theta)) +1 =0$$
$$ = R^4 (\cos(4\theta)+i\sin(4\theta)) -2R^2 \cos^2(2\theta) -2R^2i\cos(2\theta)\sin(2\theta)+1$$
$$=R^4 (\cos(4\theta)+i\sin(4\theta)) -R^2 (\cos(4\theta)+1)-R^2i\sin(4\theta)+1$$
$$=\cos(4\theta)(R^4 - R^2)+i\sin(4\theta)(R^4-R^2)-(R^2-1)$$
$$=(R^2-1)(R^2\cos4\theta +R^2 i \sin(4\theta)-1)$$
$$=(R^2-1)(R^2e^{i4\theta}-1)$$
and that's as far as I can get - if somebody would be able to point out where I've gone wrong, how I can get from here to the answer or a better way of doing this, anything would be much appreciated - thanks!
Comment: Use the quadratic formula
Comment: The formula is wrong, as you can see by plugging in $\theta=\pi$, for which the roots are $i$, $i$, $-i$, and $-i$, not $-1$, $-1$, $1$, and $1$. The correct formula is in George's answer, with $\cos2\theta$ instead of $\cos\theta$.
Answer: You can view the equation $z^4-2\cos(2\theta)z^2+1=0$ as a quadratic in the variable $z^2$. Hence by the quadratic formula
$$z^2=\dfrac{2\cos(2\theta)\pm\sqrt{4\cos^2(2\theta)-4}}{2}=\cos(2\theta)\pm i\sin(2\theta)=e^{\pm2i\theta}.$$
Therefore, upon square rooting both sides (consider roots of unity) you obtain the values given above.
To see the expression for $z^2$ simplifies down sufficiently recall $\cos^2(x)+\sin^2(x)=1$ for all $x\in\mathbb{R}$.
Comment: Thank you, I did actually try this but was missing a factor of i, hence thought this method didn't work. Thanks for pointing out my error there
Comment: Note that the OP was working with the wrong formula, with $\cos\theta$ instead of $\cos2\theta$.
Answer: You could always multiply $(z-e^{i\theta})(z+e^{i\theta})(z-e^{-i\theta})(z+e^{-i\theta})$ out and see what you get.
Or, from where you left off, how about writing $R^2e^{4i\theta}-1=(Re^{2i\theta}+1)(Re^{2i\theta}-1)=(\sqrt Re^{i\theta}+1)(\sqrt Re^{i\theta}-1)(\sqrt Re^{i\theta}+i)(\sqrt Re^{i\theta}-i)$.  So in fact, if what you did is correct, we get $\pm\sqrt Re^{i\theta}, \pm i\sqrt Re^{i\theta}$, instead.
Note that you used the same $\theta$ for $z$ as appears in the equation.  You haven't really got a polynomial.  The whole unit circle, $R=1$, is a solution.


In a set of 5 bottles,1 has a fracture.If you select a pair of bottles, probability that the fractured bottle is chosen is?

Question: Its also mentioned that this question is an example of Sampling without replacement
My question is , by the general method of how I do these kind of problems , I would assume that there are two possibilities

You chose a defective bottle and then  a non defective which will have the probability of
<code>  1/5 X 4/4 = 4/20

    OR
</code>
Choosing a non defective one first and then a defective one which will have the probability of
<code>4/5 x 1/4 =4/20
</code>

Total probability is 8/20= 2/5 which doesn't make sense at all, since there is just one bottle to begin with
But the problem is I cant find a fault in my logic. Though I feel both the options are redundant , isn't both two different ways of selecting the pair?. Or is the fact that the phrase "one after the other" is absent a reason on why this might be a wrong approach?
<code>    Thank you in advance
</code>
Comment: You're getting $2/5$ since the the total number of outcomes is $10$ and not $5$.
Comment: $4$ out of the $10$ possible selections contain a fractured bottle.
Answer: In the general case, say there are $n$ bottles, and you choose $k$ of them. There is only one flawed bottle.
The number of ways to pick $k$ bottles from $n$ is the binomial coefficient $\dbinom{n}{k}=\dfrac{n!}{k!(n-k)!}$.
Now we count the number of these $\dbinom{n}{k}$ arrangements that contain the flawed bottle.
By hand is OK for small $n$ and $k$, for example with $n=4,k=2$ we have $\dbinom{4}{2}=6$ cases:

AB..
A.C.
A..D
BC..
.B.D
..CD

and if the flawed bottle is A (it doesn't actually matter) then there are three cases with an A in them, and so the probability is $\dfrac{3}{6}=0.5$.
More generally, we need to know the number of arrangements that have the flawed bottle.
If we remove the flawed bottle, then we have $n-1$ bottles, and we want to know the number of arrangements of any $k-1$ of them, as we then add the flawed bottle back to give us the total number of arrangements we require. This is $\dbinom{n-1}{k-1}$.
So the general probability is given by:
$$\frac{\dbinom{n-1}{k-1}}{\dbinom{n}{k}}=\frac{(n-1)!}{(k-1)!(n-k)!}\cdot\frac{k!(n-k)!}{n!}=\frac{k}{n}$$
A perhaps more intuitive method is to pick the $k$ bottles first, and then someone assigns a bottle as flawed from the $n$  bottles. You have a $k$ in $n$ chance of getting the flawed bottle.
Answer: You can think of this problem in two ways. One way is the one you did which is perfectly fine.
The other is to think about the possible outcomes you can have at the end of the two selections. There are $5\choose 2$ total number of selections you can make. Now assume that you have already selected the fractured bottle. There are ${4\choose 1}=4$ different ways of selecting the second bottle. Therefore probability that the fractured bottle is chosen is
$$
\frac{4\choose 1}{5\choose 2}=\frac{4}{10}=\frac{2}{5}
$$
PS: If order of selection is taken into consideration then the total number of outcomes will simply be doubled (since the permutation of the selected pair also matters). But this doesn't affect the final answer as $\frac{{4\choose 1}\times 2}{{5\choose 2}\times 2}=\frac{4\choose 1}{5\choose 2}$
Answer: Here is another viewpoint.
Suppose you don't know there is a flawed bottle. You choose two of the five bottles. You are then told that one of the five bottles contains a crack. It is equally likely to be any of the five bottles, so each bottle has a probability of $\frac{1}{5}$ of being the cracked one.
You hold two bottles, so the probability of either one of them being the cracked one is $\frac{1}{5}+\frac{1}{5}=\frac{2}{5}$. Note that you can add these two probabilities because they are mutually exclusive events - they cannot both be cracked as there is only one cracked bottle.
Edit: I see now that JMP already briefly mentioned this at the end of his answer.
Answer: Your logic is perfectly sound. The answer is $\frac{2}{5}$. I think you find it odd that this is more than the probability of choosing one bottle and it being fractured, but this is actually what you must expect.
Think of the bottles trying to 'clear an exam'. If the exam is easy, more students tend to pass. Thus, each student has a higher chance of passing. You allowing more bottles to 'pass' (choosing more bottles) gives more chance for the fractured bottle to pass too! In the extreme case where all bottles pass, this becomes obvious.


Does every prime > 2 have a primitive root that is a prime?

Question: Every prime number has a primitive root. Actually, for every prime number p a considerable percentage of the numbers from 2 to p-1 are primitive roots (with the exception p = 2 which is the only prime that has 1 as a primitive root).
Following a discussion how to find primitive roots, I thought it would be a good idea to start checking whether the small primes (2, 3, 5, 7, 11, ... ) are primitive roots because they seem to be more than average likely to be primitive roots. That obviously raises the question whether every prime p other than 2 actually has a primitive root in the range from 2 to p-1 that is prime.
Googling didn't find any answer. There doesn't seem to be an obvious answer, for example p = 41 has the primitive root 6 but neither 2 nor 3 are primitive roots (2^20 = 3^8 = 1 modulo 41). There should always be a prime primitive root because of the sheer numbers of primitive roots (p = 271 with smallest prime primitive root 43 seems quite exceptional), but a proof would be nice.
Comment: See http://math.stackexchange.com/questions/422201/existence-of-a-prime-p-for-which-a-is-a-primitive-root?rq=1.
Comment: Not the same question, but shows there are a lot of easy questions with no easy answers...
Answer: The answer is yes. Let $a$ be a primitive root of $p$. Then $a+kp$ is a primitive root of $p$ for every $k$. By Dirichlet's Theorem on primes in arithmetic progression, there are infinitely many primes of the form $a+kp$.
Remark: The problem of whether for any  prime $p\gt 2$ there is a primitive roots $a$ with $2\le a\le p-1$ is open. I believe that the best unconditional result is that for large enough $p$, the least prime primitive root of $p$ is $\lt p^k$, for a constant $k\approx 3$. Under reasonable but unproved hypotheses (versions of GRH) one can bring this down to a power of $\log p$.
One can find some information, and references, in Greg Martin's The Least Prime Primitive Root and the Shifted Sieve.
You may also want to look at this paper, sadly behind a pay wall. There is a fair literature on the subject.
Comment: @gnasher729 There are infinitely many integers that represent a given residue class modulo $n$. When we speak of the product of primitive roots, we mean their residue classes. When we speak of a primitive root being prime, we mean being represented by a prime integer (note that primitive roots, as residue classes, are units hence cannot be prime in the ring of integers mod $n$).
Comment: I'd say that is a quite non-standard interpretation of "primitive root", so I'll change the question accordingly. For example, Wikipedia says "Gauss proved[4] that for any prime number p (with the sole exception of p = 3), the product of its primitive roots is congruent to 1 modulo p." Which doesn't make any sense if you accept an infinite number of primitive roots.
Comment: Anyone voting this up: This reply does _not_ in any way answer the question.
Comment: I think the question is whether any prime less than p can be a primitive root mod $p$.
Comment: No, my question is whether for every prime p other than 2, there is a prime number among the primitive roots of p. Yours is an interesting but different question.
Comment: If you read the question, it is quite clear what was meant. It is made even more clear by the text in bold in the question.
Answer: Probabilistically, the answer seems likely to be yes, but proving it (at least for sufficiently large $p$) might be a different matter. Here is a very special case where the answer is provably yes, in the strict sense asked for in the question. Let $p$ be a Fermat prime. Then the primitive roots (mod $p$) are the quadratic non-residues (mod $p$). Since the multiplicative group of the field of $p$-elements is cyclic of order a power of $2,$ it is generated by any element which is not a square, and obviously can't be generated by any square. There are $\frac{p-1}{2}$ quadratic residues, so there is an integer $n$ with $1 < n < p$ which is not a quadratic residue (mod $p$). Hence there must be a prime divisor $q$ of $n$ which is not a quadratic residue either. This prime $q$ must be a primitive root (mod $p$). Unfortunately, Fermat primes seem to be rather thin on the ground.
Note added later: in fact, using quadratic reciprocity, it is possible to see that $3$ is a quadratic non-residue (mod $p$) whenever $p >3$ is a Fermat prime. This is because $p \equiv 2$ (mod $3$) and $p \equiv 1$ (mod $4$). Hence $3$ is a primitive root (mod $p$) for any Fermat prime $p \geq 5.$ Clearly $2$ is a primitive root (mod $3$).
Even later edit: If $p = 2q+1$ for some odd prime $q,$ then it is again easy to see that any quadratic non-residue (mod $p$) other than $p-1$ is a primitive root (mod $p$)- possible element orders in the multiplicative group are $1,2, q$ and $2q$, and the quadratic residues other than $1$ are the elements of order $q.$ It follows that the smallest integer $n$ with $1 < n < p-1$ which is a quadratic non-residue (mod $p$) is a prime, and is a primitive root (mod $p$).
Comment: I think it also works if p = 4q + 1 for some odd prime q. Let g be a primitive root, and s = g^q (modulo p). If s > 2q then replace g with p-g, and s <= 2q. x is a primitive root iff x^q = s or -s (modulo p) and x ≠ s, x ≠ p - s, and x ≠ p - 1. If (ab)^q = +/- s (modulo p) then either a^q or b^q is +/- s (modulo p). Take the smallest primitive root which is not divisible by an odd power of s, and that primitive root is prime or has a prime factor which is a primitive root. This fails if p = 6q + 1.
Comment: Yes, I agree. In fact, I think $2$ is always a generator for such a prime. For note that $(s+1)^{2} = s^{2}+1 + 2s$ is a residue. But $s^{2}+1 = 0,$ so $2s$ is  residue. But $s$ is a non-residue, so $2$ is a non-residue, and the order of $2$ is divisible by $4$. However $2^{4}-1 = 15$ is not divisible by $p,$ so $2$ does not have order exactly $4,$ and must have order $4q,$ so is primitive.


How to interpret this normal qq-plot?

Question:
I have tried to fit a glm to some weather data and I got this weird qq-plot. What could this possibly mean? I am aware of how various skewed error distribution qq-plots should look like, but what I have here seems more bizarre.
Comment: What kind of GLM was it? GLMs shouldn't necessarily have normal residuals (see [here](http://stats.stackexchange.com/a/139624/7290)).
Comment: Is this maybe a Poisson regression with small counts?
Comment: What is `nF`? Is it a limited range DV?
Comment: Is this a possible [duplicate](http://stats.stackexchange.com/questions/101274/how-to-interpret-a-qq-plot)? (However, gung's point is relevant; the interpretation may not matter much, depending on omitted details about the GLM)
Comment: Simulate data from the **estimated** regression model, calculate residuals, repeat 1000 times, and plot those simulated residuals as a comparison distribution.  Then we can see if this is typical residuals from your model, or not.  There is in general no reason to expect normal residuals from an GLM.
Answer: You've got some non-normal residual tails over there, especially a very heavy right one. Might want to consider taking a transform of your dependent variable. A log transform might help quite a bit, but no way to tell for sure without seeing the actual variable distribution, along with the rest of the residual plots (for both dependent and independent variables).
Some resources that might help you:
http://onlinestatbook.com/2/advanced_graphs/q-q_plots.html
https://www.youtube.com/watch?v=X9_ISJ0YpGw
Comment: Standard transformations won't work, because they will not be sufficiently non-differentiable at a particular value. We should instead suspect some form of a *mixture* or perhaps *heteroscedasticity*, and model it accordingly.
Comment: @whuber - fair point. I think I rushed into the suggestion because I was just working on a problem that had an initial qqplot similar to the one above and an exponentially-distributed dependent variable. To your point however, heteroscedasticity was present and it took the introduction of polynomials and interaction terms to deal with it.
Comment: quasi-poisson doesnt change the estimated model parameters, it only affects hypothesis tests/standard errors/confidence intervals.
Comment: This is actually a Poisson glm with log link. I've even tried quasi poisson, but that doesn't change much.
Comment: If you've used the log link, then the transformation is already factored in. As whuber said, this is one likely in need of dependent variable manipulation and/or introduction, so you'll have to dive deeper into the residual plots.

How to interpret this normal qq-plot?


Cross Validation and Confidence Interval of the True Error

Question: I'm interested in the relation between Cross Validation and the True Error Estimation of a Classifier (Chapter 5 - Machine Learning - Mitchell).
Suppose we have 150 examples, I decide to use a 100 repeated 5-fold Cross Validation to understand the behavior of my classifier. At this point I have $100 \times 5$ results and I can use the mean and std dev of the error rates to estimate the variance of the model performance.
$$\text{mean(Error Rate)} \pm z \times \text{std(Error Rate)}$$
I could estimate Confidence Interval of the True Error (that I would obtain on the unseen data) using the the average Error rate:
$$\text{mean(Error Rate)} \pm z \times \sqrt{ \frac{mean(errorRate) \times (1 - mean(errorRate) )}{ N}}$$
Two questions:

Is this approach correct?
Is correct to set $N=150$ in the second equation or I should use the average number of Test Data used as Test Set in each fold of CV ($N = 30$)?
Comment: Have a look here https://stats.stackexchange.com/questions/61783/bias-and-variance-in-leave-one-out-vs-k-fold-cross-validation/357749#357749 and here http://www.jmlr.org/papers/volume5/grandvalet04a/grandvalet04a.pdf - this is no easy topic and is subject to much debate - but if you bootstrap sample a large enough data set and your algorithm is stable you can hope to estimate some sort of true confidence interval
Comment: This is a perfectly reasonable question w/ a good answer. I'm voting to leave open.
Answer: Background
Consider the following definitions:

A training set $D = {z_1,...,z_n}$ with $Z_i \in Z$ independently sampled from an unknown distribution $P$.
An algorithm $A$ which maps a data set to a function $A : \mathcal{Z} \rightarrow \mathcal{F}$
A loss function $L$. e.g. a quadratic loss: $L(f,x,y)) = (f(x) - y)^2$ or a missclassification ${0,1}$ loss $L(f,x,y)) = 1_{f(x) \neq y}$
Let $f = A(D)$ be the function returned by algorithm $A$ on the training set $D$

We can define two measures of importance:

Prediction error: expected loss on future test examples
$$ PE(D) = E[L(f,z)]$$
Where the expectation is taken with respect to $z$ sampled from $P$
Expected performance error: a more general measure which is the expected loss on training sets of size $n$ sampled from $P$
$$ EPE(n) = E[L(A(D),z)]$$
Where the expectation is taken with respect to $D$ sampled from $P$ and $z$ is independently sampled from $P$ also

Cross validation estimator
In practice the data set $D$ is chunked into $K$ disjoint subsets of the same size with $m = n / K$. Let us write $T_k$ for the $k$-th such block and $D_k$ for the training set obtained by removing the elements in $T_k$ from $D$, then

The cross validation estimator is defined as the average of the errors on test block $T_k$ obtained when training the algorithm on $D_k$
  $$ CV(D) = \frac{1}{K} \sum_{k=1}^K \frac{1}{m} \sum_{z_i \in T_k} L(A(D_k), z_i)$$

Once you have this Cross Validation Estimator $CV(D)$ you can construct bootstrap confidence intervals around it in the same way as you would for any other estimator. Bootstrap your dataset, compute the estimator, repeat many times...
The difficulty lies in understanding what you are actually computing, and how close it is from the truth... Here are a few questions:
- Is the mean of the $CV$ an estimator of the $PE$ or the $EPE$ ?
- What about the variance of $CV$ ? Does it inform us about the uncertainty of the PE or EPE ?
- Under what conditions is the difference $|CV(D) - PE(D)|$ bounded ?
- And lastly how does bootstrapping effect all of the above ?
This is an active topic of research and there are different views, conclusions, proofs to be taken into account. The paper linked below is a good place to start if you want to go into more depth.

Sources and further reading

The theory, definitions and explanations are taken from this paper from Grand Valet
The following two stackexchange posts go into significant depth on the topic: Bias and variance in leave-one-out vs K-fold cross validation and Variance of $K$-fold cross-validation estimates as $f(K)$: what is the role of "stability"?
Comment: Thanks for this answer, do you have a reference for using bootstrap on top of cross-validation? It makes sense to me, and I saw it in some papers, but I would like to have something to cite
Answer: I think you should use the following as CL:
CL = mean(Error Rate) ± ×std(Error Rate)/10
10 comes from sqrt(100). Error Rate is the average Error Rate from each CV round, so it is averaged over every 5-fold CV. So Error Rate has 100 elements.
Alternatively you can use bootstrapping of Error Rate. Let's say you create 60 bootstrapped samples from Error Rate, for each of the 60 bootstrapped samples, you'd calculate the mean. So you get 60 Error_Bootstrap values. Now use
CL = mean(Error_Bootstrap) ± ×std(Error_Bootstrap)
Notice how we don't need to divide by sqrt(size) in bootstrapped calculation. Hope this helps.


Is it okay to use `require('babel/register);` in production?

Question: It should not use babel-node in production according to the official document of Babel. Some said you can use babel/register instead of babel-node if you don't want to compile your ES6 code into ES5 before running. But doesn't babel-node use babel/register internally? What is the difference between babel-node and  require('babel/register');. Is it okay using require('babel/register'); in production?
Comment: Is no one reading tag descriptions? `babel` is for questions for a Python library with said name.
Comment: I've been wondering this myself too; I noticed that the official babel example doesn't - https://github.com/babel/example-node-server
Comment: `babel-node` implements its own CLI interface, so it does much more than requiring `'babel/register'`.
Comment: As for you question, a lot of people do it (including myself), but I'm still looking forward to see some good reasoning whether it's a good or bad practice.
Comment: I think the only drawback is that at the first request that hit the server, babel will transform and re-compile all the code and this will take some more time than normal. But, as said this will happen ONLY for the first request that hit the server (this case usually occurs after a new build of the code – i.e. after deploying a new feature), as code will be cached for subsequent requests, so I see no real issue in using it in production.
Answer: The Babel Handbook (linked from babeljs.io) says that it's bad practice to use babel-register in production (see babel-register user guide):

Note that this is not meant for production use. It's considered bad practice to deploy code that gets compiled this way. It is far better to compile ahead of time before deploying. However this works quite well for build scripts or other things that you run locally.

So it seems the suggested way is to compile before running using the babel command from the babel-cli package.
This also fits in with the npm advice on using transpilers. (That advice is given for authoring npm packages, but applies in this case too).
Answer: I believe the correct way to do it is to build it (babel src -d dist) and serve the transpiled version. This is what I'm currently doing as it feels safer, though I'm still having to import babel-polyfill in my startup file for the regenerator runtime to work. Without it I receive the ReferenceError: regeneratorRuntime is not defined.
https://babeljs.io/docs/usage/polyfill/

server.js

'use strict'

if (process.env.NODE_ENV === 'development')
  require('babel-register')

require('babel-polyfill')
var log = require('nlogger').logger(module)
var app = require('express')()

var cfg = require('./config')
var db  = require('./db')

db.once('open', function () {
  log.info('MongoDB connected.')
})

db.on('close', function () {
  log.info('MongoDB closed.')
})

db.on('error', function (err) {
  log.error('MongoDB connection error:', err)
})

require('./middleware/express')(app)

var server = app.listen(cfg.port, function () {
  log.info('Server listening on port ', cfg.port)
})

// Start socket.io & bring in routes
var io = require('./io')(server)
require('./router')(app, io)

server.on('close', function () {
  log.info('Server connection closed.')
})

module.exports = server


Applying TF/IDF to non-text data?

Question: I have a classification problem in which I am supposed to predict the end state of an object based on a set of events it experiences. There are about one thousand possible events and each object is impacted by 10-50 events.
First, I tried logistic regression (using glmnet to be specific) and got AUC = 0.59. My plan was to try xgboost next, but when I looked the data again, I realised that it looks similar to bag-of-words, with a lot of zeros and small integers here and there. That made me want to try TF-IDF for feature engineering: the events are words, and the objects are documents. Right away I got AUC > 0.7.
I did some googling to find more information about this approach, but could not find anything. So, my questions are:

Can TF-IDF be used for non-text data?
what are some potential pitfalls of this approach?
Are there any links or references to existing applications of TF-IDF for non-text data?
Comment: Interesting question, can you tell us what is your analogy of *documents* and *words*?
Answer:

Can TF-IDF be used for non-text data?

Sure. I've used it very successfully on medical records where every ICD-10 diagnosis or procedure code is a "word" and every patient is a "document." Very common procedures like EKGs and lipid panels get lower weights. This allows LSA to be applied. While we ultimately went with an LDA model which doesn't need TF-IDF preprocessing, the LSA model with TF-IDF definitely worked as intended.

what are some potential pitfalls of this approach?

Many models, such as linear or logistic regression, ignore the scale of individual features; for those models, the "IDF" part isn't necessarily doing any work. However, if your using a regularized model such as ElasticNet, then the scale becomes important. Usually we want to standardize each feature by centering and scaling, but TF-IDF can also be used as a principle way to assign different scales to each feature. This brings us to a further complication: TF-IDF isn't one concrete formula like MSE. If you say MSE, I could write down the equation, but there are lots of variations of TF-IDF. Wikipedia lists several variations, for example.
It's rarely possible to guess ahead of time which scaling strategy will work best. I recommend using cross validation to compare many scaling strategies, such as raw TF, centered and scaled, and several TF-IDF variants.

Are there any links or references to existing applications of TF-IDF for non-text data?

In addition to my own project, I've seen other papers that use TF-IDF on medical codes. I'm not sure where else its been used, but it's potentially useful anywhere you can make a clear analogy for "words" and "documents."
Answer: I've used TF-IDF and LDA on non-text, and am not aware of pitfalls in general. That doesn't mean there aren't any pitfalls, though! And, of course, any bag-of-words approach is throwing away your time series' ordering, which can dramatically affect meaning.
In your use case, there are a couple of thoughts that come to mind:

It seems that there are no amounts associated with your events? In textual use, you tend to have word counts within documents. So you are working with just presence/absence data, which is even less information from the original time series.
Your solution appeals to me, and you can make the analogy that each object is a "document" and the events that happened to it are "words" and you're looking to categorize your objects ("documents") by "topic".  But some folks won't accept that and will demand a technique they are familiar with, instead of an off-brand usage.
I'd investigate your logistic regression more. I've heard of successful logistic regressions with 10,000 variables. They used Feature Hashing to compress the huge number of highly sparse features down to 10,000.
Have you tried an association rules approach? Do certain bigrams (adjacent pair of events) have high association with your target output? Be careful, though, since slicing your data more and more finely can cause associations "by chance" — look at enough cases, especially with small numbers, and you will eventually find something.

Applying TF/IDF to non-text data?


How to find lim $(\tan x)^{\tan(2x)}$, $x\to\pi/2.$

Question: The limit
Important condition: you can't use l'Hopital's rule.
I've been thinking about that for an hour, but still can't do it. I need a full solution. Wolfram says that the answer is $1.$
Thanks in advance.
Comment: Please consider typing out what you've got.
Comment: $1/\tan x$ is between $\pi/2-x$ and $(1+\varepsilon)(\pi/2-x)$ when $x$ is near $\pi/2. \qquad$
Comment: Take logarithms so you have  $A\log B=\dfrac{\log B}{\dfrac{1}{A}}=\dfrac{A}{\dfrac{1}{\log B}}$ and apply L'Hôspital to one of the two last expressions.
Comment: I'm really sorry guys, forgot to add that you can't use l'Hopital's rule.
Answer: Correct me if wrong:
Note:$ \tan(2x)=\dfrac{2\tan x}{1-tan^2 x}.$
Take $ \log $ of your expression:
$\tan 2x \log (\tan x)$
$f(y):= \dfrac{2y \log y}{1-y^2}$, where $y:=\tan x$.
$ \lim_{y \rightarrow \infty} f(y)= $
$\lim_{y \rightarrow \infty} 2\dfrac{y\log y}{y^2(1/y^2 -1)}=$
$\lim_{y \rightarrow \infty} 2\dfrac{\log y}{y(1/y^2-1)}=0.$
To get back to the original limit consider:
$ \lim_{y \rightarrow \infty} e^{f(y)}=$
$e^{ \lim_{y \rightarrow \infty} f(y)}=1.$
(Continuity of the exponential function).
Used $\lim_{y \rightarrow \infty} \dfrac{\log y}{y}=0$.
Answer: Calculate first the easier limit $$\lim_{x\to\frac{\pi}{2}}(1+\tan(x))^\frac{1}{\tan(x)}=1$$ Then do you have the expression $$(1+\tan(x))^{\tan(2x)}=(1+\tan(x))^{\frac{\tan(x)}{\tan(x)}\tan(2x)}=(1+\tan(x))^{\frac{1}{\tan(x)}\cdot\frac{2\tan^2(x)}{1-\tan^2(x)}}$$
Verify now that $$\lim_{x\to\frac{\pi}{2}}\frac{2\tan^2(x)}{1-\tan^2(x)}=-2$$ Your limit is equal to $1^{-2}=1$
Answer: Let $y=\pi/2-x\to 0$ and recall that
$$\tan x=\frac1{\tan(\pi/2-x)}=\frac1{\tan y}$$
$$\tan 2x=\frac{2\tan x}{1-\tan^2 x}=\frac{2\tan y}{\tan^2 y-1}$$
and then by $z=\tan y\to 0$ we have
$$\lim_{x\to \pi/2} (\tan x)^{\tan 2x}=\lim_{z\to 0} \left(\frac1z\right)^\frac{2z}{z^2-1}=\lim_{z\to 0} \left(\frac1{z^z}\right)^\frac{2}{z^2-1}=\left(\frac1{1}\right)^{-2}=1$$
Answer: Hint: if $f(x) = (\tan x)^{\tan (2x)}$, then $\ln f(x) = \tan(2x) \ln(\tan x) = \frac{\ln(\tan x)}{\cot(2x)}$.  Now, you should be able to apply l'Hopital's rule to this quotient, then do some simplification to find $\lim_{x \to \pi/2} [\ln f(x)]$.


Make the Main Menu have dynamic links based on url

Question: My main menu has links to common things: HOME | PHOTOS | VIDEOS ... etc. Home points to /, PHOTOS points to /photo-galleries and VIDEOS points to /videos
The client has added a new feature request and I'm trying to figure out how to handle this. The site has a couple of general topics, let's say baseball, football and soccer.
When I browse to the main home page /, then the menu should point to /photo-galleries and /videos.
However, when I browse to the "baseball filtered" home page /baseball then I'd like the photo galleries menu link to point to /photo-galleries/baseball and the videos link to point to /videos/baseball.
This "filtering" should follow them through out the site, so once they are on /videos/baseball then all of the menu links should continue to have the baseball element on them.
I'm unsure how to approach this problem and I feel like there should be an elegant way to handle this and I'm not the first person to have this problem.
I understand how to setup my various Views on the different pages so they have contextual filters and only show the content items with the baseball tag, but my big question is about how to handle re-writing all of the URLs of the menus and the content URLs.
Help? :)
Answer: 3 (updated) options (or a combination thereof) for you to consider:

The drupal module Menu Token provides the ability to put variables in your menu options -- and used in conjunction with your existing context filtered views, may work for you if it allows you to construct the menu options you need based on other tokens that it makes available to you.
The other option is to consider an alternative approach (sorry! :) ). This would be faceted filtering. Follow the tutorials here: http://webwash.net/tutorials/intro-search-api-part-1-how-create-search-pages
This is possible on even the most modest of hosting as it does not require Solr (but it can use it if you need that functionality later).
(added in update) Drupal module Menu Trail By Path

I think option 1 (perhaps in conjunction with option 3) might be the closest to what you are looking for though.
Answer: Hope this will help you,
In Drupal 7, for your requirement you can use ThemeName_links__system_main_menu function in your template.php file. This function works only for Main menu.
function ThemeName_links__system_main_menu($variables) {
  $links = $variables['links'];
  $html = "

";
  foreach ($links as $link) {
    if(baseball filtered) {
      if(home menu) {
        $link['href'] = 'baseball';
      }
      if(photo menu) {
        $link['href'] = 'photo-galleries/baseball';
      }
      if(video menu) {
        $link['href'] = 'videos/baseball';
      }
    }
    elseif(filter is football) {
      if(home menu) {
        $link['href'] = 'football';
      }
      if(photo menu) {
        $link['href'] = 'photo-galleries/football';
      }
      if(video menu) {
        $link['href'] = 'videos/football';
      }
    }
    elseif(filter is soccer) {
      if(home menu) {
        $link['href'] = 'soccer';
      }
      if(photo menu) {
        $link['href'] = 'photo-galleries/soccer';
      }
      if(video menu) {
        $link['href'] = 'videos/soccer';
      }
    }
    else {//for normal
      if(home menu) {
        $link['href'] = 'node';
      }
      if(photo menu) {
        $link['href'] = 'photo-galleries';
      }
      if(video menu) {
        $link['href'] = 'videos';
      }
    }
    $html .= "
" . l($link['title'], $link['href'], $link) . "
";
  }
  $html .= "
";
  $html .= "
";
  return $html;
}


Setting Firebase realtime database rules

Question: I'm trying to setup rules for my Firebase realtime database, and I can't figure out why aren't they working. Here is what the top of the data looks like:

Say I want to allow users to read data where their user name matches the name field in that data. I thought something like this would work
<code>{
  "rules": {
    "lauri_laurela" :{
      "$requestid" :{
        ".read" : "data.child('name').val() == auth.token.name",
      }
    }
  }
}
</code>
Unfortunately that doesnt work for me. I even tried this for the sake of learning
<code>{
  "rules": {
    "lauri_laurela" :{
      "$requestid" :{
        ".read" : "data.child('name').exists()",
      }
    }
  }
}
</code>
or even
<code>{
  "rules": {
    "lauri_laurela" :{
      "$requestid" :{
        ".read" : true,
      }
    }
  }
}
</code>
how ever this does work
<code>{
  "rules": {
    "lauri_laurela" :{
       ".read" : true,
    }
  }
}
</code>
Comment: Why don't you use the user UID instead of the name?
Comment: I would suggest to use the UID right away. Personally I think it's a lot easyer to work with in the security rules and there are a lot more examples using the uid
Comment: Also please include the code you are using to test these rules.
Comment: Im planning to make the system more secure later on by making that change Andre. But right now my problem is that I cant even make the rule hirearchy work.
Comment: I added 2 more rule codes in the question. The problem is that for some reason my wildcard token doesnt work, but I need help figuring out why.
Comment: @TinoTerävä the are something wrong with you code. Most probably, you are trying to query `lauri_laurela` branch instead of reading separate requests
Comment: Without seeing the code you are using to test this I don't think anyone can help you.
Comment: Oh you guys are talking about the Java code I wrote my program with? Yeah the problem might be there. If that can be the case, that info already helped me thanks.
Comment: Yes that code. A common problem is the code not matching the rules (I locked the front door (your rules) but I can't open it (You are trying the back door (your code) ) )
Answer: auth.token.name only works if name is set. So make sure you have your users have their name saved in their firebase auth profile. You do this using the below code.
<code> FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
    .setDisplayName("User name")
    .build();

user.updateProfile(profileUpdates)
    .addOnCompleteListener(new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull Task<Void> task) {
            if (task.isSuccessful()) {
                Log.d(TAG, "User profile updated. Now security rules work");
            }
        }
    });
</code>
To make sure the user has their name saved, you can change your security rules to
<code>"auth.token.name!==null && data.child('name').val() == auth.token.name"
</code>
or
<code>"auth.token.name!=="" && data.child('name').val() == auth.token.name"
</code>
Not sure which one works! hope this will help you.


Why a Deep Belief Network has connection that points to the input layer?

Question: Supposing to have a 3-layer DBN. I don't understand the specific reason for which the connections between the top two layers are undirected and the connections between all other layers are directed. Moreover, the arrows, representing the weights, points toward the layer that is closest to the data.
What is the explanation of having such both directed and undirected structure?
Answer: It has to do with the construction of DBN. You get a DBN by stacking RBM each on the top of the other and learning the new one with the visible input taken as the hidden features of the previous one.
This changes the nature of the graphical model : while the top 2 layers are still a RBM, all the structure underneath becomes a deep sigmoid network (a directed model).
These explanations can be found in Hinton's Coursera Lecture 14.1.


Modify an installed docker container

Question: I am using a Synology KMU NAS. On that NAS I have installed the GitLab Docker container that seems to have a bug. That bug causes the Software to refuse to send administrative e-mails without authentication. There is an environment variable SMTP_AUTHENTICATION that is passed to GitLab but it seems the non-authenticated configuration (supported by omnibus-gitlab according to the maintainer) is not passed correctly and falls back to "Login" instead.
Since our central IT service provides an un-authenticated SMTP server only (at least for non-personal use), I need to take care of the problem until Synology (maybe) fixes the problem in the future.
My idea is to modify the docker container so it passes the proper options to GitLab. I guess the error is trivial. However I have never used Docker containers before.
Is there a way to modify the docker container? What do I need to do?
Answer: You can create your own container that depends on the container you want to modify. I once did this with a mariadb container that wouldn't start a galera cluster because a binary that was needed for a test was in the wrong place in the container.
To create your own container, you only need a few steps. I ran this on the host where I wanted to start the container, not sure if this works on your NAS:

Create an empty directory and change into it
Create a file called Dockerfile inside that directory
FROM kolla/ubuntu-binary-mariadb:queens
COPY resolveip /usr/sbin/resolveip
CMD ["dumb-init", "--single-child", "--", "kolla_start"]

(FROM: The image you want to inherit from; COPY The modified files you want to copy into the image; CMD the start command of the original image. You can find it easily using docker inspect CONTAINER.)
To copy a file out of the container to modify it you can use: $ docker cp CONTAINER:/path/to/file .
Build the container:
docker build --tag=kolla/ubuntu-binary-mariadb:queens .

I needed to keep the original name and tag because the image was provisioned along with others. Since the newly created image was available local, and was newer than the images on the docker repository it was used during deployment automatically. If you don't need this you can give it your own name and just start a container from that image.

Modify an installed docker container


Probability Table

Question: For the following joint distribution of $X$ and $Y$, find the marginal probability $Pr(Y=2)$ , if $X$ and $Y$ are mutually independent. In the table below, blanks represent unknown probabilities that have to be determined should the value be required in the calculations.

I suspect I might have to solve some complicated linear system of equations, but I hope to find easier solutions.
Comment: Not sure this is clear.  Do the blanks mean the probability is $0$?  If so, $X,Y$ are clearly not independent as $X=1$ implies that $Y\neq 0$ yet, without knowledge of $X$, there is a positive probability that $Y=0$.  Also, the table seems incomplete...from the available data $\sum_n P(Y=n)<1$.
Comment: the blanks are unknown probabilities that have to be figured out should we require the value
Comment: That is entirely unclear from what you wrote.  Please edit your post for clarity.
Comment: To your question;  I expect it really is just a matter of writing out the system of equations.  Not sure they are all linear though.
Answer: Guide:
We know the value of $P(X=1, Y=3)$ and $P(X=2, Y=3)$.
From there, you should be able to deduce the value of $P(X=2,Y=2)$ since we know $P(X=1, Y=2)$.
Comment: I saw it ... Thanks a lot for the insight!

Probability Table


How can I invalidate the entire cache when saving menu item?

Question: I use the Simplify Menu module. Since changes in the menu are not applied, I would like to clear the entire cache.
Unfortunately the following code does not work
function MODULE_menu_link_content_update(Drupal\Core\Entity\EntityInterface $entity)
{
        if ($entity->menu_name->value === 'main') {
            \Drupal::cache()->invalidateAll();
        }
}

does anyone have an idea?
Comment: thanks! but not really. the hook MODULE_menu_link_content_update does not seem to be called when a menu item is updated.
Comment: Does this answer your question? [How do you clear menu caches programmatically?](https://drupal.stackexchange.com/questions/246450/how-do-you-clear-menu-caches-programmatically)
Answer: The Simplify Menu module has the problem that it doesn't transport cache metadata and a code like \Drupal::cache()->invalidateAll() doesn't exist.
You can add the most important cache tag to the Twig template yourself because you know the menu name:
{{ {'#cache': {'tags': ['config:system.menu.main']}} }}

Then changes in the main menu configuration will trigger a cache invalidation of the template automatically.
After you've added the cache tag to the Twig template it's possible to use it for menu content as well. The hook mentioned in the question can target it like this:
\Drupal::service('cache_tags.invalidator')->invalidateTags(['config:system.menu.main']);

This cache tag is the most important one and you will see a much better cache handling. However, there is a lot more cache metadata in menus, for example cache contexts for access handling, so this module should be used only for really simple menus.
Background info
For arrays Twig {{ }} is the same as PHP render(), which bubbles up metadata in contrast to renderPlain(). You use render() in the theming level (templates and preprocess hooks) when there is a page render stack (Drupal term render context not to be confused with cache context). Bubbleable metadata is #cache and #attached in a render array.
For example the core Twig function
{{ attach_library('core/drupal.dialog.ajax') }}

runs PHP:
  public function attachLibrary($library) {
    assert(is_string($library), 'Argument must be a string.');

    // Use Renderer::render() on a temporary render array to get additional
    // bubbleable metadata on the render stack.
    $template_attached = ['#attached' => ['library' => [$library]]];
    $this->renderer->render($template_attached);
  }

and could be replaced in Twig with the same result:
{{ {'#attached': {'library': ['core/drupal.dialog.ajax']}} }}

For #cache metadata you have to use the second method as there is no specific Twig function in core. Or the contrib module could bubble up the cache tag already when preparing the menu tree because Twig functions are always in a render stack.
Comment: `{{ {'#cache': {'tags': ['config:system.menu.main']}} }}`- wow thats neat, did not know you can create a render array only for caches on the fly in Twig, without preprocessing. So you basically can add any arbitrary cache tag or cache context inline in any Twig template and it will bubble upwards?
Comment: Yes, there are also Twig extensions just bubbling up metadata because Twig templates are always rendered inside of a cache context. For example core TwigExtension::attachLibrary.
Comment: Wow, so simple. I'm a bit surprised that I can add the cache tag in the Twig template. But that's great.
Answer: \Drupal::cache()->invalidateAll() does not invalidate the content of all the cache bins; it just invalidates the content of the cache.default bin.
The Workspaces module uses workspaces_menu_link_content_update() to invalidate the menu cache. I would use similar code.
function mymodule_menu_link_content_update(EntityInterface $entity) {
  if ($entity->getMenuName() === 'main') {
    $cache_tags = Cache::buildTags('config:system.menu', ['main'], '.');
    \Drupal::service('cache_tags.invalidator')->invalidateTags($cache_tags);
  }
}

Comment: This is the second part of my answer. This hook only works after you've added the tag to the twig template. I've only included the hook because it was mentioned in the question. I'm not sure this hook is even necessary, there is already a lot of invalidating happening when updating menus and this specific workspace code would target our template if it is tagged properly as well.
Comment: Your answer does not say that the *Workspaces* module uses `hook_ENTITY_TYPE_update()` to clear the cache. It also says that *code like `\Drupal::cache()->invalidateAll()` doesn't exist* without saying what exactly it would do. (Yes, it is perfectly correct code, but it does not do what the OP probably thinks it does.)


Got "Boolean" expected "LongInt" pascal

Question: I get this error on my insertion sort algorithm:

insertionsort.lpr(19,17) Error: Incompatible types: got "Boolean" expected "LongInt"

Here's the line 19 of my code
 while j > 0 and A[j]>key do

I have tried googling all over the internet but i couldn't find any syntax errors or anything.
Here's the full code if it helps :
program instert;
uses crt;
const
  N = 5;
var
   i:integer;
   j:integer;
   key:integer;
   A : Array[1..N] of Integer;

procedure insertionsort;
  begin
  for i := 2 to N  do
    begin
    key := A[1];
    j:= i - 1;
        while j > 0 and A[j]>key do
        begin
          A[j+1] := A[j] ;
          j := j-1;
        end;
    A[j+1] := key ;
   end;
 end;

begin
  A[1]:= 9;
  A[2]:= 6;
  A[3]:= 7;
  A[4]:= 1;
  A[5]:= 2;
  insertionsort;
end.

I also get the same error on the bubble sort algorithm i did. Here's the error line

bubblesort.lpr(26,14) Error: Incompatible types: got "Boolean" expected "LongInt"

Here's line 26 of my algorithm:
 until flag = false or N = 1 ;

Here's the full code:
program bubblesort;
uses crt;

var
  flag:boolean;
  count:integer;
  temp:integer;
  N:integer;
  A : Array[1..N] of Integer;

procedure bubblesort ;
begin
  Repeat
    flag:=false;
    for count:=1 to (N-1)  do
    begin
    if A[count] > A[count + 1] then
       begin
       temp := A[count];
       A[count] := A[count + 1];
       A[count] := temp;
       flag := true;
       end;
    end;
    N := N - 1;
  until flag = false or N = 1 ;
end;

begin
  A[1]:= 9;
  A[2]:= 6;
  A[3]:= 7;
  A[4]:= 1;
  A[5]:= 2;
  N := 5;
  bubblesort;
end.

Comment: It's a precedence issue. `>` has lower precedence than `and`, so use parentheses: `while (j > 0) and (A[j]>key) do`. Similarly, you need `until (flag = false) or (N = 1) ;` (or just `until not flag or (N = 1) ;`)
Comment: @lurker Somebody is almost as bad as I am, concerning answering in comments ;)
Comment: See, for example, [Pascal Operators Precendence - TutorialsPoint](http://www.tutorialspoint.com/pascal/pascal_operators_precedence.htm)
Comment: @lurker thanks for that now the programs working
Comment: @CodesInChaos yeah it's a pathology I suffer from. ;)
Comment: @lurker: want to write it up as an answer? It's quite a trap, especially if you come from another language.
Comment: @Jongware i can do so later today. I'm smart phone only access for several hours and its difficult to do a full answer from here.
Answer: In Pascal, boolean operators and and or have higher precedence than the comparison operators >, =, etc. So in the expression:
while j > 0 and A[j] > key do

Given that and has higher precedence, Pascal sees this as:
while (j > (0 and A[j])) > key do

0 and A[j] are evaluated as a bitwise and (since the arguments are integers) resulting in an integer. Then the comparison, j > (0 and A[j]) is evaluated as a boolean result, leaving a check of that with > key, which is boolean > longint. You then get the error that a longint is expected instead of the boolean for the arithmetic comparison.
The way to fix it is to parenthesize:
while (j > 0) and (A[j] > key) do ...

The same issue applies with this statement:
until flag = false or N = 1 ;

which yields an error because or is higher precedence than =. So you can parenthesize:
until (flag = false) or (N = 1);

Or, more canonical for booleans:
until not flag or (N = 1);    // NOTE: 'not' is higher precedence than 'or'

When in doubt about the precedence of operators, parenthesizing is a good idea, as it removes the doubt about what order operations are going to occur.

Got "Boolean" expected "LongInt" pascal


Loose compression for all images directly from Drupal

Question: I need to do image loose-compressing usually done with GIMP/TinyPNG/GPI, but just inside Drupal, but also For all images, in a single process or several sporadic processes (say, for each content type).
This could save much time instead of download, compress, reupload, etc.
Is there a way to loose-compress all images in the application so that webpages containing them load faster?
If you don't know such a tool but does know a way to show all nodes that has images, please comment naming such a tool, so it could at least help in the alternative of downloading and manually loosely-compressing each image before re uploading it.
Comment: I think the question is about "lossy compression" for PNGs. is that right?
Comment: I use `pngquant` to do lossy compression. It is possible to run that process on multiple files at once. It is already a part of libgd so perhaps it is already supported in image styles in Drupal?
Answer: You're looking for this but in D8 - https://www.drupal.org/project/imageapi_optimize. You can still use the tools to do it manually.
PNG - Use https://pngquant.org/ first with these settings <code>--speed=1 --quality=90-99 --force --ext .png</code> and then https://github.com/subzey/zopfli-png
JPG - https://github.com/mozilla/mozjpeg and then https://stackoverflow.com/questions/5579183/jpegtran-optimize-without-changing-filename
EDIT: This new D8 project just appeared https://www.drupal.org/project/file_processor
Answer: Drupal core has a setting out of the box that allows you to compress all images on upload. See admin/config/media/image-toolkit.
My image compression plan is to use that setting of 75% for basic compression.
On top of this I'll install the Image effects module and use the "Strip" effect to remove metadata and the and "Interlace" option to make my jpeg's progressive and significantly increase perceived speed.
The Image effects module uses the GD2 image kit that core already uses, so by using it I'm not required to worry about installing any other server tools or rely on a 3rd party API.


Como definir os tipos de dados das colunas de uma JTable igual a do banco de dados MySql?

Question: Criei uma interface gráfica no Netbeans onde inseri uma JTable dentro de um FORM JFrame. Eu tenho um Banco de dados MySql cujas colunas são:
Id: Integer
Nome: String
Ativo: Boolean
Porém quando utilizo: jTable.setModel(DbUtils.resultSetToTableModel()) (método da biblioteca RS2XML.jar), a JTable é preenchida toda como String.
Como faço para que a JTable seja preenchida com os tipos de dados corretos igual ao banco de dados (Integer, String e Boolean)?
Answer: Utiliza o parse.
Por exemplo, você está com uma variável do tipo String mas no banco é int, você coloca:
int x = Integer.parseInt(variavel String);
assim você terá uma variável do mesmo tipo que o seu banco.
Comment: Não tem como fazer assim, porque o método resultsetToTableModel() já joga os valores direto na tabela.


Existence of a functional on $L^\infty$ that vanish on C(X)

Question: So I want to prove the existence of a functional on $L^\infty(0,1)$ that vanish on C(X). I looked up and there is one example, but not much explanation. So we consider the continuous functions that have equal limits when x tends to 0 and 1. And take the functional that maps a function to the difference of two limits. And then extend it to the whole space.
However, it only vanishes on the set of continuous functions that have equal limits. Can you help me explain why does it vanishes on all continuous ones? I think this is wrong, do you know other examples?
Comment: $C(X)$ means $C(0,1)\cap L^\infty (0,1)$?
Comment: You can use the second "important consequence"  [here](https://en.wikipedia.org/wiki/Hahn%E2%80%93Banach_theorem#Important_consequences) for existence.
Comment: Yes weiyi sun. It is
Comment: Do you know any text that Ican read the proof of this great consequence?
Comment: Using the notation of the link: Set $M=z+U$ and $f(u+\alpha z)=\alpha$ for $u$ in $M$, $\alpha\in \Bbb R$. This is a non-zero linear functional on $M$. Extend using HB.
Answer: Let $V$ be the span of $C[0,1]$ and some particular member of $L^\infty(0,1)$ that is not in  $C[0,1]$,
e.g. $I_{[0,1/2]}$, the indicator function of $[0, 1/2]$.  Define a bounded linear functional $\varphi$ on
$V$ by $\varphi(f + t I_{[0,1/2]}) = t$.  Then extend to $L^\infty(0,1)$ by Hahn-Banach.
Comment: Why is this functional $\varphi$ continuous?
Comment: I try to show this in the following way: $|\varphi(f+tI_{[0,1/2]})|\leq  \dfrac{\|f+tI_{[0,1/2]}\|}{\|f/t+I_{[0,1/2]}\|}$ and shows that $\|f/t+I_{[0,1/2]}\|>1/3$ for any $t\neq 0$ and any continuous $f$.
Comment: If $W$ is a closed subspace of Banach space $X$, and $u \notin W$, let $d > 0$ be the distance from $u$ to $W$.  Then the linear functional on $\text{span}(u,W)$ defined by $\varphi(tu + w) = t$ for $w \in W$ has norm at most $1/d$ because $ \|t u + w\| \ge d |t|$, i.e. $|\varphi(tu+w)| = |t| \le d^{-1} \|tu+w\|$.
Comment: Nice, so by choosing $w_0\in W$ s.t $d=\|w_0-u\|$ and putting $g=d^{-1}(u-w_0)$, we have that $\|g\|=d^{-1}d=1$ and $\varphi(g)=d^{-1}$. As a consequence $\|\varphi\|=d^{-1}$.  Am I correct?
Comment: Not quite.  In general there may not be such a $w_0$, just a sequence such $w_n$ such that $\|w_n - u\| \to d$.
Comment: A last question: in the above question $w_0\equiv 1/2$ is a minimizer   which realize $1/2=d=(I_{[0,1/2]},C([0,1])$. Is this ok? I  am using  a variiation of this answer

https://math.stackexchange.com/questions/221069/why-are-continuous-functions-not-dense-in-l-infty.   To conclude that $\|f-I_{[0,1/2]} \| \geq 1/2$.


Angular lazy loaded module components with the same name

Question: I have an Agular app with several lazy-loaded modules. These modules each contain some different components which are logically similar but differ in content. E.g. each module may have its own "home" component.
Is it okay to name these components exactly the same?
To me, it seems overly verbose to prefix each with the module name. Especially when the names start to get long, and considering I would like to maintain the balance between concision and readability.
Functionally this doesn't appear to be a problem. Take the following app as an example. It has 2 lazy loaded modules each containing 2 components with the same name as the components in the other module. One component is loaded by the module's route and the other is loaded via its selector in the template of the first component.
https://stackblitz.com/edit/angular-comp-name-test
I understand that this question may be considered as opinion-based but are there any technical reasons why this shouldn't be done? (I am also interested in opinions if someone wants to dm me)
Comment: what is the question?
Comment: Are there any good reasons why you should not have components with the exact same name in different lazy-loaded modules?
Comment: I don't think there is any technical reason not to do so, you can even have components with the same name in one module
Answer: Technically there is no issue, you can use the same name. Like I have many modules having dashboard as each respective module's component. As long as you properly import it, its fine.
But for larger apps sometimes when auto importing it can import pointing to different 1 then the one required. This happened with me once, I had add and list component in 2 different so while auto importing the url was pointing to the wrong one.
So for just the sake of clarity its nice if you keep different name like prefixing it with something so you know it is for this module etc otherwise we can't say it is or is not "good or bad practice".
Answer: I have been working on a project with 5 lazy loaded modules having millions of components in their sub folder with same components names.
The good reason or the problem faced by me in while in the development only is while importing the components the auto import does some time imports component from different module and that way I have been facing confusion and getting development done some time with wrong components.
But this has happened 2 times after then I was very safe while importing components
Answer: Hey you can use import aliases  in the tsconfig.json paths
"paths": {
    "@modules": "app/test-mod(?:\.\d+)?"
},

You can use regex to match the file end names so that if you have more than one folder you can just name them like file1, file2, file3 and son on the match them in the import using
import('@modules/innerfolder/mymodule.ts')

Comment: Thanks for the answer but it doesn't really address the question I was asking. Sorry if it wasn't clear. I made a little edit that maybe clarifies it.


How do you determine what to define when you are writing a math research paper?

Question: I find that often researchers in math do not define every piece of notation that they use, however, I am not sure what criteria they use to deem that a definition should be left out, or should be included.
For example, in Terence Tao's paper, he did not provide a definition of the gamma function. But the gamma function is standard, so there shouldn't be any problems.
In these other papers on optimization, for example, the researchers uniformly do not define what they mean by $\Omega, \omega, O$, or $o$ and assume that they are well known (even though I can think of conflicting definitions in CS versus math, see chapter 1 of CLRS versus Luenberger and Ye's optimization text)
I am sure there are many other examples. Now I am beginning to learn how to communicate in math, but I am not sure what I should define, what I should leave out. And if I define everything, it soon becomes a rabbit hole, but if I don't define, I get yelled at for being fast and loose and imprecise.
How do you determine what to define?
Comment: This may be better suited to academia.stackexchange.com
Comment: If a notation is well used in the fields literature, leave it out. If _you_ feel it is required, put it in. I'm sure a referee will make a suggestion if they feel like you've left something out.
Answer: You can look at similar papers (to the one you're writing) in your particular field, and you can emulate what others have done. I am assuming you'd be referencing other papers for example, so you can take a clue from these, regarding what is assumed well known or standard in that field.
You can also think of what you believe is well known or could be easily looked up by a reader and decide whether it is worth leaving something out or if it would be of benefit to the reader or clarity of exposition to include it.
Referees will help here too as they may suggest exclusions or additions.


How is an overthrow represented on the wagonwheel?

Question: The "wagonwheel" is a diagram used to show where a batsman's shots were played, colourcoded for the number of runs scored from that shot.
An overthrow occurs when a fielding player attempts to return the ball to the stumps, either directly or indirectly, but through some error causes the ball to be sent to another area of the field instead.
Suppose a batsman plays a shot to one side of the field, scoring runs from it. An overthrow to the other side then allows additional runs.
How would this shot and overthrow be represented on the wagonwheel? How are the runs coded?
Answer: This is two wagon wheel from ESPN Cricinfo showing overthrow.
What I did was to look for overthrow causing 7 runs in an ashes 06/07 Adelaide test Australia 2nd inning by Michael Clarke Link to Youtube Video and search the same match in cricinfo for wagon wheel.
Michael Clarke wagon wheel:

The white line in wagon wheel is overthrow 7 runs because Clarke has scored only 10 runs against Flintoff. Among which 1sx1 and 2sx1 and no 4s or 6s.
Andrew Flintoff wagon wheel:

Which clearly shows 7 runs in wagon wheel as no fours or six have been scored against him by Clarke.
Answer: It would be represented as the first shot the batsmen has played even though the throw has been missed and u get runs through it. This is because the first shot triggered the whole event this makes the wagon wheel to show that the runs have been scored by the batsmen with the first shot. This is my personal view
Comment: Is this from a document that states how an organiser will actually record an overthrow, or just what you think should happen? Please refer to appropriate and credible sources.


Shape TierListView Scrolling Problem

Question: I have a tierview that uses a shape xml file for the background.
Drawable greyGradient =
    this.getResources().getDrawable(R.drawable.grey_gradient);
final TierListView tierView = (TierListView) findViewById(R.id.content_list);
tierView.setBackgroundDrawable(greyGradient);

My problem is that whenever I scroll the list my Stroke around the edges of the TierListView disappears. Actually the entire xml file stops working until the scrolling stops. When I release the touch the stroke returns. How do I keep the stroke and just cause the list items to scroll within it?
<shape
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:shape="rectangle" >
<corners
   android:topLeftRadius="5dip"
   android:topRightRadius="5dip"
   android:bottomLeftRadius="5dip"
   android:bottomRightRadius="5dip" />
<gradient
   android:angle="90"
   android:endColor="#000000"
   android:startColor="#3d3d3d"
   android:type="linear" />
<size
   android:scaleType="center" />
<stroke
   android:width="2dip"
   android:color="#d6d7d6" />
</shape>

Answer: Ok. So I fixed the problem by changing android:layout_weight="1" to 5.  I don't know why this would make a difference (the documentation is bare on layout_weight) but it did.

Shape TierListView Scrolling Problem


Assigning converted `Base64` values in Javascript in Vuejs method

Question: I'm trying to retrieve file information from input field of type="file" in my Vuejs application. I'm having a render function which renders the input fields something like this and calls a function on input, code as below:
input: (event) => {
    var reader = new FileReader()
    reader.readAsDataURL(event.target.files[0])
    let baseFile = ''
    reader.onload = function () {
        baseFile = reader.result
        console.log(baseFile)
    };
    console.log(baseFile)
    const docs = {
        name: event.target.files[0].name,
        size: event.target.files[0].size,
        lastModifiedDate: event.target.files[0].lastModifiedDate,
        base64: baseFile
    }
    this.$emit('input', docs)
}

When I run this function console.log inside my reader.onload function gives me converted files but when I do console outside of it, the value is just an empty string. How I can I retrieve and assign to my const docs variable. Help me out with this. Thanks.
Comment: I guess  you should assign var inside callback of `reader.onload`
Answer: I recommend to put the rest of code inside the block of that function after changing it to an arrow function as follows :
input: (event) => {
  var reader = new FileReader()
  reader.readAsDataURL(event.target.files[0])
  let baseFile = ''
  reader.onload = () => {// <------ use arrow function
    baseFile = reader.result
    const docs = {
      name: event.target.files[0].name,
      size: event.target.files[0].size,
      lastModifiedDate: event.target.files[0].lastModifiedDate,
      base64: baseFile
    }
    this.$emit('input', docs)
  };

}


Begging the question in a proof

Question: I've found in my math textbook a proof of De Morgan's law but I think it's begging the question. Here's the proof:
$$ \begin{aligned} x\in(A\cap B)^c&\iff x\notin A\cap B \\
&\iff x\notin A \text{ or } x\notin B \\
&\iff x\in A^c \text{ or } x\in B^c \\
&\iff x\in A^c\cup B^c
\end{aligned}$$
Thus: $(A\cap B)^c=A^c\cup B^c$ Am I right? If not, why?
Comment: Not sure what exactly is your question. Are you asking whether the proof in your math textbook is correct? What makes you think that it is *not* correct?
Comment: @tahafen: It is using the logical version, not the set-theoretic one.
Comment: No, it is not begging the question (it is not assuming what you are trying to prove). The $\Rightarrow$ path shows that $(A\cap B)^c$ is contained in $A^c\cup B^c$, and the $\Leftarrow$ path shows that $A^c\cup B^c$ is contained in $(A\cap B)^c$, thus proving equality.
Comment: @Stinking Bishop I think it's incorrect because it's assuming what it has to be proved. How can he pass from  x∉A∩B  to x∉A or x∉B without De Morgan's law.
Comment: How can he turn the "and" in the first into "or"
Comment: True: in proving DeMorgan's laws for sets, they use ... DeMorgan's laws in logic. ($\lnot(p\land q)\Leftrightarrow (\lnot p \lor \lnot q)$). These can be proven (e.g. truth tables - a finite problem altogether).
Answer: The given proof hides an application of De Morgan's law for propositional logic. Let me write it out in full, expanding "$x \not\in X$" to "$\text{not } x \in X$":
$$ \begin{align*}
 x\in(A\cap B)^c&\iff \text{not} (x\in A\cap B )\\
&\iff \text{not} (x\in A \text{ and } x\in B) \\
&\iff (\text{not } x\in A) \text{ or } (\text{not } x\in B) \tag*{$(*)$}\\
&\iff x\in A^c \text{ or } x\in B^c \\
&\iff x\in A^c\cup B^c
\end{align*}$$
You can use truth tables to check the rule used in step $(*)$.

Begging the question in a proof