Como ler uma lista de objetos serializados salvos em um arquivo em java?

Question: Estava querendo trabalhar com serialização em arquivos em java e li este tutorial sobre como escrever o objeto no arquivo e este outro sobre o como ler o objeto do arquivo
Então criei a seguinte classe que salva o objeto Adreess no arquivo "arquivo.ser":
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import wl.revisao.write.Address;

    public class WriteObject {

        public void serializeAddressJDK7(Address address) {

            try (ObjectOutputStream oos
                    = new ObjectOutputStream(new FileOutputStream("arquivo.ser",true))) {

                oos.writeObject(address);
                System.out.println("Done");

            } catch (Exception ex) {
                ex.printStackTrace();
            }

        }

         public Address deserialzeAddressJDK7(String filename) {

            Address address = null;

            try (ObjectInputStream ois
                    = new ObjectInputStream(new FileInputStream(filename))) {

                address = (Address) ois.readObject();

            } catch (Exception ex) {
                ex.printStackTrace();
            }

            return address;

        }

//Metodo indicado pelo amigo Isac com a resposta abaixo

public List<Address> recuperarTodos() {
        List<Address> addresses = new ArrayList<Address>(); //lista de Address

        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("arquivo.res"))) {

            while (true) {
                Address address = new Address();

                address = (Address) ois.readObject(); //le outro objeto e adicionar à lista
                addresses.add(address); //le outro objeto e adicionar à lista
            }

        } catch (EOFException ex) {

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return addresses;

    }

}

Aqui esta a minha classe principal:
public class Main {

    public static void main(String args[]) {

        WriteObject obj = new WriteObject();

        Address address = new Address();
        address.setStreet("Wall street");
        address.setCountry("United States Of America");

        Address address2 = new Address();
        address2.setStreet("Avenida Brasil");
        address2.setCountry("Brasil");

        obj.serializeAddressJDK7(address);
        obj.serializeAddressJDK7(address2);

//   obj.deserialzeAddressJDK7("arquivo.ser");
       System.out.println(obj.recuperarTodos());
    }
}

O outro metodo deserialzeAddressJDK7 devolve um objeto Address  lido do arquivo.
Ok tudo esta perfeito!!
O problema é quando eu salvo mais de um objeto no arquivo "arquivo.ser", pois
o metodo foi construido para ler apenas um objeto salvo no arquivo;

Como faço para devolver uma lista de objetos salvos no tal arquivo?

Por ultimo a famigerada classe Address:
public class Address implements Serializable {

    private static final long serialVersionUID = 1L;

    String street;
    String country;

    public Address() {
    }

    public void setStreet(String street) {
        this.street = street;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getStreet() {
        return this.street;
    }

    public String getCountry() {
        return this.country;
    }

    @Override
    public String toString() {
        return new StringBuffer(" Street : ")
                .append(this.street).append(" Country : ")
                .append(this.country).toString();
    }

}

ps: estou usando o append como true, pois como sabemos quero acumular os objetos no arquivo.ser , e caso eu o omitisse, isso não seria possivel!
Caso exista outra forma de salvar os objetos no arquivos sem o uso do append , e seja possível listar esses arquivos, ficaria feliz em conhecer.
Usei o Booleano append commo true , porque foi a unica alternativa que tive... não sabia como rescrever no arquivo sem apagar os objetos ja existentes previamente!
Comment: @AndréLuizdeGusmão Valeu cara vou dar um olhada!
Answer: Para ler uma lista de objetos no arquivo tem de usar um laço/ciclo na parte da leitura e ir adicionando os objetos lidos a uma lista:
List<Address> addresses = new ArrayList<Address>(); //lista de Address

try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filename))) {

    while(true){
        addresses.add((Address) ois.readObject()); //le outro objeto e adicionar à lista
    }

} catch (EOFException ex){
    //fim da leitura aqui
} catch (Exception ex) {
    ex.printStackTrace();
}

Note que laço foi marcado como infinito e o fim da leitura foi capturado com EOFException o que pode parecer estranho. Na verdade o null é um valor válido de se obter lendo um objeto e por isso não é possível de testar o fim comparando com nulo mas apenas capturando exceções.
Podemos questionar a decisão do Java de implementar o fim do ficheiro por meio de exceções mas é como foi implementado para o ObjectInputStream e readObject.
Deixo aqui a nota de que escrevendo com append a true não irá conseguir desserializar múltiplos objetos!
Posto isto mostro um exemplo de como utilizar esta lógica sem o append true, tentando-a deixar o mais parecida à que tinha:
public class WriteObject {

    //guarda a stream de saída aqui considerando N escritas seguidas pois não tem
    //append e apenas no fim uma unica leitura para os objetos todos
    private ObjectOutputStream oos;

    public void serializeAddressJDK7(Address address) {

        try {
            if (oos == null){ //se é o primeiro objeto a guardar inicia a stream
                oos = new ObjectOutputStream(new FileOutputStream("arquivo.ser"));
            }

            oos.writeObject(address);
            System.out.println("Done");

        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }

    public List<Address> recuperarTodos(String filename) {

        try {
            oos.close(); //tenta fechar a stream de saída
        } catch (IOException e) {
            e.printStackTrace();
        }

        List<Address> addresses = new ArrayList<Address>();

        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filename))) {
            while (true) {
                addresses.add((Address) ois.readObject());
            }
        } catch (EOFException ex) {
            // fim da leitura aqui
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return addresses;
    }

}

Testando agora no main:
public static void main(String[] args) {
    ...
    obj.serializeAddressJDK7(address);
    obj.serializeAddressJDK7(address2);

    obj.recuperarTodos("arquivo.ser").stream().forEach(x-> System.out.println(x));

Saida:
Comment: Ele só consegue retornar a Lista quando o arquivo tem apenas um objeto! Aqui esta o erro :java.io.StreamCorruptedException: invalid type code: AC
 at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1381)
 at java.io.ObjectInputStream.readObject(ObjectInputStream.java:373)
 at wl.revisao.write2.WriteObject.recuperarTodos(WriteObject.java:58)
 at wl.revisao.write2.Main.main(Main.java:28)
Comment: @PenaPintada Assumo que o método `recuperarTodos` seja o que tem o código que eu aqui coloquei. Qual a sua assinatura ? E qual o caminho que está a ser passado/utilizado nesse método ?
Comment: Vou colocar ele no codigo acima
Comment: @PenaPintada O problema tem a ver com o `append` `true`, que basicamente não funciona com `writeObject` e `ReadObject`. Tem até uma pergunta relacionada no [SOen](https://stackoverflow.com/questions/16473856/write-and-read-multiple-objects-to-file) com esse problema do `append`. E já consegui aqui testar sem o `append` e funciona mas é preciso dar outra lógica ao programa/classe `WriteObject`. Por isso estou mais tentado a remover a minha resposta do que alterar a lógica da que está na pergunta
Comment: Isso mesmo estou usando o append, obrigado pelo apoio.
Comment: @PenaPintada Com `append` não funciona para deserializar múltiplos objetos, dá para testar até de uma forma direta executando `obj.deserialzeAddressJDK7("arquivo.ser");` como estava no seu main 2 vezes seguidas, excluindo até todo o código que eu fiz, que aparece sempre o primeiro. E se testar dentro do método `deserialzeAddressJDK7` duas leituras seguidas com `address = (Address) ois.readObject();` tem o mesmo erro.
Comment: Obrigado ai cara! Grande resposta. Agora nasce outra questão  que vai ficar para a próxima! Espero contar com voce...
Comment: @PenaPintada De nada. Ficarei atento! Tudo de bom para si.


TypeError: encode() argument 'encoding' must be str, not int

Question: I'm trying to control my Arduino in python with pyserial and get this error:
TypeError: encode() argument 'encoding' must be str, not int
I'm really new to coding so I'm a little lost.
What I'm trying to do is that I want to first choose "function" nr 1 which is "swipe" and I want to give it three arguments. First, it sais that "command" only takes two arguments at most so I tried to use 2/3 arguments just to make it work but now it complains that the arguments must be str...
Anyone who can help me make it work??
<code>import time
import serial
strComPort = '/dev/ttyACM0'
strComBaud = 9600

cmdSerial = serial.Serial(strComPort, strComBaud)
time.sleep(2) #sec

while True:
    command= input("Enter command number in list: \n1: Swipe \n2: tap\n3: Double tap\n4: Press\n5: Drag\n6: Flick right\n7: Flick left")

    if (command == '1'):
        x = int(input("From which deg?: "))
        y = int(input("To which deg? :"))
        spd = int(input("Speed of swipe? :"))
        cmdSerial.write(command.encode(x, y, spd))
        time.sleep(1)

    if (command == '2'):
        cmdSerial.write(command.encode())
        time.sleep(1)

    if (command == '3'):
        cmdSerial.write(command.encode())
        time.sleep(1)

    elif (command == '4'):
        cmdSerial.write(command.encode())
        time.sleep(1)

    elif (command == '5'):
        x = int(input("From which deg?: "))
        y = int(input("To which deg? :"))
        cmdSerial.write(command.encode(x, y))
        time.sleep(1)

    elif (command == '6'):
        cmdSerial.write(command.encode())
        time.sleep(1)

    elif (command == '7'):
        cmdSerial.write(command.encode())
        time.sleep(1)

    elif (command == 'q'):
        print("Exiting...")
        break

    else:
        print("Only number between 1-6 or 'q' (exit)")
</code>
Answer: You get the error because you are trying to encode a string with an integer.
Here is the list of all the encode that you can use.


R function survfit(): give newdata reference values for factors with >2 levels?

Question: The goal is to plot separate survival curves for each level of a categorical variable in R, using a coxph model including the variable and a second categorical variable with >2 levels.
If the second categorical variable had had only 2 levels, it is possible to give the proportion of one level as the reference value. This is frowned upon by the R community, but done by default in some other statistical software.
An example using the mgus dataset:
library(survival)
mgustest <- mgus
mgustest$agecat <- cut(mgustest$age, breaks=quantile(mgustest$age))
    mgustest$albcat <- cut(mgustest$alb, breaks=quantile(mgustest$alb, na.rm=T))
mfit.refs <- data.frame("sex"=mean(mgustest$sex == "female"),
                        "albcat"=c('(1.8,3]','(3,3.2]','(3.2,3.5]','(3.5,5.1]'))
mfit <- coxph(Surv(futime, death) ~ sex + albcat, data=mgustest)
plot(survfit(mfit, newdata=mfit.refs), col=c("black","red","blue","green"))

The newdata data frame looks like this:
      sex    albcat
1 0.4190871   (1.8,3]
2 0.4190871   (3,3.2]
3 0.4190871 (3.2,3.5]
4 0.4190871 (3.5,5.1]

Assuming the model:
mfit2 <- coxph(Surv(futime, death) ~ agecat + albcat, data=mgustest)

How should I build the newdata data frame to be able to fit separate  survival curves for albcat levels with survfit (I only want four curves representing the albact levels)?
Thoughts: How do other statistical software produce these survival curves without specifying reference values for agecat? For example, how does SPSS do it?
Disclaimer: I agree that it makes little sense to assume that every individual in a sample has the sex 0.42, when the only occurring values are 0 and 1. Still, this assumption is common in other statistical software, and it is useful to be able to replicate models resulting from such assumptions in R. I have googled for a couple of hours about the matter, but could not find an answer about how to deal with categorical variables with >2 levels.
Edit:
I want to clarify based on the first comment. I do not want 4*4=16 survival curves like in this example:
mfit.refs2 <- data.frame(
"agecat"=c(rep('(34,55]', 8),rep('(55,64]',8),rep('(64,72]', 8),rep('(72,90]', 8)),
"albcat"=rep(c('(1.8,3]','(3,3.2]','(3.2,3.5]','(3.5,5.1]'), 4))
mfit2 <- coxph(Surv(futime, death) ~ agecat + albcat, data=mgustest)
plot(survfit(mfit2, newdata=mfit.refs2), col=c("black","red","blue","green"))

Comment: Why not just plot 2 curves, 1 for male & 1 for female?
Comment: The objective is to plot the albcat curves. Do you mean to plot the four albcat twice?
Answer: I found a solution that produces survival curves equivalent to the standard survival curves in SPSS (judged visually). In short, I had to pre-create the dummy variables from agecat and insert the dummy variables into the coxph() function instead of agecat. After that, you specify proportions for each dummy variable in the "newdata" data frame, like I did with sex in the example.
A solution that avoids the pre-creation step would be great if it is possible, but I was not able do it like that. Any refinements or alternative solutions would be appreciated.
Here is the code:
#create three dummy variables from agecat
out <- contrasts(mgustest$agecat)[as.numeric(mgustest$agecat),]
colnames(out) <- paste("agecat",colnames(out),sep="")
out <- apply(out,2, as.logical)
mgustest <- data.frame(mgustest, out)

names(mgustest) #variable names to use in mfit3
prop.table(table(mgustest$agecat)) #proportions to use as reference values

#coxph with three dummy variables instead of "agecat"
mfit3 <- coxph(Surv(futime, death) ~ agecat.55.64. + agecat.64.72. + agecat.72.90. + albcat,
               data=mgustest)
#newdata data frame specifying proportion for each of the dummy variables
mfit.refs3 <- data.frame("agecat.55.64."=prop.table(table(mgustest$agecat))[[2]],
                            "agecat.64.72."=prop.table(table(mgustest$agecat))[[3]],
                        "agecat.72.90."=prop.table(table(mgustest$agecat))[[4]],
                        "albcat"=c('(1.8,3]','(3,3.2]','(3.2,3.5]','(3.5,5.1]'))
#final plot
plot(survfit(mfit3, newdata=mfit.refs3), col=c("black","red","blue","green"))


Populate XML template-file from XPath Expressions?

Question: What would be the best way to populate (or generate) an XML template-file from a mapping of XPath expressions?
The requirements are that we will need to start with a template (since this might contain information not otherwise captured in the XPath expressions).
For example, a starting template might be:
<s11:Envelope xmlns:s11='http://schemas.xmlsoap.org/soap/envelope/'>
    <ns1:create xmlns:ns1='http://predic8.com/wsdl/material/ArticleService/1/'>

        <name>?XXX?</name>
        <description>?XXX?</description>
        <price xmlns:ns1='http://predic8.com/common/1/'>
          <amount>?999.99?</amount>
          <currency xmlns:ns1='http://predic8.com/common/1/'>???</currency>
        </price>
        <id xmlns:ns1='http://predic8.com/material/1/'>???</id>

    </ns1:create>
  </s11:Body>
</s11:Envelope>

Then we are supplied, something like:
expression: /create/article[1]/id                => 1
expression: /create/article[1]/description       => bar
expression: /create/article[1]/name[1]           => foo
expression: /create/article[1]/price[1]/amount   => 00.00
expression: /create/article[1]/price[1]/currency => USD
expression: /create/article[2]/id                => 2
expression: /create/article[2]/description       => some name
expression: /create/article[2]/name[1]           => some description
expression: /create/article[2]/price[1]/amount   => 00.01
expression: /create/article[2]/price[1]/currency => USD

We should then generate:
<ns1:create xmlns:ns1='http://predic8.com/wsdl/material/ArticleService/1/'>

        <name xmlns:ns1='http://predic8.com/material/1/'>foo</name>
        <description>bar</description>
        <price xmlns:ns1='http://predic8.com/common/1/'>
            <amount>00.00</amount>
            <currency xmlns:ns1='http://predic8.com/common/1/'>USD</currency>
        </price>
        <id xmlns:ns1='http://predic8.com/material/1/'>1</id>

        <name>some name</name>
        <description>some description</description>
        <price xmlns:ns1='http://predic8.com/common/2/'>
            <amount>00.01</amount>
            <currency xmlns:ns1='http://predic8.com/common/2/'>USD</currency>
        </price>
        <id xmlns:ns1='http://predic8.com/material/2/'>2</id>

</ns1:create>

I am implemented in Java, although I would prefer an XSLT-based solution if one is possible.
PS: This question is the reverse of another question I recently asked.
Comment: Do you want a solution in Java? or in XSLT? Your question suggests Java, but you have tagged the question as XSLT. Also note, that in your output document, you have a large number of pointless name-space declarations.
Comment: Actually, the XML shown above is one that is generated as part of my some libraries I'm using. It could be pointless, but it just shows that we need to consider namespaces and the like that also needs to be part of the final output. As for the solution: I would really prefer an XSLT solution, however, is such is not possible, I would then opt for a Java solution.
Comment: I see an inconsistency: Why some element names such as `id` and `description` aren't followed by `[1]` while the rest of the leaf nodes are followed by `[1]` ?
Comment: It is easier to manually create the wanted XML document than to create the set of population expressions -- I strongly recommend not implementing such processing at all. It is necessary to have a sound design so that any such "curiosities" are avoided.
Comment: @DimitreNovatchev It is only because, those elements can have potential multiple occurrences. If this is an issue, of course, we could make it all consistent, like the output shown in the linked question. (i.e. where all elements have [1], and those with multiple occurrences are then iterated, etc.)
Comment: Larry, As I already commented, such processing is totally unnecessary -- whoever creates the expression will need *less* time in creating the complete XML document.
Comment: @DimitreNovatchev I would agreed, the point is I'm actually working with an API that produces the expressions. So I don't really have any choice, I now need to formulate an appropriate XML message that corresponds with the expressions. Of course, if I were the one producing the expressions, then that would be a different story. But I kind of need to work with what is given... so if you could think about an efficient solution, it would be greatly appreciated!
Comment: Larry, would it be feasible to accept a 2-invocation solution? That means that you run one style-sheet with the XPATH information as input. Its output is a style-sheet, which you then run as the second invocation? If you can tolerate a two-step process, this may be the simplest solution.
Answer: This transformation creates from the "expressions" an XML document that has the structure of the wanted result -- it remains to transform this result into the final result:
<xsl:stylesheet version="2.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:xs="http://www.w3.org/2001/XMLSchema"
 xmlns:my="my:my">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:variable name="vPop" as="element()*">
    <item path="/create/article[1]/id">1</item>
    <item path="/create/article[1]/description">bar</item>
    <item path="/create/article[1]/name[1]">foo</item>
    <item path="/create/article[1]/price[1]/amount">00.00</item>
    <item path="/create/article[1]/price[1]/currency">USD</item>
    <item path="/create/article[1]/price[2]/amount">11.11</item>
    <item path="/create/article[1]/price[2]/currency">AUD</item>
    <item path="/create/article[2]/id">2</item>
    <item path="/create/article[2]/description">some name</item>
    <item path="/create/article[2]/name[1]">some description</item>
    <item path="/create/article[2]/price[1]/amount">00.01</item>
    <item path="/create/article[2]/price[1]/currency">USD</item>
 </xsl:variable>

 <xsl:template match="/">
  <xsl:sequence select="my:subTree($vPop/@path/concat(.,'/',string(..)))"/>
 </xsl:template>

 <xsl:function name="my:subTree" as="node()*">
  <xsl:param name="pPaths" as="xs:string*"/>

  <xsl:for-each-group select="$pPaths"
    group-adjacent=
        "substring-before(substring-after(concat(., '/'), '/'), '/')">
    <xsl:if test="current-grouping-key()">
     <xsl:choose>
       <xsl:when test=
          "substring-after(current-group()[1], current-grouping-key())">
         <xsl:element name=
           "{substring-before(concat(current-grouping-key(), '['), '[')}">

          <xsl:sequence select=
            "my:subTree(for $s in current-group()
                         return
                            concat('/',substring-after(substring($s, 2),'/'))
                             )
            "/>
        </xsl:element>
       </xsl:when>
       <xsl:otherwise>
        <xsl:value-of select="current-grouping-key()"/>
       </xsl:otherwise>
     </xsl:choose>
     </xsl:if>
  </xsl:for-each-group>
 </xsl:function>
</xsl:stylesheet>

When this transformation is applied on any XML document (not used), the result is:
<create>

      <id>1</id>
      <description>bar</description>
      <name>foo</name>
      <price>
         <amount>00.00</amount>
         <currency>USD</currency>
      </price>
      <price>
         <amount>11.11</amount>
         <currency>AUD</currency>
      </price>

      <id>2</id>
      <description>some name</description>
      <name>some description</name>
      <price>
         <amount>00.01</amount>
         <currency>USD</currency>
      </price>

</create>

Note:

You need to transform the "expressions" you are given into the format used in this transformation -- this is easy and straightforward.
In the final transformation you need to copy every node "as-is" (using the identity rule), with the exception that the top node should be generated in the "http://predic8.com/wsdl/material/ArticleService/1/" namespace. Note that the other namespaces present in the "template" are not used and can be safely ommitted.
Comment: Thanks, but is this a generic solution?
Comment: @Larry: Of course, this is a generic solution. It works with any set of "expressions" -- do note that in my example I added two new expressions, containing `price[2]`. If you need the created elements to be in specific namespace, these need to be specified (not any template at all) in a separate XML document using a convenient notation.
Comment: Ok, thanks. Btw: how about attribute values, would these work as well? For example, an expression such as: `/create/article[@val]=> 123`?
Comment: @Larry, almost everything can be done, however this question has become two big and is "overflowing". I recommend that you rethink your current requirements and ask a new question. I believe this answer is a correct solution to the current question and you may consider accepting it.
Comment: Thanks again, I've accepted. In regard to requirements, I really need what I've mentioned in the Q. I.e. that I want to populate an XML file, given a mapping of XPath expressions. The added requirement is that, I also want to begin with a template file, in the case that there is additional information not directly captured in the XPath expressions. For e.g., namespaces and other attributes. So perhaps, I was hoping a solution would be one where the template could be taken as "input" and used for this purpose. Furthermore, as the question also specifies Xpath, attributes should work as well.
Comment: @Larry, You have accumulated enough new requirements for a new question. Please, ask it. I want only to warn that the "template file" is useless and it may contradict the set of expressions. I would recommend adding "namespace expressions", similar in spirit to the ones used by Sean.
Comment: Ok thanks, I took your suggestion and asked a more detailed question with broader requirements. You can have a look at here: http://stackoverflow.com/questions/11395990/. If you have a solution, it would be much appreciated.
Answer: This solution requires you to re-organise your XPATH input information slightly, and to allow a 2-step transformation. The first transformation will write the stylesheet, which will be executed in the second transformation - Thus the client is required to do two invocations of the XSLT engine. Let us know if this is a problem.
Step One
Please re-organise your XPATH information into an XML document like so. It should not be difficult to do, and even an XSLT script could be written to do the job.
<paths>
 <rule>
  <match>article[1]/id[1]</match>
  <namespaces>
   <namespace prefix="ns1">http://predic8.com/wsdl/material/ArticleService/1/</namespace>

  </namespaces>
  <replacement>1</replacement>
 </rule>
 <rule>
  <match>article[1]/description[1]</match>
  <namespaces/>
  <replacement>bar</replacement>
 </rule>
 ... etc ...
</paths>

Solution constraints
In the above rules document we are constrained so that:

The match is implicitly prefixed 'expression: /create/'. Don't put that explicitly.
All matches must begin like article[n] where n is some ordinal number.
We can't have zero rules.
Any prefixes that you use in the match, other than s11="http://schemas.xmlsoap.org/soap/envelope/" and ns1="http://predic8.com/wsdl/material/ArticleService/1/". (Note: I don't think it is valid for namespaces to end in '/' - but not sure about that), are defined in the namespaces node.

The above is the input document to the step one transformation. Apply this document to this style-sheet ...
<xsl:stylesheet version="2.0"
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
      xmlns:step2="http://www.w3.org/1999/XSL/Transform-step2"
      xmlns:s11="http://schemas.xmlsoap.org/soap/envelope/"
      xmlns:ns1="http://predic8.com/wsdl/material/ArticleService/1/"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  exclude-result-prefixes='xsl'>
<xsl:output method="xml" indent="yes" encoding="UTF-8" />
<xsl:namespace-alias stylesheet-prefix="step2" result-prefix="xsl"/>

<xsl:template match="/">
 <step2:stylesheet version="2.0">
 <step2:output method="xml" indent="yes" encoding="UTF-8" />

  <step2:variable name="replicated-template" as="element()*">
   <step2:apply-templates select="/" mode="replication" />
  </step2:variable>

  <step2:template match="@*|node()" mode="replication">
     <step2:copy>
        <step2:apply-templates select="@*|node()" mode="replication" />
     </step2:copy>
  </step2:template>

  <step2:template match="/s11:Envelope/s11:Body/ns1:create/article" mode="replication">
   <step2:variable name="replicant" select="." />
    <step2:for-each select="for $i in 1 to
       {max(for $m in /paths/rule/match return
        xs:integer(substring-before(substring-after($m,'article['),']')))}
          return $i">
   <step2:for-each select="$replicant">
       <step2:copy>
        <step2:apply-templates select="@*|node()" mode="replication" />
       </step2:copy>
      </step2:for-each>
     </step2:for-each>
  </step2:template>

  <step2:template match="@*|node()">
   <step2:copy>
    <step2:apply-templates select="@*|node()"/>
   </step2:copy>
  </step2:template>

  <step2:template match="/">
   <step2:apply-templates select="$replicated-template" />
  </step2:template>

  <xsl:apply-templates select="paths/rule" />
 </step2:stylesheet>
</xsl:template>

<xsl:template match="rule">
 <step2:template match="s11:Envelope/s11:Body/ns1:create/{match}">
  <xsl:for-each select="namespaces/namespace">
   <xsl:namespace name="{@prefix}" select="." />
  </xsl:for-each>
  <step2:copy>
   <step2:apply-templates select="@*"/>
   <step2:value-of select="'{replacement}'"/>
   <step2:apply-templates select="*"/>
  </step2:copy>
 </step2:template>
</xsl:template>

</xsl:stylesheet>

Step Two
Apply your soap envelope file, as an input document, to the style-sheet which was output from step one. The result is the original soap document, altered as required. This is a sample of a step two style-sheet, with just the first rule (/create/article[1]/id => 1) being considered for the sake of simplicity of illustration.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:s11="http://schemas.xmlsoap.org/soap/envelope/"
                version="2.0">
   <xsl:output method="xml" indent="yes" encoding="UTF-8"/>
   <xsl:template match="@*|node()">
      <xsl:copy>
         <xsl:apply-templates select="@*|node()"/>
      </xsl:copy>
   </xsl:template>
   <xsl:template xmlns:ns1="http://predic8.com/wsdl/material/ArticleService/1/"
                 match="/s11:Envelope/s11:Body/ns1:create[1]/article[1]/id[1]">
      <xsl:copy>
         <xsl:apply-templates select="@*"/>
         <xsl:value-of select="'1'"/>
         <xsl:apply-templates select="*"/>
      </xsl:copy>
   </xsl:template>
</xsl:stylesheet>

More solution constraints

The template document must contain at least one /s11:Envelope/s11:Body/ns1:create/article . Only the article node is replicated (deeply) as required by rules. Other than than it can be any structure.
The template document cannot contain nested levels of the s11:Envelope/s11:Body/ns1:create node.

Explanation
You will notice that your XPATH expressions are not far removed from a match condition of template. Therefore it is not too difficult to write a stylesheet which re-expresses your XPATH and replacement values as template rules. When writing a style-sheet writing style-sheet the xsl:namespace-alias enables us to disambiguate "xsl:" as an instruction and "xsl:" as intended output. When XSLT 3.0 comes along, we are quiet likely to be able to reduce this algorithm into one step, as it will allow dynamic XPATH evaluation, which is really the nub of your problem. But for the moment we must be content with a 2-step process.
The second style-sheet is a two-phase transformation. The first stage replicates the template from the article level, as many times as needed by the rules. The second phase parses this replicated template, and applies the dynamic rules substituting text values as indicated by the XPATHs.

UPDATE
My original post was wrong. Thanks to Dimitre for pointing out the error. Please find updated solution above.
After-thought
If a two-step solultion is too complicated, and you are running on a wintel platform, you may consider purchasing the commercial version of Saxon. I believe that the commercial version has a dynamic XPATH evaluation function. I can't give you such a solution because I don't have the commercial version. I imagine a solution using an evaluate() function would be a lot simpler. XSLT is just a hobby for me. But if you are using XSLT for business purposes, the price is quiet reasonable.
Comment: I see I misread the question. I think the 2-step method might still be workable for this question, but it becomes a lot harder. I'll have a think about it.
Comment: @DimitreNovatchev: Thank-you for pointing that out. Solution corrected .
Comment: Sean, the approach is good, with the exception of one remaining problem: if I understand well your code, it will search for `...article[2]` and will not find such a node as there isn't  (and can't be) more than one `article` element in the "template" provided by the OP. Due to this reason, the result must be generated -- not just simply doing replacemants in the "template". This means, that if you construct all the rules, the generated stylesheet in the first pass, when applied on the "template" in the second pass doesn't produce more than one `article` element (or any other element `x[2]`.
Comment: Sean, I see. However, this code is not generic and uses hardcoded element names as `article` and `id`. I believe that the OP is looking for a generic solution.


Why my SlidingTab scrollbar color does not change and always return on the position 0

Question: What is wrong with this code? After I clicked tab page 2, it loads the data and the scrollbar color below does not change, and always returns to tab page 1. What should I do? All I want is to indicate by scrollbar color which tab is selected after I click which page I want.
Here is the code:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    titlebar = getIntent().getStringExtra("Branch");
    setTitle( titlebar +" Order" );
    setContentView(R.layout.activity_main);

    // Creating The Toolbar and setting it as the Toolbar for the activity

    toolbar = (Toolbar) findViewById(R.id.tool_bar);
    setSupportActionBar(toolbar);

    // Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
    adapter =  new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);

    // Assigning ViewPager View and setting the adapter
    pager = (ViewPager) findViewById(R.id.pager);
    pager.setAdapter(adapter);

    // Assiging the Sliding Tab Layout View
    tabs = (SlidingTabLayout) findViewById(R.id.tabs);
    tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width

    // Setting Custom Color for the Scroll bar indicator of the Tab View
    tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
        @Override
        public int getIndicatorColor(int position) {

                return getResources().getColor(R.color.tabsScrollColor);

        }
    });
    // Setting the ViewPager For the SlidingTabsLayout
    tabs.setViewPager(pager);

    pager.setOnPageChangeListener(pagelistener);
    pagelistener.onPageSelected(0);

}

final ViewPager.OnPageChangeListener pagelistener = new ViewPager.OnPageChangeListener() {
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        if (position==0){

            new LoadProducts().execute();

        }else if(position==1){

            new LoadCart().execute();
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
};

ViewPagerAdapter.java:
package com.example.work.mcoatorderingapp;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;

public class ViewPagerAdapter extends FragmentStatePagerAdapter {

CharSequence Titles[]; // This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created
int NumbOfTabs; // Store the number of tabs, this will also be passed when the ViewPagerAdapter is created

// Build a Constructor and assign the passed Values to appropriate values in the class
public ViewPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
    super(fm);

    this.Titles = mTitles;
    this.NumbOfTabs = mNumbOfTabsumb;

}

//This method return the fragment for the every position in the View Pager
@Override
public Fragment getItem(int position) {

    if(position == 0) // if the position is 0 we are returning the First tab
    {
        OrderTab ordertab = new OrderTab();
        return ordertab;
    }
    else if(position==1)     // As we are having 2 tabs if the position is now 0 it must be 1 so we are returning second tab
    {
        ViewOrderTab viewordertab = new ViewOrderTab();
        return viewordertab;
    }
    else
    {
        OrderStatus orderstatus = new OrderStatus();
        return orderstatus;
    }

}

// This method return the titles for the Tabs in the Tab Strip

@Override
public CharSequence getPageTitle(int position) {
    return Titles[position];
}

// This method return the Number of tabs for the tabs Strip

@Override
public int getCount() {
    return NumbOfTabs;
}

public static interface FirstShot
{
    public void onFirstShot();
}

}

Comment: Post your code for ViewPagerAdapter
Comment: Please check the code above
Answer: The problem is pager.setOnPageChangeListener(pagelistener), instead do this tabs.setOnPageChangeListener(pagelistener)
i.e instead of creating and assigning OnPageChangeListener for ViewPager, create and assign one for SlidingTabLayout to listen for its event.
Below is the portion from SlidingTabLayout.java found on android sample project explaining the part.
     /**
     * Set the {@link android.support.v4.view.ViewPager.OnPageChangeListener}. When using {@link SlidingTabLayout} you are
     * required to set any {@link android.support.v4.view.ViewPager.OnPageChangeListener} through this method. This is so
     * that the layout can update it's scroll position correctly.
     *
     * @see android.support.v4.view.ViewPager#setOnPageChangeListener(android.support.v4.view.ViewPager.OnPageChangeListener)
     */
     public void setOnPageChangeListener(ViewPager.OnPageChangeListener listener) {
        mViewPagerPageChangeListener = listener;
     }

Also setOnPageChangeListener is deprecated, use addOnPageChangeListener instead of that in your code.
Comment: My main problem is when i click my desire tab the color below that tab does not change and always return to tab 1, i dont have problem in loading data.
Comment: please check my problem above
Comment: You should not add listener to pager, add it to SlidingTabLayout. Did you try that?
Comment: Also setOnPageChangeListener is deprecated, use addOnPageChangeListener instead. http://developer.android.com/reference/android/support/v4/view/ViewPager.html#addOnPageChangeListener(android.support.v4.view.ViewPager.OnPageChangeListener)
Comment: Can you provide some examples because I'm new in android development
Comment: Example for ? I mean for which part


Finding a function whose product with itself has a higher value at an optimal point for a different parameter value

Question: Suppose we have a function $f(x;\theta)$ that depends on a parameter $\theta$. We also have another function $P(x, y;\theta)=f(x;\theta)\cdot f(y;\theta)$. For a fixed value of $\theta$, say $\theta_1$, the function $P(x, y;\theta_1)$ has a global maximum at $(x_1, y_1)$. However, for a different value of $\theta$, say $\theta_2$, the function $P(x, y;\theta_2)$ has a global maximum at $(x_2, y_2)$, which is not the same as $(x_1, y_1)$. Does there exist any function $f(x; \theta)$ that satisfies the condition $P(x_1, y_1;\theta_2)>P(x_1, y_1;\theta_1)$?
EDIT: Found a simple solution. $f(x; \theta) = m\theta \cdot e^{-m\theta(x - n(\theta))^2}$ or $X\text~N(n\theta, 1/m\theta)$ could be two such functions.
Answer: I take it that this inequality should hold for all $\theta_2\ne\theta_1$. (If not, you'd need to specify for which values of $\theta_2$ it's meant to hold.)
If so, there can be no such function, since we'd have
$$
P(x_1,y_1;\theta_2)\gt P(x_1,y_1;\theta_1)\ge P(x_1,y_1;\theta_2)\gt P(x_2,y_2;\theta_2)\ge P(x_1,y_1;\theta_2)\;,
$$
where the first strict inequality is your condition, the second strict inequality is the same condition with $1$ and $2$ swapped, and the weak inequalities are due to the fact that $(x_1,y_1)$ and $(x_2,y_2)$ are global maxima for the respective parameter values $\theta_1$ and $\theta_2$.


Personal email archive alternative to PST files

Question: If you aren't willing or able to prevent users from keeping old emails "forever", what solution do you have?

Exchange 2007 allows pretty massive mailboxes, but lots of people still recommend against it (although it's unclear whether there's a real reason for this, or it's just an old habit).
PST files should not be on a network drives -- the choice seems to be doing it anyways (which I've done for years without any real problem) or backing up desktops (not always an option)

So.. what else?
Notes:

Bonus points for solutions that works with hosted/outsourced exchange setups
Bonus points for solutions that allow for some archives to be shared amongst users
Bonus points for solutions that allow access/search via Outlook (Added w/ Edit)
This has nothing to do with compliance, I don't care to archive all emails
Comment: Could you clarify your question? Are you looking to retain access to these old emails in Outlook? If not, you could simply export the messages and save them in CSV then delete them if you do not want to use a PST.

I personally throw all older messages in the Archive folders to keep my inbox snappy.
Answer: If your are using MS Exchange 2007, then you could use Managed Folders. With Managed Folders you can make custom rules for archiving/deleting old emails in client mailboxes. MS Exchange 2010 will include builtin email archiving.
From users perspective, Outlook 2007/2003/2002 Add-in: Personal Folders Backup is pretty handy.
Comment: Nice, thanks for reminding me about the PST backup tool.
Answer: You're not going to like this answer, but I would keep the messages on the server and improve your storage/backup options.  When you export the messages you lose the advantages of single instance storage and you will only add complexity to the system.  If you're using a hosted solution and they can't expand your storage I would consider moving to someone who can. If not then auto-archiving to .PST's will probably be your best bet.
Comment: That's the way to go - once the email leaves the server it cannot be safely backed up anymore so if an employee's drive crashes and looses it's data, the PST is gone forever too.
Comment: Joshua- Desktop backups would take care of that.  (Now, backing up desktop may not be something one wants to do, but it's not unheard of.)
Answer: See the similar questions here for better answers: Email Archiving in an Exchange Environment
And I copy my answer again below,
I always recommend GFI MailArchiver (http://www.gfi.com/mailarchiver/). I have been using it since 2006. Couldn't be happier. To be honest, it's a dream to whoever needs to manage the exchange server for having an archive solution. It makes so much easier managing on the server side.
The MailArrchiver is a web-based system built on ASP.net with using SQL at the back. You don't need to change anything on Exchange server side, only enable the journal on the mail storage and it archives emails on the fly in the real time.
It also has bulk import tool that helps to archive the existing mail boxes and a bulk export tool to download the emails from the archiver. It also has audit built right in.
Most of all, it's inexpensive.
Plus, MailArchiver solves all requirements he has.
Answer: One other option (in addition to GFI MailArchiver) is Redgate's Exchange Server Archiver which seems to do everything you are looking for.  I haven't used it myself, but they do have a free trial: http://www.red-gate.com/products/Exchange/index.htm
Answer: A good friend of mine that worked at a large Exchange Hosting company wrote a good article as to why you do not want to leave PSTs on a network share here:  http://cohesivelogic.com/2009/05/should-you-store-psts-on-your-file-server/
With Outlook 2007 SP2, local caching of very large mailboxes (>2GB) works very well.
As to your actual question... I see that you don't want to archive all e-mails, but just certain e-mails for certain people?  Are people concerned about losing information that they have moved into PSTs?
Comment: pst is an evil to email management. stay away, as far as you can.
Comment: I agree... I was trying to clarify some ambiguity in the original question.
Comment: Aware of this, i should've linked to the KB in my question.  PSTs are still an option, but should be stored on the desktop.
Answer: Archive the email using TEAL (CoolRock Software). Users can search for their email using the web interface, or the TEAL Outlook plugin. Users can be more confident about deleting their email from Outlook knowing they can just drag it back if they need to (even if the Exchange server is down). Then you can introduce quotas etc. if you want to.
Answer: We show our users how to move email they want to keep to their Personal Folders. That way its off the server and on their machine, but still in Outlook for them to access it. For users that can't handle this on their own, we show them how to set up Auto Archive in Outlook. It basically moves anything older than a set time frame to a Personal Folder in Outlook.
This solution works for your off-site (hosted) solution as their data is moved from the server to their desktop and keeps you from having to store .pst's on you SAN. We leave the data backup to them. If they want to put it on the SAN they can or not worry about it.
Comment: Leaving the data backup up to the users sounds like a great way to get into a lot of trouble..  Just wait for a high level employee to lose the PST because the desktop drive failed..
Answer: DON'T USE PST FILES AT ALL
They are the worst invention ever for networked environments.  If you have Exchange you don't need them.  I'm continually amazed by the amount of people who wreck perfectly good Exchange implementations by adding on PST files.
On the PC they don't get backed up, unless you resort to trickery like copying them back to the network at logoff (which won't be good for remote users).  On the server Outlook will maintain open file handles and kill your network performance.  Either way you're relying on the user to manage their own email storage.  Most users are not interested in doing this.  They want to log in in the morning and get their stuff.  Either way they're not secure - anybody can pull a copy of the PST and - even if they're encrypted - run a brute force decrypter.
The solution is to implement tight data retention policies with rigidly enforced quotas.  Tell the users that retaining correspondance in the email is useless, as that record of correspondance is not accessible by anyone else (so what's gonna happen when they're on leave and it's urgently needed), and it will be lost when they leave the organisation and their account gets deleted.  Instruct them to either print and file important correspondance, or to save it off to a shared folder.  Get them into good habits and the end result will be better for everybody.
Comment: "Print and file important correspondence?" Really?
Comment: "The solution is to implement tight data retention policies with rigidly enforced quotas" -- The central premise of the question is that this is not an option.
Answer: There is a registry tweak that will limit the size of the .pst here
I havent personally used it yet, but plan on experimenting with it soon.  We have psts on a dedicated machine at each branch and havent had any issues at all.  Some of them are getting fairly large though.
Answer: For myself and on an experimental basis for a few normal users, we've used two products called EZDetach and MessageSave.  You can read more on their website, but basically they're used to pull messages and attachments out of Outlook and into folders.
EZDetach goes through any Outlook folder(s) you point it at (can be a mailbox or a PST) and pulls out attachments and deletes them (if you want.)  MessageSave does the same thing with the body of the messages - it pulls them out and saves them on disk in - usually - .eml format.
There are other similar tools, but I haven't tested very many of them.  I found these two work for me personally and for a few others in the company.  They're not really for novices, they usually just work they way you set them up, but there are lots of options and if you change something you can get strange results - messages saved in unexpected locations, for example.
They do give you an easy way to share the "archived" messages, just put the folders and files on a share.
So these aren't a perfect solution, but for you or someone with similar needs, they might do the trick.
OTOH...
For myself, I keep my email archives in text files, and have all my email going back 19 years.  Easy to search, very portable.  For the past year or so, I've used the programs mentioned above to save my messages as text and then to store any attachments I didn't have somewhere else.
Answer: Everyone seems to have different definitions of massive, but for me running Exchange 2003 with executives that generate over 10GB/year in mail, I wrote a simple VBA script that replicates the archiving functionality that comes with Outlook, but seems to be able to copy mailbox to mailbox better and lets me specify date parameters.
Each year, I create a new mailbox for that year like "bob2008", etc and every quarter/half year/year (depending on how fast their mailbox grows), I move mail from their current mailbox to the archive one. The archive mailboxes are stored on a separate Exchange server that just stores archived mail in order to keep our main server fast. Backups don't need to be frequent because there is only new data on a quarterly basis.
As for allowing users access, I just grant them permission to view it as an additional mailbox in their Outlook.
Answer: Use an LDAP server. You can keep old email as long as you want and there's support for shared folders. Cyrus is an excellent option for this.
Comment: ?!?!?!  What does LDAP have to do with storing e-mail?

http://en.wikipedia.org/wiki/LDAP
Comment: LDAP is good, but not THAT good, I'm afraid.


Dart HTTP Server and importing a SSL Certificate

Question: I have create a Dart HTTP(s) server for deploying files. I can have it run the https with a self signed cert. But how do you import a .crt properly from someone for example GoDaddy properly?
Answer: So after a long struggle I have finally succeeded in importing a certificate from GoDaddy properly into Darts HttpServer bindSecure.
In order to pull this off, first you must merge your key and the certificate from GoDaddy together.
This can be done using a variation of this:
openssl pkcs12 -export -in website_cert.crt -inkey website_key.key -out website.p12 -name Name-Of-Cert -passout pass:SECRET
After...
pk12util -i website.p12 -d 'sql:./' -W SECRET
You should now see the cert with the Name-Of-Cert value, (If you have a password on the db, apply the appropriate flags)
certutil -L -d 'sql:./'
Now, verify
certutil -V -u V -d 'sql:./' -n "Name-Of-Cert"
Credit to: https://stomp.colorado.edu/blog/blog/2010/06/04/on-setting-up-mod_nss/
Comment: I made a complete tutorial here: https://gist.github.com/stevenroose/e6abde14258971eae982


Using glmrob function in R with proportional/percentage dependent variable

Question: I have performed a glmrob to infer whether belonging to one of the treatment groups causes a higher % in success. I have used the following code:
rob5 <- glmrob(Num_ofSuccess/Total_No_Reports~RGamDesStrat3, weights = Total_No_Reports,
               family = binomial, data = MyMasterThesisDataRSTUDIOV3, method = "Mqle",
               control = glmrobMqle.control(tcc = 3.5))

The num_ofsuccess represents the total number of reports there were successful, and total_no represents the total number reported.
The results that I received are as follows:
Coefficients:
                      Estimate      Std. Error
(Intercept)            0.5108        0.3266
RGamDesStrat3(0,1]     2.2088        0.4744
RGamDesStrat3(1,2]     2.1638        0.4346

All the estimates are significant. However, the estimates 2.2088 and 2.1638 are impossible to interpret since the DV can only range from 0 to 1. I am unsure what I might have done wrong. Any advice on how to continue?
Comment: I am voting to leave this open as it is really about statistics - the same issue could arise with any software.
Answer: The fact that the parameter estimates are above 2 really has little to do with the DV being bounded by 0 and 1. When you put in "family = binomial" then by default you get a logit link, so you are estimating the logit of the proportion of successes. These parameter estimates would then go into a formula for estimating that.
You can get the predicted values for the proportion by using fitted.values.  Those values should be between 0 and 1.


Generate drupalSettings in Ajax Callback

Question: I'm returning a form with #ajax functionality in an Ajax response. The form is properly loaded into the page, however it is not #ajaxified, as the drupalSettings are not being returned. In D7, we could generate the JS settings AKA Drupal.settings using the following code:
<code>$scripts = drupal_add_js();
if (!empty($scripts['settings']))
{
    $settings = '<script type="text/javascript">jQuery.extend(Drupal.settings, ';
    $settings .= drupal_json_encode(call_user_func_array('array_merge_recursive', $scripts['settings']['data']));
    $settings .= ');</script>';
}
</code>
I'm trying to find the D8 equivalent of this code, but not having much success. At the moment I'm returning a JsonResponse from my ajax callback, but I'm thinking I probably need to return an AjaxResponse. What I can't figure out is how to pass my generated form to the AjaxResponse, in order for it to return the settings along with the HTML for the form.
Answer: Well, I'm answering my own question. The secret is to use BubbleableMetadata. Here is my code explaining what I did and how it happened. Here is my entire controller response that generates the JSON for the response:
<code> public function ajax_callback($type)
 {
    // Retrieve the form
    $form = \Drupal::service('form_builder')->getForm('Drupal\path\to\Form');

    // Render the form
    $rendered_form = render($form);

    // Get the data from BubbleMetaData
    $data = BubbleableMetadata::createFromRenderArray($form);
    // Retrieve the attachments from the $data
    $attachments = $data->getAttachments();

    // Generate the settings to be sent back with the ajax response
    if(!empty($attachments['drupalSettings']))
    {
        $settings .= '<script type="text/javascript">jQuery.extend(drupalSettings, ';
        $settings .= Json::encode($attachments['drupalSettings']);
        $settings .= ');</script>';
    }

    // Send back the rendered form along with the settings
    $response = [
        'content' => $rendered_form . $settings,
        'status' => TRUE,
        'type' => $type,
    ];

    // Return the data as a JsonResponse
    return new JsonResponse($response);
}
</code>
Answer: You can attach the settings to the section of the array you return in the ajax callback:
<code>$form['section']['#attached']['drupalSettings']['mysettings'] = ...
return $form['section'];
</code>
If you use an html insert command like replace or a dialog command you can do the same for the content you use in this command.
ajax.js will reattach drupal behaviors and settings after it receives the ajax response.
Comment: I'm not trying to insert the settings, I'm trying to retrieve them to send back with my Ajax response.
Comment: I think the js code you are looking for is already in ajax.js, see edit.
Comment: Again, I'm not looking to insert the settings, I need to retrieve the entire drupalSettings from the form, to send back to the browser. I figured out how to do it, you can see my solution below.
Comment: But thank you for your help - sorry I just re-read both my responses and they were a little curt.
Comment: No problem, I try to understand why AjaxResponse is not working for you. Drupal\Core\Ajax\AjaxResponse::addCommand is also using BubbleableMetadata.


Spring MVC stop refreshing the page after GetMapping

Question: I am working on a page where I have to retrieve the "tasks" of a specific date from the database. My current approach is to use GetMapping at the server, and return the list of tasks
Below is part of my TaskController
@Controller
@RequestMapping()
public class TaskController {

    @Autowired
    private TaskService taskService;

    @GetMapping("/calendar/{date}")
    public String displayTasksByClick(@PathVariable("date") int date, Model model) {

        long userId = this.getCurrentUserId(); // just a method to get the user id requesting the task

        List<Task> taskList = taskService.findByDateAndUserId(date, userId);
        model.addAttribute("taskList", taskList);
        return "/calendar";
    }

And calendar.html looks like this (I'm only pasting the relevant part)

        <meta charset='utf-8' />
        <title>Dashboard</title>
        <link rel="stylesheet" href="../static/css/calendar.css">

show

show

show

  ......


How to use CC_DENY and CC_ALLOW of the CSF firewall

Question: How to use CSF Firewall features:

CC_DENY

and

CC_ALLOW

I am getting a lot of attempts to access ssh, so I would like to block all countries, instead of having to add them one by one.
Of course, leave only my country as allowed.
UPDATE 2020-02-13
After researching a lot I found that:

CC_DENY = If you want to block the country, this is where you must enter the country code.
CC_ALLOW = Here is the catch, if you put your country's code here, it will do the general release, including firewall ports. In other words, your country will not respect any rules of your firewall.

I will leave my contribution of country codes. REMOVE YOUR CODE.
CC_DENY = "AD,AE,AF,AG,AI,AL,AM,AO,AQ,AR,AS,AT,AU,AW,AX,AZ,BA,BB,BD,BE,BF,BG,BH,BI,BJ,BL,BM,BN,BO,BQ,BS,BT,BV,BW,BY,BZ,CA,CC,CD,CF,CG,CH,CI,CK,CL,CM,CN,CO,CR,CU,CV,CW,CX,CY,CZ,DE,DJ,DK,DM,DO,DZ,EC,EE,EG,EH,ER,ES,ET,FI,FJ,FK,FM,FO,FR,GA,GB,GD,GE,GF,GG,GH,GI,GL,GM,GN,GP,GQ,GR,GS,GT,GU,GW,GY,HK,HM,HN,HR,HT,HU,ID,IE,IL,IM,IN,IO,IQ,IR,IS,IT,JE,JM,JO,JP,KE,KG,KH,KI,KM,KN,KP,KR,KW,KY,KZ,LA,LB,LC,LI,LK,LR,LS,LT,LU,LV,LY,MA,MC,MD,ME,MF,MG,MH,MK,ML,MM,MN,MO,MP,MQ,MR,MS,MT,MU,MV,MW,MX,MY,MZ,NA,NC,NE,NF,NG,NI,NL,NO,NP,NR,NU,NZ,OM,PA,PE,PF,PG,PH,PK,PL,PM,PN,PR,PS,PT,PW,PY,QA,RE,RO,RS,RU,RW,SA,SB,SC,SD,SE,SG,SH,SI,SJ,SK,SL,SM,SN,SO,SR,SS,ST,SV,SX,SY,SZ,TC,TD,TF,TG,TH,TJ,TK,TL,TM,TN,TO,TR,TT,TV,TW,TZ,UA,UG,UM,US,UY,UZ,VA,VC,VE,VG,VI,VN,VU,WF,WS,YE,YT,ZA,ZM,ZW"

CC_ALLOW = ""

Answer: Use CC_DENY to block countries in your server
or
Use CC_ALLOW to whitelist countries in your server
Allowed values are two-letter ISO Country Code(s) e.g. "US,GB,DE"
Caution must be taken when using this setting as you might completely block yourself or your visitors.
A better solution might be to change the default ports of services e.g., SSH port.
Comment: @Tiago Yes, also consider using `CC_ALLOW_FILTER` instead so your port rules are still applied. `CC_ALLOW` ignores all other rules AFAIK
Comment: How do I block all other countries and only allow BR?
Comment: @Tiago put `BR` in `CC_ALLOW `
Comment: CC_DENY is empry?


Dificuldade para obter informações atraves de Expressões Regulares

Question: Estou tendo dificuldades para obter uma informação utilizando preg_match_all.
Estas informações estão sendo retiradas de um código HTML de uma página da intranet, porém das informações que preciso, estou conseguindo coletar somente uma.
Segue um pedaço do código onde constam as informações:

                      19445/2015:2

As informações que preciso estão entre as tags <title>, no qual estou conseguindo capturar. O que não estou conseguindo é coletar a informação que esta entre  .
A código que estou utilizando para recuperar estas informações:
 preg_match_all("/title=\"(.*)/", $url, $conteudo);

Minha dificuldade está em como fazer para também recuperar o que está entre  na mesma Expressão regular que está sendo utilizada para o <title>.
Answer: Acerte para :
preg_match_all("/title=\"(.*)\"|(.*)/", $url, $conteudo);

Comment: ha vais tentado desta forma, porem semresultado. Para utilizar assim tenho que inserir um quebra "\" na tag  ficando assim:
    preg_match_all("/title=\"(.*)|(.*)<\/strong>/", $url, $conteudo);
mas não esta trazendo o conteudo desejado.
Comment: mas o que ele ta trazendo para você? Qual o conteudo desejado? No regex Tester funcionou, estranho, qual ta sendo o problema de retorno ae?
Comment: não me traz o que esta entre as tags de , que usando o codigo acima, deveria ser 19445/2015
Comment: consegui fazer o ajuste necessario e agora esta retornando o valor desejado, mas tambem esta trazendo outras informações que tambem estão entre as tags . Tens como restringir o retorno de valor numerico. Só me interessa o que contiver numero. O que deve acrescentar na ER para isso?


two premises with four conclusions drawn from them (taking singly or together). Which conclusions are validly drawn?

Question: <code> Given below are two premises with four conclusions drawn from them (taking singly or
  together). Which conclusions are validly drawn ? Select the correct answer from the code
  given below.

  Premises :  (i) All lawyers are extroverts.
              (ii) Some wisemen are extroverts.
  Conclusions : (a) All lawyers are wisemen.
              (b) All wisemen are lawyers.
              (c) Some extroverts are wisemen.
              (d) All extroverts are lawyers.
  Code :

 (1) (b) and (c) only
 (2) (c) only
 (3) (a) only
 (4) (a) and (c) only
</code>
I guess the correct answer is option 2, which is some extroverts are wisemen. isn't?
Answer: Yes, you're correct. You can visualize this via a Venn diagram. Let $L$ be the set of all lawyers, let $E$ be the set of all extroverts, and let $W$ be the set of all wisemen. Then the first premise states that $L$ is a subset of $E$ (i.e.: $L$ is contained in $E$), and the second premise states that $E$ and $W$ overlap (i.e.: there is at least one person who is both an extrovert and a wiseman).
Conclusion (a) could be false, since $L$ doesn't need to be contained in $W$ (i.e.: there could be some person who is a lawyer but not a wiseman). You can reason similarly for the other two wrong conclusions.


php não mostra mensagens de erro

Question: Bom dia.
No início de minha página php coloquei:
ini_set("display_errors",1);
ini_set("display_startup_errors",1);
error_reporting(E_ALL);
ini_set("log_errors_max_len",2048);

Após estas diretivas, dei um phpinfo().
display_errors e display_startup_erros estão marcados como On na coluna Local Value.
Ocorre que as mensagens de erro não são mostradas de jeito nenhum.
Tirei o ponto-e-virgula do final de uma linha e a página fica em branco, não mostrando a mensagem de erro que me ajudaria a localizar o problema.
Já tentei mudar de php5.6 para php 7 mas também não adiantou.
Estou rodando esta página hospedada na Locaweb.
Alguém pode me dar uma ajuda, por favor?
Muito obrigada
Answer: Ao invés de tentar exibir erros na página, considerando que é uma hospedagem, o mais recomendado é direcionar os erros para um arquivo e inclusive mensagens customizadas como abaixo:
ini_set("log_errors", 1);
ini_set("error_log", "/caminho/onde/guardar/php-error.log");
error_log( "POST: " . print_r($_POST, true) );

Assim você não corre o risco de deixar dados de depuração na página por acidente.

php não mostra mensagens de erro


Dúvida a respeito de excluir elementos específicos da função clone()

Question: Me surgiu uma dúvida a respeito da exclusão de elementos específicos quando eu uso a função clone(). Gostaria de saber se consigo excluir os elementos  quando eu chamar a função. Ou seja, o que está escrito "Item", "ID", "Selecione um produto" etc; só apareça na primeira DIV, as demais que serão adicionadas, só venham com os valores dos inputs / select.
Isso facilitaria também quando eu fosse imprimir a página, visando que, eu não conseguiria dar um display:none nesses elementos através do media queries. Alguém consegue me informar se é possível fazer isto?
index.php:

                            Item:

                            <input type="text" class="index font-pop input-div" id="index_produto"
                                   name="index_produto[]" value="1" readonly="true">

                            ID:

                            <input class="font-pop number_id_produto input-div" value="0" readonly="true"
                                   name="id_produto[]">

                            Selecione um produto:
                            <select class="selectpicker form-control" data-show-subtext="false"
                                    data-live-search="true" name="select_produtos[]" id="select_produtos" onchange="initProdutos(this)">
                                <?php
                                foreach ($result2 as $item_produtos) {
                                    echo '<option data-subtext="' . $item_produtos['desc_produto'] . '" value="'
                                        . $item_produtos['desc_produto'] . '">' . $item_produtos['desc_produto'] . '</option>';
                                }
                                ?>
                            </select>

                            Embalagem:

                            <input type="text" maxlength="2" class="edit-input font-pop" name="embalagem[]" value="">

                            Preço:

                            <input type="text" maxlength="5" name="preco[]" class="edit-input font-pop" value="0">

                            Quantidade:

                            <input type="text" maxlength="3" class="edit-input font-pop" value="0"
                                   name="quantidade-produto[]">

                            Preço do Produto:

                            <input class="font-pop preco-produto input-div" readonly="true" name="preco-produto[]"
                                   value="0">

                            <button type="button" class="remover glyphicon glyphicon-remove button-produto"></button>

                <button type="button" id="add-button" class="glyphicon glyphicon-plus-sign button-produto"></button>

JQuery:
$(function () {
    var clone = $('#allProducts').html();
    $(document).on('click', '#add-button', addProd);

    $(document).on('click', '.remover', function () {
        $(this).parents('.produtos-wrap').remove();
        ids();
        calculos();
    });

    function addProd() {
        $('#allProducts').append(clone);
        ids();
    }

    function ids() {
        $("[name='index_produto[]']").each(function (i, e) {
            $(e).val(i + 1);
        });
    }
})

Comment: Tente trocando esta linha: `var clone = $('#allProducts').html();`, por esta: `var clone = $('#allProducts').html().replace(/.*?<\/b>|/g, "");`
Answer: Se quer remover todos os  e os
, você pode fazer de duas formas:
Usando .remove()
Converta a variável clone, que é uma string com o HTML da div, em objeto HTML com $.parseHTML() e em seguida busque as tags  e
 e remova-os:
var clone = $.parseHTML($('#allProducts').html());
$("b, br", clone).remove();

Usando .replace()
Usando uma expressão regular (regex) para buscar as tags  e
:
var clone = $('#allProducts').html().replace(/.*?<\/b>|
/g, "");

Comment: A opção do .replace() funcionou perfeitamente, obrigado Sam !
Answer: Uma outra possibilidade que complementa a resposta do @Sam e que não cabe em um comentário.
var $clone = $('#allProducts').clone();
$clone.find("b, br").remove();

// console.log($clone.html());
// $clone.removeAttr('id').appendTo('body');

E você continua com a vantagem de poder manipular os elementos de $clone sem precisar parsear o conteúdo novamente.
$clone.find('.button-produto').on('click', function () {});
$clone.find('.edit-input').on('input change', function () {});
(...)

E assim vai.


Buscar dados via SQL usando Laravel

Question: Preciso fazer um select para me retornar todos os usuários que possuam as iniciais de um nome.
Exemplo:
Eu digito no meu campo input de busca: "paulo" me retorna todos os usuários que tenham essa palavra.
Fiz uma pesquisa e usei isso:
$usuarios = User::where('nome', 'LIKE', $search. '%')
                ->paginate();
            return view('auth.adm.lista', compact( 'usuarios', 'title'));

Esse código me retorna 15 usuários.
Porém se vou no PHPMYADMIN e digito esse sql:
SELECT * FROM `users` WHERE nome LIKE 'paulo%'

A linha acima retorna 44 usuários.
Onde posso estar errando que acaba limitando a 15 a busca no laravel ?
Answer: No paginate é o retorna em página (ou seja, pagina 1, pagina 2 e assim conforme página tiverem com esse resultado):
$usuarios = User::where('nome', 'LIKE', $search. '%')
                ->paginate();  // isso retorna somente 15 registros

que por padrão o método paginate retorna 15 registros por vez, mas, isso pode ser configurado para retornar outra quantidade, exemplo: 10 registros o código é o seguinte: ->paginate(10) consequentemente a paginação é de 10 em 10 registros.

Se quiser retornar todos os registro utilize o método get():
$usuarios = User::where('nome', 'LIKE', $search. '%')
                ->get(); // retorna todas da pesquisa sem paginação.

Leia a documentação: Database: Pagination

Buscar dados via SQL usando Laravel


Other twig syntax in templates

Question: In some twig templates of the commerce modules, I can see the use of an alternate syntax:
Ex. in commerce-cart-flyout-offcanvas-contents-items.html.twig :
<% _.each(cart.order_items, function(orderItem, key) { %>

or
<%= orderItem.total_price.formatted %>

I can't see any doc on this and as I am curious, I would like to know from where it is coming and what is the difference.
Comment: They may have done something like this: https://twig.symfony.com/doc/2.x/recipes.html#customizing-the-syntax
Comment: Thank you... This makes sense. I can accept your answer if you add it.
Answer:
In some twig templates of the commerce modules, I can see the use of an alternate syntax:

This is only in one module - Commerce Cart Flyout. These are Underscore.js templates. These are used to customize the JavaScript progressively decoupled cart flyout. These are not actually Twig templates.
It was a design decision I regret to try and enable end-users to customize Flyout without needing to learn how to override JavaScript.
Comment: If, with the help of this "design decision" we do not needs to handle Javascript when overriding is mandatory, then I will say it is a good idea!!!
Comment: Yeah, this allows you to alter the Flyout templates without `libraries-extend` or anything. The Underscore.js contents are in Drupal's theme registry and more easily overridden.

Would documentation somewhere have helped? In Flyout? Where did you find the template, our Belgrade theme maybe? or the module itself and I should add file doc comments

Other twig syntax in templates


Pry Remote / ByeBug next goes into Teardown

Question: So I've decided to split my last post since the bug is Related to ByeBug more than to Pry-Remote (I think). Last post URL: Pry-Remote not triggered Rails 4
Problem:
When typing Next in Pry-Remote, ByeBug acts unexpectedly and goes to "teardown".

Also created an ByeBug Issue:
https://github.com/deivid-rodriguez/pry-byebug/issues/78
What I am running:
  gem 'pry-byebug', '=1.3.3'
  gem 'pry-stack_explorer'
  gem 'pry-rails'
  gem 'pry-remote'

pry (0.10.2)
  coderay (~> 1.1.0)
  method_source (~> 0.8.1)
  slop (~> 3.4)
pry-byebug (1.3.3)
  byebug (~> 2.7)
  pry (~> 0.10)
pry-rails (0.3.4)
  pry (>= 0.9.10)
pry-remote (0.1.8)
  pry (~> 0.9)
  slop (~> 3.0)
pry-stack_explorer (0.4.9.2)
  binding_of_caller (>= 0.7)
  pry (>= 0.9.11)

ruby 2.2.3p173 (2015-08-18 revision 51636) [x86_64-darwin14]
Rails 4.2.4

Note 1:
Updated all the pry related gems
https://gist.github.com/YOUConsulting/65cdcdc22d32780dde51
Comment: Why people downvoting this topic? Still no solution found...
Answer: You seem to be using an ancient version of pry-byebug, the latest as of this writing is 3.2.0 but you're using 1.3.3. If you update your gems there's a good chance the problem will go away.
UPDATE
After further research it looks like pry-remote and pry-byebug do not work well together on Ruby 2.x.
However, there is a bit of code a coder posted, most of the comments are in Japanese, but they claim it makes pry-remote work. I'm including their code below (I've translated the Japanese as well):
module ObjectUtils

  # remote parameter is the ip address, default port is 9876
  def pry!(remote=nil, port=9876)
    $LOAD_PATH.unshift "#{ENV['RUBY_PATH']}/debuger"
    require 'pry'
    return if __callee__ == :pry1 and !Pry.instance_variable_get(:@pry_is_start)

    Pry.instance_variable_set(:@pry_is_start, true)

    # if defined? Pry and defined? PryStackExplorer and Pry.config.hooks.hook_exists? :after_session, :delete_frame_manager
    #   Pry.config.hooks.delete_hook :when_started, :save_caller_bindings
    #   Pry.config.hooks.delete_hook :after_session, :delete_frame_manager
    # end
    if remote or ENV['USE_PRY_REMOTE']
      if defined? PryNav
        if defined? ActionDispatch # rails application.
          if Pry.initial_session?
            warn '[0m[33mloading pry remote ...[0m'
            binding.of_caller(1).remote_pry(remote, port)
          end
        else
          binding.of_caller(1).remote_pry(remote, port)
        end
      else
        require_remote_debugger
        binding.of_caller(1).remote_pry(remote, port)
        `notify-send -t 5000 -- "exiting pry remote ..."` if find_executable 'notify-send'
      end
    else
      # if these constants are defined then you're already in a debugger session
      if defined? PryByebug or defined? PryDebugger or defined? PryNav
        if defined? ActionDispatch # rails application.
          if Pry.initial_session?
            # When sending a new request, it will reset Pry.initial_sesssion? It is true.
            # This ensures that, in the same request the debugger will be activated once.
            # Only on the next request will it be reinitialized
            warn '[1m[33mloading debugger ...[0m'
            binding.of_caller(1).pry
          end
        else
          binding.of_caller(1).pry
        end
      else
        require_debugger
        binding.of_caller(1).pry
      end
    end
  end

  def require_debugger
    case RbConfig::CONFIG['ruby_version']
    when '2.0.0'...'3.0.0'
      require 'pry-byebug'
    when '1.9.0'...'2.0.0'
      require 'pry-debugger'
    end
    # to make sure the debugger is loaded
    warn '[1m[33mloading debugger ...[0m'
    require 'ap'; AwesomePrint.pry!
  rescue LoadError
    require 'pry-nav'
    warn '[1m[33mloading debugger ...[0m'
  end

  def require_remote_debugger
    require 'pry-remote'
    require 'pry-nav'
    warn '[0m[33mloading pry remote ...[0m'
    `notify-send -t 10000 -- "loading pry remote ..."` if system 'which notify-send &>/dev/null'
    require 'ap'; AwesomePrint.pry!
  end

end

Kernel.send(:include, ObjectUtils)
Object.send(:include, Kernel)

You'll need to call these methods, and might need to tweak them for your usage.

References

https://github.com/Mon-Ouie/pry-remote/issues/58
https://github.com/Mon-Ouie/pry-remote/issues/35#issuecomment-20290739
https://github.com/deivid-rodriguez/pry-byebug/issues/33
https://rubygems.org/gems/pry-byebug
Comment: Dear, Thank you for your response I've updated all my pry related gems. But no difference, please notice my Note 1!
Comment: Thanks. Answer updated. When you've already done research on a topic, please post it in your question so we can see your work without us all having to start over.
Comment: I have also tried all versions of pry-remote and pry-nav and pry-byebug on ruby 2.2.3 and none of them work. My guess is that the problem is that current frame that pry-nav and pry-byebug think they are at is actually the frame that pry-nav starts the drb listener. I am continuing to dig and will report back if I find anything. If you don't hear from me send a search party. It seems that everyone who has gone down this rabbit hole with pry-remote on ruby 2.x has never come back :(


SQL Fact table-dimension

Question: LARGE RESOLUTION (click here)

How can we put to the fact table called Patent a foreign key for the primary key of the Inventor table (InventorID) preserving the right connection of the tables as noted by the relation between the primary key of the table Patent called Patent and its foreign key Patent of the table Inventor.
We are doing this to create a dimension using the inventor table for the fact table patent.
Answer: Your problem is that you have a many-to-many relationship between patents and inventors.  You cannot readily implement this with a simple snowflake schema.
Basically, you need to introduce a new table at the patent-inventor level, to handle the many-to-many relationship between these entities.
You can think of this in two ways.  The first is that you have a star flake schema with a fact table at a new level, patent-inventor.  The patent and inventor levels are then dimensions off of this table.
The second is as a multiple fact tables, with the patent-inventor table connecting them.
What is important is that other dimensions that may be common to both patent and inventor are shared -- dimensions such as time and geography.
Comment: Another question. The inventorid attribute didn't exist at first. We created it in order to have a primary with unique values in the table Inventor. Now, we want the inventorid attribute to have a role as a primary key in the inventor table and the foreign key in the patent and fill with unique values. How can we do this? Peace
Comment: For a many-to-many relationship, you can't do this.  Patents have multiple inventors.  You need a mapping table with the keys , .

SQL Fact table-dimension


Subgroup of an abelian group isomorphic to a given quotient group

Question: STATEMENT: Let $H$ be a subgroup of a finite abelian group $G$. Show that $G$ has a subgroups that is isomorphic to $G/H$.
QUESTION: Could someone offer a proof using dual groups. I have found one use the fundamental theorem of finitely generated abelian groups, but I cannot seem to find on using dual groups.
Answer: Let $S^1$ be the circle group.  Consider the exact sequence:
$$0\to H\to G \to G/H \to 0$$
Applying the functor $\operatorname{Hom}(-,S^1)$, we get another exact sequence:
$$0\to \operatorname{Hom}(G/H,S^1) \to \operatorname{Hom}(G,S^1) \to \operatorname{Hom}(H,S^1)$$
Now, it so happens that $\operatorname{Hom}(G,S^1) \cong G$ for a finite abelian group $G$—though I don't know if there's a good way to prove that without using the fundamental theorem.  But if you accept it, then this sequence gives us a (non-canonical) injection $G/H\to G$.
Comment: @S.Sheng The point is that $S^1$ has a unique cyclic subgroup of every finite order.  So if $G$ is a finite cyclic group, say $G\cong \mathbb{Z}/n$, then $nG = 0$ so $\operatorname{Hom}(G,S^1) \cong \operatorname{Hom}(\mathbb{Z}/n,\mathbb{Z}/n) \cong \mathbb{Z}/n$.  We then extend this isomorphism to all direct sums of finite cyclic groups.  But the fact that every finite abelian group is a direct sum of cyclic groups is basically the fundamental theorem.  There cannot be a canonical isomorphism (as there is no canonical section of $G\to G/H$).
Comment: @S.Sheng Oh, and the only thing that's really important about all the functor business it that if $A\to B$ is a surjection, then $\operatorname{Hom}(B,C)\to \operatorname{Hom}(A,C)$ is an injection (for any $C$).  This can be proved directly.
Comment: I'm not too familiar with the circle group or functors. Do you mind showing the isomorphism Hom$(G,S1)≅G$
Comment: Got it. Thanks!


Ways of merging two incomparable sorted lists of elements keeping their relative ordering

Question: Suppose that, for a real application, I have ended up with a sorted list A = {$a_1, a_2, ..., a_{|A|}$} of elements of a certain kind (say, Type-A), and another sorted list B = {$b_1, b_2, ..., b_{|B|}$} of elements of a different kind (Type-B), such that Type-A elements are only comparable with Type-A elements, and likewise for Type-B.
At this point I seek to count the following: in how many ways can I merge both lists together, in such a way that the relative ordering of Type-A and Type-B elements, respectively, is preserved? (i.e. that if $P_M(x)$ represents the position of an element of A or B in the merged list, then $P_M(a_i)<P_M(a_j)$ and $P_M(b_i)<P_M(b_j)$ for all $i<j$)
I've tried to figure this out constructively by starting with an empty merged list and inserting elements of A or B one at a time, counting in how many ways each insertion can be done, but since this depends on the placement of previous elements of the same type, I've had little luck so far. I also tried explicitly counting all possibilities for different (small) lengths of A and B, but I've been unable to extract any potential general principle in this way.
Comment: http://math.stackexchange.com/questions/6801/how-do-i-determine-the-possible-number-of-combinations-of-two-ordered-sets
Answer: The merged list has length $|A|+|B|$. Once you know which $|A|$ positions in it are occupied by the elements of list A, you also know exactly how the whole thing has to be ordered, since the internal orders of the elements of A and the elements of B are already known. Thus, there are $$\binom{|A|+|B|}{|A|}=\binom{|A|+|B|}{|B|}$$ possible merged lists, one for each choice of $|A|$ positions for the elements of list A.
Comment: @BryanPendleton: Yes: it's a [multinomial coefficient](https://en.wikipedia.org/wiki/Multinomial_theorem#Multinomial_coefficients), $$\binom{|A_1|+|A_2|+\ldots+|A_N|}{A_1,A_2,\ldots,A_N}\,,$$ which can be expanded as a product of binomial coefficients as shown at the link.
Comment: Great answer! I've made an impl in C++ that generates all possible interleaved combinations of two lists, while maintaining relative order for anyone who is interested: https://github.com/domfarolino/algorithms/tree/master/src/algorithm_practice/Combinatorics/interleaveOrderedLists
Comment: Can this further generalize to 3 lists? To 4? To N?
Comment: Indeed, I believe this can further generalize to N lists, by viewing the overall operation as a series of (N-1) merges, so the total number of merged lists is computed as the product of (N-1) Binomial Coeffecients, where the i-th expression computes the selection of the positions of the i-th lists's elements from the available positions left after the first (i-1) lists have already been merged.
Comment: Great answer. Since we have to keep the relative ordering. This question is equal to "How many different ways are there to select n positions from m + n positions?"
Answer: $\frac{(m+n)!}{(m)!(n)!}$;
where m,n is the length of the arrays.
$(m+n)!$ is the total number of ways of arranging without any restriction.
The condition given that you can not change the order of each array so you should not change the order of each array , so we need to divide all the permutations of each array!
Answer: For merging N sorted lists, here is a good way to see that the solution is $$\frac{(|A_1|+\dots|+|A_N|)!}{|A_1|!\dots |A_N|!}$$
All the $(|A_1|+\dots|+|A_N|)$ elements can be permuted in $(|A_1|+\dots|+|A_N|)!$ ways. Among these, any solution which has the ordering of the $A_1$ elements different from the given order have to be thrown out. If you keep the positions of everyone except $A_1$ fixed, you can generate $|A_1|!$ permutations by shuffling $A_1$. Only 1 among these $|A_1|!$ solutions is valid. Hence the number solutions containing the right order of $A_1$ is $$\frac{(|A_1|+\dots|+|A_N|)!}{|A_1|!}$$
Now repeat the argument for $A_2$, $A_2, \dots A_N$.


What is a "flat wrist"?

Question: Bass legend Carol Kaye writes that she uses a "flat wrist" technique when playing bass with a pick.
What does she mean by this?
Answer: It means to not rotate your hand inwards towards your inner arm.  If you look up videos of Eddie van Halen playing some of his solo's, esp. when he's rapidly picking. He often curves his wrist over in a manner that is inappropriate for bass (according to C. Kaye).  Here's a good negative example, with primarily rotational motion (note: I'm only trying to indicate that C. Kaye would frown on this kind of right hand technique for playing bass).  Or here is a longer discussion -- note the emphasis on the rotational motion.
Stick your arm straight out in front of you, palm down, but parallel to the floor.  Now drop your hand at the wrist -- C. Kaye advocates for avoiding this position/motion when playing bass.
Stick your arm straight out in front of you, palm down, but parallel to the floor.  Now rotate like you're turning a doorknob. -- She'd say to avoid this kind of motion in wrist as well.
Stick your arm straight out in front of you, palm down, but parallel to the floor. Now rotate your hand left and right at the wrist while keeping the palm parallel to the floor.  This is the primary wrist motion that C. Kaye advocated;
she believes that the wrist is in a sense strongest in direction of motion, and allowing other aspects of motion (curving inward or rotating the forearm) are liable to lead to injury.
Here's a reasonable example of her playing -- note that the primary motion is as I've described, although there are a few points where she uses some fore-arm rotation type of motion to get extra pull on some of the notes, particularly up-strokes..

What is a "flat wrist"?


How to put icon in field label?

Question: Is it possible to add an icon in front of a field name?
I have a field name called Tel and would like to put a phone icon in front of it?
I've searched for a while and can't seem to find an answer to this.
Comment: Use css, you can check here same question: http://drupal.stackexchange.com/questions/150802/adding-icons-to-field-labels
Comment: Thank you for your answer... I am very new to Drupal so forgive me if Im asking obvious questions.. Would I just put this into my css so? #field-name {
  background-image: url('image/path/ico_phone.png');
  background-repeat: no-repeat;
  background-position: left center;
  padding-left: 16px;
}
Comment: Or do I need to do anything else?
Answer: Use Font Awesome classes to add the icons for the field label.
Comment: I have downloaded Font Awesome, however, it only lets me add icons in the body of the text and not in the label name of my content type. Is there a certain way I can add it to the label using Font Awesome?
Comment: let me know you want to chaneg the label of field for admin panel and front end both.
Comment: Yes I want to change it for both.
Comment: @Karuna details please

How to put icon in field label?


Reconstructing a string manipulated with bitwise operations

Question: Suppose I have a Java string of length 32, e.g.
String s = "Y7yEdfjQ2qmpGZbPYswKIdxYVo6KnR9M";

I'm looking for the string t with the following property: If the following loop is performed on t, the resulting string is s:
char[] tArr = t.toCharArray();
for (int i = 1; i < 32; i++) {
    tArr[i] = (char) (tArr[i] ^ tArr[i * 123456 % 31] & 31);
}

Note that in Java the array operator [] has highest precedence and bitwise AND is evaluated before bitwise XOR.
In order to obtain t the reverse operation must be applied to s. The inverse operation of XOR is XOR, however the logical AND obviously has no inverse operation.
Can the string t be recovered short of bruteforcing?
Answer: 31 is 11111b
so the algorithm takes lowest 5 bits of any char, which gives you no option to recover the initial string - you may find out some string which leads to the same hash
and the brute-force is the only option here
Comment: I believe you mean 31 is 0b11111 (and 0x1F)?
Comment: yeah, really, I probably thought about something else.
Answer: Your loop takes in each iteration two chars, and xors the first char with the lowest 5 bits of the other char. That means that the top 3 bits remain unchanged. They don't get lost. In fact the top 3 bits of t[i] are equal to the top 3 bits of s[i], and we only have to find the lowest 5 bits of the characters in the original string t.
Now, lets calculate i * 123456 % 31, and see what the loop actually does in each iteration :
t[1] = t[1] ^ (t[14]&31)
t[2] = t[2] ^ (t[28]&31)
t[3] = t[3] ^ (t[11]&31)
t[4] = t[4] ^ (t[25]&31)
t[5] = t[5] ^ (t[8]&31)
t[6] = t[6] ^ (t[22]&31)
t[7] = t[7] ^ (t[5]&31)
t[8] = t[8] ^ (t[19]&31)
t[9] = t[9] ^ (t[2]&31)
t[10] = t[10] ^ (t[16]&31)
t[11] = t[11] ^ (t[30]&31)
t[12] = t[12] ^ (t[13]&31)
t[13] = t[13] ^ (t[27]&31)
t[14] = t[14] ^ (t[10]&31)
t[15] = t[15] ^ (t[24]&31)
t[16] = t[16] ^ (t[7]&31)
t[17] = t[17] ^ (t[21]&31)
t[18] = t[18] ^ (t[4]&31)
t[19] = t[19] ^ (t[18]&31)
t[20] = t[20] ^ (t[1]&31)
t[21] = t[21] ^ (t[15]&31)
t[22] = t[22] ^ (t[29]&31)
t[23] = t[23] ^ (t[12]&31)
t[24] = t[24] ^ (t[26]&31)
t[25] = t[25] ^ (t[9]&31)
t[26] = t[26] ^ (t[23]&31)
t[27] = t[27] ^ (t[6]&31)
t[28] = t[28] ^ (t[20]&31)
t[29] = t[29] ^ (t[3]&31)
t[30] = t[30] ^ (t[17]&31)
t[31] = t[31] ^ (t[0]&31)

We know that after the final iteration, the array has been transformed from t (which we don't know) to s (which we know - "Y7yEdfjQ2qmpGZbPYswKIdxYVo6KnR9M").
Now, since t[0] is never modified, we know that s[0]=t[0]='Y' (or 01011001 in binary).
This gives us t[31] easily :
t[0]&31 = 00011001
s[31] = 'M' = 01001101 = t[31] ^ 00011001

xor both sides, and get :
t[31] = 01001101 ^ 00011001 = 01010100

The other characters are less easy.
The iterations of the loop form two cycles :
1->14->10->16->7->5->8->19->18->4->25->9->2->28->20->1

3->11->30->17->21->15->24->26->23->12->13->27->6->22->29->3

Now, lets try finding other characters of t :
t[30] = t[30] ^ (t[17]&31)
after this assignment, t[30] becomes s[30], i.e. '9' or 00111001.
We know that 001 11001 = 001 ????? ^ 000 xxxxx
Where ????? are the lowest 5 bits of t[30] and xxxxx are the lowest 5 bits of t[17]. But actually, it's not the original t[17]. By the time we assign t[30], t[17] has already been updated to its final value, which we know (it's s[17] - 's' or 01110011).
Therefore 001 11001 = 001 ????? ^ 000 10011.
And if we xor both sides, 001 11001 ^ 000 10011 = 001 01010
so the original t[30] is 00101010.
So far I found t[0],t[30] and t[31].
I believe (though I haven't actually checked), that I can go on and find all the other characters of t this way.
The important thing to pay attention to when we calculate t[i] is that if t[i] depends on t[j] such that i<j, it depends on the original value of t[j] (the unknown), while if i>j, it depends on the final value of t[j] (which is s[j] - which we know).
Comment: That's really nice explanation, but since it really cuts things down to 5 bits allowed - then it's not possible to decrypt it in real life. However for some edicational purpose, considering letters to be encoded from 1 to 26 - that *might* be possible to resolve it back. Thanks!
Comment: @jdevelop But as I explained, it doesn't cut things to 5 bits. you have `tArr[i] = (char) (tArr[i] ^ tArr[i * 123456 % 31] & 31)`, which to simplify we can write as `t[i]=t[i]^t[j]&31`. Since the AND is evaluated before the XOR, you are XORing t[i] with the low 5 bits of t[j]. That means that the top 3 bits of t[i] remain unchanged, and therefore they are not lost, and you only have to find the 5 lowest bits, and I showed how to do that.
Comment: I missed the point of priority of logical operators, true. I believe that in this case the reversing is quite possible, because, let's see for the "terminal" case (last symbol):

- a[i] = 238
- a[j] = 11

so applying the same function

229 ^ 11 & 31

it will give us 238.

Applying it back:

238 ^ 11 & 31

And that's it
Comment: I had followed the same line of thought but discarded it because of a mistake in my calculation. I wish I could upvote you twice, Eran!
Comment: @lpradel Glad I could help! It was an interesting question


Theme's css and js files are not being loaded

Question: I was trying to create a theme for Drupal 8.1.8. My CSS and JS files unfortunately cannot be loaded. I have checked if I used any tab characters, but I have used always 2 space characters for an indent.
I have read the documentation page at Drupal.org: https://www.drupal.org/theme-guide/8/assets. I was trying around 2 hours with all possible combination. Also I tried the google search, Drupal core code inspection.. I could not figure it out.
My theme is located at themes/englishtrainer. The css is located in themes/englishtrainer/css and the javascript files are in themes/englishtrainer/js. The theme can be enabled as a theme without problems.
The contents of my theme's files in the following.
englishtrainer.info.yml:
name: Englishtrainer
type: theme
version: 8.x-1.0
core: 8.x
package: Custom
# Scripts & Styles
libraries:
  - englishtrainer/global-styling

englishtrainer.libraries.yml:
global-styling:
  version: 1.x
  css:
    theme:
      css/css-test.css: {}
  js:
    js/js-test.js: {}

css/css-test.css:
body {
    background-color: red;
}

js/js-test.js:
alert('it is loaded!');

I was checking the html markup for any occurrences. The javascript console has been also checked. It does not contain any entries.
Do you have any idea?
Answer: englishtrainer.info.yml:
name: Englishtrainer
type: theme
core: 8.x
version: '1.0.0'
libraries:
  - englishtrainer/base
regions:
  header: Header

No need for package
englishtrainer.libraries.yml:
base:
  version: VERSION
  css:
    theme:
      css/css-test.css: {}
  js:
    js/js-test.js: {}

Use base to start things off and the VERSION keyword will take the version info from englishtrainer.info.yml.
Comment: As you can see here https://www.drupal.org/developing/api/8/assets base is a key name. So using base as the library name, could cause some conflict (have not tested), change base to something else on both files and try again, maybe that's the prob.
Comment: And don't forget to KCCC (Keep Calm Clear Cache) after you make changes to these files.
Comment: Thanks LittleCoding for your quick answer. Unfortunately it does not solve the issue. I was using exactly the same code you have provided, enabling, re-enabling the theme, clearing the cache via Drush and Drupal itself. There was no change. I have added "content: Content" to the regions, because otherwise Drupal was not allowing me to enable the theme. Do you have any further ideas?
Comment: Did u try configuration->development->performance->bandwidth optimization-> and uncheck aggregate css and js files and save configuration then clear cache @jepster
Comment: Try to add dependencies:
    - core/jquery
    - core/drupalSettings
Answer: Solved it. My issue was, that I had a theme "and" a module with the same name. However the module did not implement any theming components. But this broke the theme. After I have uninstalled the module with the same name, the background was red (css worked) and the javascript alert appeared (javascript worked).
Thank you for your attention.