Funcionamento da função free() em tipos abstratos

Question: Eu esperava que o seguinte código registrasse os dados dos alunos, e logo em seguida apagasse da memória:
testeTurma.c
#include "aluno.h"
#include <stdlib.h>

int main(){
    aluno *turma;
    turma = malloc(3*sizeof(aluno));

    turma[0] = regAluno("Joao",123,7.0,5.0);
    turma[1] = regAluno("Maria",124,8.0,6.0);
    turma[2] = regAluno("Jose",163,6.0,5.0);

    for(int i = 0;i<3;i++) exibeAluno(turma[i]);

    free(turma);

    //Aqui eu esperava ou exibir lixo de memória, ou dar erro e abortar
    for(int i = 0;i<3;i++) exibeAluno(turma[i]);

    return 0;
}

Mas eu obtenho a seguinte saída:
Nome: Joao,   Matr.: 123,   Media: 6.00
Nome: Maria,   Matr.: 124,   Media: 7.00
Nome: Jose,   Matr.: 163,   Media: 5.50
Nome: (null),   Matr.: 123,   Media: 6.00
Nome: Maria,   Matr.: 124,   Media: 7.00
Nome: Jose,   Matr.: 163,   Media: 5.50

Ou seja, só apagou a primeira propriedade da struct aluno que foi reservada na primeiro espaço de memória, alguém poderia me explicar como a função free() realmente funciona, e como posso liberar todo espaço de memória alocado?
Resto do código:
aluno.c
#include "aluno.h"
#include <stdlib.h>
#include <stdio.h>

aluno regAluno(char *nome,int matricula, float nota1,float nota2){
    aluno a;
    a.nome = nome;
    a.matricula = matricula;
    a.nota1 = nota1;
    a.nota2 = nota2;
    a.media = (nota1+nota2)/2;

    return a;
}

aluno *criaPontAlunos(int size){
    aluno *p;
    p = malloc(size*sizeof(aluno));

    return p;
}

void exibeAluno(aluno a){
    printf("Nome: %s,   Matr.: %d,   Media: %.2f\n",
    a.nome, a.matricula, a.media);
}

aluno.h
#ifndef ALUNO_H
#define ALUNO_H

typedef struct{
    char *nome;
    int matricula;
    float nota1;
    float nota2;
    float media;

} aluno;

aluno regAluno(char *nome,int matricula, float nota1,float nota2);
aluno *criaPontAlunos(int size);
void exibeAluno(aluno a);

#endif

Comment: Poderia mostrar a estrutura do struct aluno?
Comment: Precisa ver o que está querendo fazer porque isto está bem errado, para te dar uma solução só sabendo que precisa, não é só erro no `free()`.
Comment: @G.Bittencourt  typedef struct{
    char *nome;
    int matricula;
    float nota1;
    float nota2;
    float media;

} aluno;
Comment: Conforme o link [inserir a descrição do link aqui](https://www.ime.usp.br/~pf/algoritmos/aulas/aloca.html) bastava realizar o free(turma).
Answer: Acredito que tem mais problemas nesse seu código - sem ver a função regAluno não dá pra dizer exatamente o quê (de repente até funciona).
Mas sobre a função free: ela marca a memŕoia como livre para o sistema operacional - inclusive para partes do seu próprio programa que são "pilotadas" por trechos de código criados pelo compilador C e pelas bibliotecas usadas - você não tem controle sobre os mesmos.  A chance é que isso é o que esteja ocorrendo: a memória é re-utilizada pelo seu próprio programa (lembrando, de forma automática), para alocação da própria variável i do segundo for. Declare o int i no começo da função em vez de em cada  for e você deve ver uma mudança no comportamento aí.
Mas o que é importante para você lembrar ela não faz é "zerar" a área da memória liberada: todos os seus dados continuam no mesmo lugar, exceto um marcador logo no começo ali. Então, programas que tem dados sensíveis na memória- sobretudo se vão rodar em um servidor compartilhado, tem que tomar cuidado para zerar explicitamente esses dados sensíveis antes de liberar a memória. Isso pode dar bastante trabalho, uma vez que em linguagens de aplicações "reais" pra web e banco de dados, se tem pouco controle direto sobre a memória, como é possível ter em C. (E de qualquer forma, as falhas na arquitetura atual de CPU com o nome de "Spectre" e "meltdown" mostraram que mesmo com o programa em execução e acesso teóricamente exclusivo à  memória, esses dados podem vazar: segurança é um trabalho ingrato).
Sim - esse programa poderia dar erro por "violação de acesso" - e é provável que se você insistir em ficar executando algo desse tipo, vai conseguir um erro desses de vez em quando. Mas o sistema operacional não dedicou essa área alocada para outro processo de imediato, e não deu uma "falha de acesso" - nesse caso. Interessante pra você ver que os dados continuam na memória.
A critério de varios fatores inclusive: do seu sistema operacional, e do compilador, pode ser que trechos pequenos de memória sejam reutilizados dentro de um mesmo espaço do processo, daí você não tem esse erro ocorrendo. Mas a razão de isso não ser documentado com mais transparência é simplesmetne que você não deve utilizar essa memória depois do free.
Então: sim - parabéns pela inciativa de realizar a experiência, e perguntar quando não entendeu. E sim, a resposta correta continua sendo a resposta teórica: isso está errado, e chance do programa parar de repente é muito grande.
(Se você tivesse colocado o código completo do programa eu compilaria e executaria aqui - como é um sistema diferente do seu, provavelmente o resultado seria uma violação de acesso e encerramento do programa).
Comment: obrigado pela ótima resposta, poderia me informar como posso colocar formato de código nos comentários?
Comment: Creio que não é possível comentar códigos formatados, mas você pode editar sua postagem.
Comment: feito, no inicio eu estava utilizando a função criaPontAlunos() para alocar, mas com o problema tentei direto, o que não mudou muito
Answer: Nelson,
faça o seguinte teste:
for(int i = 0;i<3;i++)
{
    free(turma[i]);
}

for(int i = 0;i<3;i++)
    exibeAluno(turma[i]);

Comment: fiz isso logo que vi o erro e nem compila ----

testeTurma.c:14:10: error: incompatible type for argument 1 of 'free'
     free(turma[0]);
Comment: turma[0] não é um ponteiro, logo não pode usar o free( ).


AMQP Library not loading for apache2, ubuntu 14.04

Question: I am trying to install Rabbit MQ and the php library AMQP on Ubuntu 14.04, but am receiving an error upon apache start (in apache error log)
PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/lib/php5/20121212/amqp.so' - /usr/lib/php5/20121212/amqp.so: undefined symbol: amqp_error_string2 in Unknown on line 0

And AMQP does not start.
I followed this: https://github.com/pdezwart/php-amqp/issues/87
And...
locate librabbitmq.so

returns:
/usr/lib/librabbitmq.so.0
/usr/lib/librabbitmq.so.0.0.0

ls -al librabb* returns:
/usr/lib/librabbitmq.so.0 -> librabbitmq.so.0.0.0  (root / root)
librabbitmq.so.0.0.0 (root / root)

In /user/local/lib there is also:
librabbitmq.so -> /usr/lib/librabbitmq.so.0 (root / root)

Permissions are root/root and 755 on all.
Any help, most appreciated.
Thanks
Comment: It is hard to guess what problem exactly do you have while you didn't provide any software versions. To give the first aid, just check that you have the latest librabbitmq library - since php-amqp>=1.3.0 rabbitmqp should be >= 0.4.1.
Comment: Thanks for the reply. 'rabbitmqctl status' returns RabbitMQ version 3.2.4. Let me know if you need anything else?
Answer: Installing amqp via pecl didn't worked for me so i had to compile the RabbitMQ C AMQP client library and pecl amqp myself.
RabbitMQ C AMQP Client library can be found at https://github.com/alanxz/rabbitmq-c/
and Pecl amqp from http://pecl.php.net/package/amqp .
Here is a list of commands that should do the trick on ubuntu 14.04:
#create a directory for sources
mkdir ~/kit
cd ~/kit

#download and install the rabbitmq c amqp lib
wget https://github.com/alanxz/rabbitmq-c/releases/download/v0.5.1/rabbitmq-c-0.5.1.tar.gz
tar -zxvf rabbitmq-c-0.5.1.tar.gz
cd rabbitmq-c-0.5.1/
./configure
make
sudo make install

cd ..

#download and compile the amqp
wget http://pecl.php.net/get/amqp-1.4.0.tgz
tar -zxvf amqp-1.4.0.tgz
cd amqp-1.4.0/
phpize && ./configure --with-amqp && make && sudo make install

#Add amqp extension to php mods-availabile directory
echo "extension=amqp.so" > /etc/php5/mods-available/amqp.ini

#Enabled it in cli
cd /etc/php5/cli/conf.d/
ln -s ../../mods-available/amqp.ini 20-amqp.ini
php -m | grep amqp

#Enabled it in cli
cd /etc/php5/apache2/conf.d/
ln -s ../../mods-available/amqp.ini 20-amqp.ini

#restart Apache and than check phpinfo on web
service apache2 restart


Ping hostname works but nslookup to hostname doesn't

Question: I have a Windows 2008 standard server which can ping by hostname and give me the proper IP address back however if I try to do an nslookup on the hostname I receive:
server: nmgdc1.nmg.local
Address 192.168.1.10
DNS request timed out. timeout was 2 seconds.
DNS request timed out. timeout was 2 seconds.
*** Request to nmgdc1.nmg.local timed-out

I can get to the website fine through a web browser and can do a successful nslookup from a different client. Any ideas?
Answer: As people have been pointing out your DNS server on 192.168.1.10 is not setup correctly or is not the right DNS server.
However the name can still be resolved by windows, probably using what is called NetBIOS over TCP/IP that works like an automatic DNS server system with auto server discovery on a LAN but doesn't scale well and is a bit hit and miss on it actually working.
Answer: Check the DNS Server entries on the problematic host. Chances are, it's not using the same DNS server as everything else that's working correctly.
Comment: I have 1 server and 3 computers at this location and none of them can do an nslookup on the website however from some of my other clients that I manage I can nslookup fine... the server nmgdc1 is my actual DNS server...
Answer: If none of the machines on you LAN can complete a nslookup, then it's likely your local DNS can't resolve the hostname properly. It could be an issue with your DNS server, or with just the records for that host.
I would try to nslookup other local hosts, to see if the LAN DNS is functioning. You could also try to nslookup the hostname in question on a public DNS i.e. nslookup targetHost 188.8.131.52 (openDNS), though it sounds like public resolution is working fine.
Comment: If i do a nslookup targethost 188.8.131.52 than I get the proper IPs back. If I try to a local IP address on the network I get: Server: nmgdc1.nmg.local Address: 192.168.1.10 | *** nmgdc1.nmg.local can't find 192.168.1.150: Non-existent domain.
Comment: Another thing I found is for some reason the server keeps adding a forwarder of 10.100.1.10 even though my ip address is 192.168.1.10. I deleted the forwarder and it seems to re-add itself some how...
Answer: This article is from the Windows 2000 TechNet, but the principles and actions should still apply. It's got great troubleshooting and workflow steps to help you identify DNS resolution issues. Keep in mind, nslookup is kind've a PITA if reverse zones aren't established.
Answer: I feel like your DNS server is not properly set up on the .10 address. My guess is that your TCP/IP stack is using multiple DNS servers and one of them has pointed to the outside world. Go back and reconfigure your .10 address to your outside DNS servers.


Override a node page using page manager

Question: I know it is possible to override node pages using page manager, then use panels to make new layout by selecting a variant type, and  creating a new variant.
Is it possible not to use the Panels mdoule? I would like to use the Context module, and the default theme regions.
Comment: I'm not sure I understand what you are trying to achieve. What do you expect Ctools will do for you when you override the node-template, if you are going to use Context? That doesn't make sense.
Comment: You should try display suit module as well.
Answer: Yes it is possible to use only context module to override layout.

When you first add context @ admin/structure/context/add, you need to select condition as "path" and reaction can be whatever you want. For ex. choose reaction as "Regions" and then go ahead disable region for the sleected "path" (the one you chose above in condition).

Just remember context module will use your existing theme layout and regions (.tpl.php files) unlike in panels where it allows you create your own regions and layout.

Override a node page using page manager


Finding the spectral decomposition of a given $3\times 3$ matrix

Question: I am trying to find the spectral decomposition of the following matrix:
$$
A=\begin{pmatrix}
4 & 0 & 0\\
0 & 2 & 0\\
2 & 3 & 0\\
\end{pmatrix}
$$
So I found the eigenvalues which are $\lambda_1 = 0, \lambda_2=2, \lambda_3=4$ and the eigenvectors for them $v_1 = \begin{pmatrix}0\\0\\1\\\end{pmatrix}, v_2 =\begin{pmatrix}0\\2\\3\\\end{pmatrix},v_3 =\begin{pmatrix}2\\0\\1\\\end{pmatrix}$ correspondingly.
Now from what I understood, I should normalize the vectors above like that:
$$
q = \frac{v}{||v||}
$$
And calculate this: $\lambda_1q_1q_1^T+\lambda_2q_2q_2^T+\lambda_3q_3q_3^T$
However, when I do that the answer is not the matrix $A$ from above, but another one. Shouldn't the spectral decomposition be equal to the matrix ?
I don't know what I'm doing wrong, I have checked the eigenvalues and vectors many times I can't find what's wrong with this.
Any help is appreciated, thank you :D
Comment: @Tannous If someone asked for a "spectral decomposition" of this matrix, they're probably referring to a decomposition of the form $A = PDP^{-1}$, i.e. the "usual" diagonalization of a matrix.
Comment: If you were decomposing a symmetric matrix, then the eigenvectors would (for distinct eigenvalues) be orthogonal.  However this matrix is not symmetric and the eigenvectors are not orthogonal.
Comment: @hardmath, thanks for answering. How am I suppose to find the spectral decomposition in that case then? Am I suppose to do some manipulation the matrix?
Comment: See for the terminology "eigendecomposition" meaning diagonalization ("sometimes spectral decomposition") in the [Wikipedia writeup](https://en.wikipedia.org/wiki/Eigendecomposition_of_a_matrix).
Answer: The technique you use: $$\lambda_1q_1q_1^T+\lambda_2q_2q_2^T+\lambda_3q_3q_3^T$$ is only true for a symmetric matrix. You can easily check that the result of such a calculation will always be a symmetric matrix by taking the transpose operator.
The general technique is to form the matrix with columns that are your eigenvectors:
$$P=\begin{pmatrix}v_3&|& v_2&|&v_1\end{pmatrix}= \begin{pmatrix}2&0&0\\0&2&0\\1&3&1\\\end{pmatrix}$$
and calculate its inverse with your favorite method (for example Gauss elimination with pivoting).
In this case, you should get: $$P^{-1}=\begin{pmatrix}\frac{1}{2}&0&0\\0&\frac{1}{2}&0\\-\frac{1}{2}&-\frac{3}{2}&1\\\end{pmatrix}$$
Then you will have $$A=P\begin{pmatrix}\lambda_3&0&0\\0&\lambda_2&0\\0&0&\lambda_1\\\end{pmatrix}P^{-1}$$
Note that the order you use for the columns of P need to be the same as the order for the diagonal matrix.


styling in react native

Question: I am involved in a project that several people working on a react native project.
I need to find a way to separate the styling tasks form code, in a way that UI develop can work without the need of code developer (from my point of view, a style is a person who define the structure of UI, place components on screen and also define their color and visual representation).
my questions are:

Is there any tools that the style developer can use to create styles and export suitable files for inclusion to  project?
How can I make sure that the two team work without duplicating their work by other team? I came from a WPF and Web development, and in that systems, there is a good separation between the UI and codes. For example, In MVVM, the only agreement that stylist and coder should have is the name of component, and the stylist can make all of the styles and coder can do all of the coding without repeating their work (I know that this is over simplified, but the concept is there and a good team can use it). In a web development, stylist create the HTML and CSS, and the coder use angolarJS or JQuery to control the component and attach to their events.
In our styling team we are using skitch, can this tool generate suitable style code for react native? If yes, what would be the workflow?
Any other suggestion on how best to separate styling from coding in react native.
Comment: There are tools like BuilderX.io that aim to do this. Posting this as a comment instead of answer, because I haven't really used in and can't recommend it out of experience.
Answer: I don't have the best answer for this question, But I can provide you some feedback & tips from my experience.
For separating UI & Business code like in MVVM, you can separate the classes as

Container class (handles all business logic) and
View class (Only responsible for presentation) with styles defined as a separate class that can make use of some universal theme provider

There can be multiple view classes (iOs, Android , if possible Web) but all them will use the main container class for business logic (REfer 1st link for more details)
Refer:

https://blog.cloudboost.io/react-native-a-deep-dive-part-1-5a982f847d20
https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0

For styling you can opt for some Theme Provider classes that will hold universal themes as an object. The coder can use these styles in the components. The main theme will be defined in the root class with the provider. If you are carefully reusing these styles, you only need to update the styles in one place updating all of them. Also there is support for dark & light themes.
Refer:

https://github.com/callstack/react-native-paper
https://github.com/xinthink/react-native-material-kit
https://github.com/xotahal/react-native-material-ui

styling in react native


Type complex vs two level

Question: I am conducting a cfa (two level, with meaning of level 2;it is staff rating organizations and we care about organizations).
My question is what is the difference is in mplus between type=complex (mlr with sandwich) and type=twolevel if mlr is selected as an estimator with no covariates in the model?
These should be the same corrct?
Answer: If you care about the organizations (the clusters), then use type=twolevel and estimate a within and a between part of your model.
If you were not concerned about the clustering level but wanted to control for within-cluster correlation (you should do that), you would use type=complex to make Mplus use a sandwich estimator.
These two solutions are different in that they will estimate different models (two-level vs single level), and you can expect that they will produce different results for the within part (which would be the only part estimated if you use type=complex model).

Type complex vs two level


PrimeFaces' Photocam : Showing Captured Image

Question: I'm trying to replicate the example of https://www.primefaces.org/showcase/ui/multimedia/photoCam.xhtml with a simple variation.
In the example, every taken picture is saved and showed.
But I just need to show the latest one, so I've removed the list references and edited the code a little bit.
So I'm using just the graphicsImage instead of the imageSwitch, and, in the onCapture method I just overwrite the previous image.
But here's the problem.
The new image is correctly taken, I can see it by browsing to its folder, but it won't be updated in the page.
It seems that it still shows the previous cached one, because it works if it's the first one (no file before this take).
Any suggestion?
EDIT:
Here some code.
PrimeFaces JSF
<h:form>

<h:panelGrid columns="3">

        <ui:repeat value="#{photoCamBean.photos}" var="photo">

        </ui:repeat>

</h:panelGrid>

MY JSF

                <f:param name="mode" value="'show'" />

PRIMEFACES BEAN
public void oncapture(CaptureEvent captureEvent) {
    String photo = getRandomImageName();
    this.photos.add(0,photo);
    byte[] data = captureEvent.getData();

    ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
    String newFileName = servletContext.getRealPath("") + File.separator + "photocam" + File.separator + photo + ".png";

    FileImageOutputStream imageOutput;
    try {
        imageOutput = new FileImageOutputStream(new File(newFileName));
        imageOutput.write(data, 0, data.length);
        imageOutput.close();
    }
    catch(Exception e) {
        throw new FacesException("Error in writing captured image.");
    }
}

MY BEAN
public void onCapture(CaptureEvent captureEvent) {
    makeAvatar(captureEvent.getData());
}

private void makeAvatar(byte[] imageData) {
    FileImageOutputStream imageOutput;
    ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
    File imageFile = new File(extContext.getRealPath("NEW//uploaded//temp") + "//" + utente.getUsername() + ".png");
    try {
        if (imageFile.exists()) {
            imageFile.delete();
        }
        imageFile.createNewFile();
        imageOutput = new FileImageOutputStream(imageFile);
        imageOutput.write(imageData, 0, imageData.length);
        imageOutput.close();
        FacesMessage msg = new FacesMessage("Immagine caricata correttamente.");
        FacesContext.getCurrentInstance().addMessage(null, msg);
    } catch (Exception e) {
        FacesMessage msg = new FacesMessage("Errore nel caricamento dell'immagine!");
        FacesContext.getCurrentInstance().addMessage(null, msg);
    }
}

The image is captured and updated in my temp folder, but it won't change in the page.
Even a refresh won't help me.
It changes only after a server restart !
EDIT :
Here's my glassfish-web.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE glassfish-web-app PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 Servlet 3.0//EN" "http://glassfish.org/dtds/glassfish-web-app_3_0-1.dtd">
<glassfish-web-app error-url="">
    <class-loader delegate="true"/>
    <jsp-config>
         <property name="keepgenerated" value="true">
             <description>Keep a copy of the generated servlet class' java code.</description>
         </property>
         <property name="alternatedocroot_1" value="from=/uploads/* dir=/home/stefano/Documenti/UniLife" />
    </jsp-config>
 </glassfish-web-app>

Using Daniel's solution, I should have been able to browse to localhost:8080/Unilife5-war/uploads/avatar/cp99.png to show /home/stefano/Documenti/UniLife/avatar/cp99.png , or I'm getting wrong?
Comment: does this helps, http://stackoverflow.com/a/9674671/617373   ?
Comment: It seems to be the right way, but somehow it doesn't work !
I've added my glassfih-web.xml to the first post.
Answer: Not familiar with glassfish to well... but for a start I'd use the simplest example given by BalusC
PrimeFace update after upload
<property name="alternatedocroot_1" value="from=/uploads/* dir=/var/webapp" />

And use http://localhost:8080/contextname/uploads/* to serve those uploaded images from by

<h:graphicImage> the usual way.

Without other inner folders like

stefano/Documenti/UniLife/avatar/

And have you changed you're bean code ?
File imageFile = new File(extContext.getRealPath("NEW//uploaded//temp") + "//" + utente.getUsername() + ".png");

Comment: Thanks again, but http://localhost:8080/contextname/uploads/ gives me a 404 error. I suppose that _contextname_ is a parameter, but I've tried all the combos without succeding. I'll close this question and I'll open a new one because the subject is changed !
Comment: i thought that contextname meant your web app name localhost:8080/yourWebAppName/uploads isn't it?
Comment: That's what I thought too, but it doesn't work..I've got a file f.txt in /var/webapp and http://localhost:8080/Unilife5-war/uploads/f.txt shows a 404 error !


Counterexample to infinite sum of expectations = sum of infinite expectations?

Question: I am looking for the counterexample to the statement $\sum E[X_n] = E[\sum X_n]$ given that $\sum E[X_n]$ and $\sum X_n$ exist. This would be also a counterexample to the dominated convergence theorem without one of its assumptions with the probability measure; I was able to create a counterexample using Lebesgue integral, but the domain is the entire real so it unfortunately fails.
Comment: The dominated convergence theorem is a theorem.  What do you mean by a counterexample to it?
Answer: Is this the sort of thing you had in mind?
Take Lebesgue measure  on $[0,1]$.
For each positive integer $n$, let $X_n = 2^n$ on an interval of measure $2^{-1-n}$, $-2^{n}$ on an interval of measure $2^{-1-n}$, $0$ everywhere else, where all these intervals are pairwise disjoint (note that the sum of the measures of the
intervals is $1$).  The pointwise sum $\sum_n X_n$ exists (and is finite) everywhere (in fact for any $x$ there is at most one $n$ for which $X_n(x) \ne 0$).  Also each $\mathbb E X_n = 0$, so $\sum_n \mathbb E X_n = 0$.  But $\mathbb E \sum_n X_n$ does not exist because $\sum_n X_n$ is not in $L^1$: $\mathbb E \left|\sum_n X_n\right| = \infty$.
Comment: All $A_i$ and $B_j$ are disjoint.
Comment: all the sets and all the intervals are pairwise disjoint? or do you mean for each n the $set_n$ and the $interval_n$ are disjoint?
Comment: Sorry,, the "set" was meant to be an interval.  I'll edit.
Comment: Is this right? Consider $X_1, X_2, ...$ in $(\Omega, \mathscr F, \mathbb P) = ([0,1], \mathscr B([0,1]), \lambda)$ where

$$X_n = 2^n 1_{A_n} + -2^{n} 1_{B_n}$$ where $\lambda(A_n) = \frac{1}{2^n} = \lambda(B_n)$ and $A_n \cap B_n = \emptyset$
Comment: That's almost what I said (but $2^{-1-n}$ not $2^{-n}$, and all the $A_m$'s and $B_n$'s disjoint, not just for the same $n$).  And yes, it is right.
Comment: Sorry for the confusion, Robert Israel. 1 We have the collection $A = (A_1, A_2, ...)$ to be pairwise disjoint? 2 We have the collection $B = (B_1, B_2, ...)$ to be pairwise disjoint? 3 Is the collection $$A \cup B$$ pairwise disjoint?


Adder delay model in a ripple carry adder.

Question: In section 5.3. of the following book an analysis of carry propagation in the ripple carry adder is performed. However the statistical analysis doesn't particularly convince me. Specifically at the beginning of page 81 it is stated that "The probability that a carry generated at position i will propagate up to and including position $j - 1$ and sto at position  $j(j > i)$ is $2^{-(j-1-i)}\times1/2$".
However my modeling gives me a different result, to be honest the result given by the book is not explained very well, IMHO.
Here is my derivation,
I call $g_i$ the event that a carry is generated at position $i$, $p_i$ the event that a carry is propagated through the position $i$ and $a_i$ the event that it is annihileted. All of these events depend only from $x_i, y_i$ (bits of the input). I have to compute the probability
$$
Pr\left(g_i,p_{i+1},...,p_{j-1},a_{j}\right) = Pr(g_i) \prod_{k=i}^{j-1}Pr(p_{k}) Pr(a_j)
$$
However when I substitute the probabilities given by the book at the beginning of page 81 the result that comes out from my expression is not the same, so probably both I'm missing something or the book's result is wrong.
Can you help to understand where is the problem?
Comment: Based on the example given in the book, it seems to me a chain can stop either when the carry is annihilated _or_ when a new carry is generated. If you only count annihilation you will get half the correct probability. What probability did your modeling give you?
Comment: basically the same, but instead of the factor 1/2 it gives me 1/2^4
Comment: I think that should be $\prod_{k=i+1}^{j-1}Pr(p_{k})$ rather than $\prod_{k=i}^{j-1}Pr(p_{k})$, because you cannot have both $g_i$ and $p_i$ occur simultaneously.
Answer: I think this comes down to the interpretation of the phrase,

The probability that a carry generated at position $i$ will propagate up to and including position $j - 1$ and stop at position $j$ $(j > i)$

You seem to have interpreted this as "the probability that a carry is generated at position $i$ and propagates up to and including position $j - 1$ and is annihilated at position $j$". The only way for a chain to be "annihilated" is if it reaches a position where both addends have bit value $0$.
The book is interpreting this phrase to mean "the probability that a carry propagates up to and including position $j - 1$ and the chain stops for any reason at position $j$, given that a carry is generated at position $i$". Reasons for the chain to stop are because position $j$ annihilates the carry, or because position $j$ generates a new carry (which stops the previous chain), or because "position $j$" is actually the "carry out" bit (which by assumption no chain can continue beyond).
That is, the probability that the book computes as $2^{-(j-i)}$ is
meant to be
$$
\left(\prod_{k=i+1}^{j-1}Pr(p_{k})\right) Pr(a_j \lor g_j)
$$
which is a factor of $8$ greater than the result you reported.


Conditional random forest :: saving models efficiently

Question: I'm working on a regression problem involving multiple independent learning tasks. I'm using conditional random forest as the learner (see Hothorn et al. 2006) as they are quite robust. The problem I'm having is saving the models. Multiple learning tasks means many big models.
How can I save a subset of each model without taking too much disk/memory space without compromising the usability of my models for predictions?
Comment: Is this more of an R / programming question? I can't tell for sure. If it is, it would be better asked, & probably answered, on [Stack Overflow](http://stackoverflow.com/) rather than here. If this is a question primarily about statistics, please edit to clarify, OTOH, if you just want to know how to get R to do this, flag your Q & we can migrate it for you (*please don't cross-post, though*).
Comment: I agree with gung's comments. The trees may be large but not say 100's of megabytes. They should be a manageable size on disk, especially if compressed.
Answer: Here is what I do:

use a newer package like ranger because it can have a smaller footprint
save the object with the compress flag set

If you have a particular library, aka your conditional is NOT applied to existing RF libraries, then it should make a single tree of models, and just saving with compress set can be about the best you will get without manually reconstructing the save-format.
If you do NOT have a particular conditional, that is to say you are making many independent RF's, then using a relatively modern tool along with saving using the compress flag as true, can very substantially improve your results.


How can I replace a DynamoDB table with an updated name attribute with Terraform?

Question: I have a DynamoDB table that is created with some Terraform that starts off like this:
resource "aws_dynamodb_table" "mytable" {
  name         = "${var.environment_name}-mytable"

(let's say that var.environment name is set to myenvironment)
I need to use terraform to replace it with an empty version of the table, for which I am trying to use the -replace argument, like so:
terraform plan -replace=aws_dynamodb_table.mytable -out plan.bin
terraform apply plan.bin

The problem is that doing this generates a ResourceInUseException:
Error: creating Amazon DynamoDB Table (myenvironment-mytable): ResourceInUseException: Table already exists: myenvironment-mytable

This gives me a double-bind.
If I change the table name in the -replace argument to match the name in the error message (ie. to be prefixed with the environment name) then it doesn't find the table. Checking the name of the table with terraform state show and terraform state list confirms that indeed, terraform thinks the table name is not prefixed with the environment name, and it wants to operate on the table that way.
However, if I leave the table name alone (ie. don't prefix the environment name) then I get the error above - it says it can't replace it because it's in use. Sure enough, if I look in DynamoDB using the AWS console, the table exists with a name that is prefixed with the environment name.
I found this question with an answer that suggests it maybe can't cope with being asked to replace a table that already exists and I need to either delete or rename it first, but I'd really prefer not to do that - I want to do a create_before_replace (I'm not there yet!) and surely the whole point of -replace is that the resource must already exist or you wouldn't be trying to replace it?
I don't know how to resolve this. How do I tell Terraform which table it is I'm trying to replace without having it either fail to find it or complain that it's already in use but named differently?
Comment: Yeah (or at least, something to that effect), I was trying to do it atomically. I don't think I actually need to though, so I probably will just destroy it and then create it again separately.
Comment: are you trying rename the dynamodb table name that already has items in it ?
Comment: No. I'm trying to wipe the contents of the table and restore it to a pristine (empty) state. It's potentially quite large, so I was hoping to do it by just telling Dynamo to recreate the table rather than by explicitly deleting everything in it, which might take a while.
Comment: I see , could you not just comment out the resource , do an apply and then uncomment it by reapplying the tf config? that will delete the table from my understanding
Answer: I have not been able to answer the original question (how to get -replace to work with a non-empty DynamoDB table) and my suspicion is that it isn't possible, that Terraform will not do an atomic replace on an existing non-empty table. But I don't know that for sure.
What I have done is to do this non-atomically instead. This may be of use to some, and to others who want an answer to my original question, it may not be. But here's what I ended up doing.
terraform plan -destroy -target=aws_dynamodb_table.mytable -out plan.bin
terraform apply plan.bin
terraform plan -out plan.bin
terraform apply plan.bin

This deletes the original table (it looks like it's destroying everything, but it doesn't) and then creates it again from the original plan. Terraform spits out a nasty warning that you shouldn't really use -target (because it leaves your configuration in a state that isn't the same as your configuration files), but as long as you remember it's done that and don't forget to re-create it again, this seems fine to me.
I'm not accepting this answer because it doesn't answer the original question (it's a partial work-around) so if anyone does have an answer to the original question, I'm all ears!
EDIT: Oh, noticeably, the table name is the one in the resource declaration (ie. without the environment name prepended) not the one from the "name" attribute.


Lattice Reduction in Mathematica

Question: I have some trouble understanding the concept of lattice reduction.
As I understand, an integer lattice
$$\{ A k : k \in \mathbb{Z}^n \} \subset \mathbb{Z}^n $$
is defined by a regular matrix $A \in \mathbb{Z}^{n \times n}$.
Two matrices $A$ and $B$ generate the same lattice if there exist $R \in \mathbb{Z}^{n \times n}$ such that
$$A = B R.$$
Now I try the following in Mathematica with the function
A = {{1, 0, 1345}, {1, 0, 35}, {0, 1, 154}}
B = LatticeReduce[A]
yields
$$
B= \left(
\begin{array}{ccc}
 9 & -2 & 7 \\
 -2 & -8 & 8 \\
 -2 & 9 & 6 \\
\end{array}
\right)
$$
Now, I expect $B^{-1} A \in \mathbb{Z}^{3 \times 3}$.
However,
R = Inverse[B].A
yields
$$
R=\left(
\begin{array}{ccc}
 \frac{9}{262} & -\frac{4}{131} & \frac{233}{2} \\
 -\frac{32}{655} & \frac{43}{655} & \frac{62}{5} \\
 \frac{111}{1310} & \frac{38}{655} & \frac{459}{10} \\
\end{array}
\right)
$$
What did I do wrong? Thanks!
Answer: EXTRA: Alright, Mathematica works with the rows as generating vectors. A vector in their lattice will be $k A,$ where $k$ is a row vector of integers. Try $k = (1,0,0)$ and see what happens. This means that reduction follows the recipe $A = LB,$ so that $L = A B^{-1}.$
<code>? opa = a
%16 =
[1 0 1345]

[1 0 35]

[0 1 154]

? opb = [ 9,-2,7; -2,-8,8; -2,9,6]
%17 =
[9 -2 7]

[-2 -8 8]

[-2 9 6]

? matdet(opb)
%18 = -1310

? opbinv = - matadjoint(opb) / 1310
%19 =
[12/131 -15/262 -4/131]

[2/655 -34/655 43/655]

[17/655 77/1310 38/655]

? L =  opa * opbinv
%21 =
[35 79 78]

[1 2 2]

[4 9 9]
</code>
ORIGINAL: You have not been clear about rows and columns. We usually talk about the lattice generated by the columns of $A,$ that is what your definition says. Here is a satisfactory calculation from gp-pari that results in the transpose (well, permuted with $\pm$ signs) of your $B.$ I have no way of knowing how that compares with Mathematica. Note that there is a problem if we just take transposes, as $(AT)^t = T^t A^t,$ so the order becomes incorrect.

qflll(x,{flag = 0})
LLL algorithm applied to the columns of the matrix x. The columns of x
  may be linearly dependent. The result is a unimodular transformation
  matrix T such that x .T is an LLL-reduced basis of the lattice
  generated by the column vectors of x.

<code>aa = [1,1,0; 0,0,1; 1345,35,154]
%1 =
[1 1 0]

[0 0 1]

[1345 35 154]

? matdet(aa)
%2 = 1310

? aat = qflll(aa)
%13 =
[1 0 -1]

[-3 9 -1]

[-8 -2 9]

? aared = aa * aat
%14 =
[-2 9 -2]

[-8 -2 9]

[8 7 6]

?
?
? matdet(aat)
%15 = 1
?
</code>
Comment: thanks a lot! this was precicely the problem.

Lattice Reduction in Mathematica


Flot Time Series Date Labels Incorrect

Question: I'm trying to create a time series graph using Flot to compare two series of data. After including jQuery, jquery.flot.js, and jquery.flot.time.js, my code looks like:
<code>$(function () {
  var d1 = {
    label: "Fall 2011",
    data: [
      [1296536400, 9],
      [1296622800, 23],
      [1296709200, 30],
      [1296795600, 64],
      [1296882000, 94],
      [1296968400, 113],
      [1297054800, 125],
      [1297141200, 156],
      [1297227600, 181],
      [1297314000, 200],
      [1297400400, 217],
      [1297486800, 231],
      [1297573200, 248],
      [1297659600, 259],
      [1297746000, 271],
      [1297832400, 282],
      [1297918800, 308],
      [1298005200, 316],
      [1298091600, 332],
      [1298178000, 345],
      [1298264400, 360],
      [1298350800, 373],
      [1298437200, 391],
      [1298523600, 409],
      [1298610000, 427],
      [1298696400, 433],
      [1298782800, 444],
      [1298869200, 460],
      [1298955600, 467],
      [1299042000, 479],
      [1299128400, 494],
      [1299214800, 500],
      [1299301200, 509],
      [1299387600, 530],
      [1299474000, 548],
      [1299560400, 567],
      [1299646800, 577],
      [1299733200, 596],
      [1299819600, 608],
      [1299906000, 623],
      [1299992400, 638],
      [1300075200, 651],
      [1300161600, 670],
      [1300248000, 689],
      [1300334400, 712],
      [1300420800, 722],
      [1300507200, 737],
      [1300593600, 764],
      [1300680000, 784],
      [1300766400, 807],
      [1300852800, 839],
      [1300939200, 865],
      [1301025600, 880],
      [1301112000, 901],
      [1301198400, 937],
      [1301284800, 970],
      [1301371200, 1000],
      [1301457600, 1030],
      [1301544000, 1064],
      [1301630400, 1081],
      [1301716800, 1111],
      [1301803200, 1144],
      [1301889600, 1176],
      [1301976000, 1207],
      [1302062400, 1232],
      [1302148800, 1251],
      [1302235200, 1270],
      [1302321600, 1293],
      [1302408000, 1329],
      [1302494400, 1361],
      [1302580800, 1398],
      [1302667200, 1442],
      [1302753600, 1474],
      [1302840000, 1499],
      [1302926400, 1524],
      [1303012800, 1553],
      [1303099200, 1585],
      [1303185600, 1619],
      [1303272000, 1658],
      [1303358400, 1703],
      [1303444800, 1754],
      [1303531200, 1784],
      [1303617600, 1830],
      [1303704000, 1896],
      [1303790400, 1968],
      [1303876800, 2045],
      [1303963200, 2140],
      [1304049600, 2230],
      [1304136000, 2337],
      [1304222400, 2457],
      [1304308800, 2532],
      [1304395200, 2587],
      [1304481600, 2618],
      [1304568000, 2641],
      [1304654400, 2658],
      [1304740800, 2675],
      [1304827200, 2690],
      [1304913600, 2703],
      [1305000000, 2719],
      [1305086400, 2735],
      [1305172800, 2746],
      [1305259200, 2757],
      [1305432000, 2761],
      [1305518400, 2778],
      [1305604800, 2794],
      [1305691200, 2800],
      [1305777600, 2804],
      [1305864000, 2813],
      [1305950400, 2821],
      [1306036800, 2822],
      [1306123200, 2833],
      [1306209600, 2843],
      [1306296000, 2854],
      [1306382400, 2860],
      [1306468800, 2871],
      [1306555200, 2875],
      [1306728000, 2879],
      [1306814400, 2883],
      [1306900800, 2886],
      [1306987200, 2891],
      [1307073600, 2894],
      [1307160000, 2897],
      [1307246400, 2898],
      [1307332800, 2903],
      [1307419200, 2907],
      [1307505600, 2913],
      [1307592000, 2914],
      [1307678400, 2919],
      [1307764800, 2920],
      [1307851200, 2923],
      [1308024000, 2929],
      [1308110400, 2935],
      [1308196800, 2936],
      [1308283200, 2937],
      [1308369600, 2940],
      [1308456000, 2941],
      [1308542400, 2946],
      [1308628800, 2949],
      [1308715200, 2957],
      [1308801600, 2958],
      [1308888000, 2962],
      [1308974400, 2963],
      [1309060800, 2965],
      [1309147200, 2969],
      [1309233600, 2970],
      [1309320000, 2974],
      [1309406400, 2975],
      [1309492800, 2976],
      [1309924800, 2978],
      [1310702400, 2979],
      [1310875200, 2980],
      [1310961600, 2981],
      [1311134400, 2982],
      [1311566400, 2983],
      [1311652800, 2984]
    ]
  };
  $.plot("#placeholder", [d1], {
    xaxis: {
      mode: "time",
      timeformat: "%m/%d %h:%m"
    },
    legend: {
      show: true,
      position: 'se'
    }
  });
});
</code>
This generates the graph:

Notice the x-axis labels are incorrect. The unix timestamps range from 01 Feb 2011, to  26 Jul 2011. I've tried various 'timeformat' and 'minTickSize' options, to no avail. What am I doing wrong? How do I get the labels to show up with month and day names for the entire range of data?
Comment: Duplicate - http://stackoverflow.com/questions/15199814/how-to-plot-a-date-range-on-x-axis-in-flot-charts/15204645#15204645
Answer: You want to multiply your UNIX timestamps by 1000 in order to get them into the appropriate format for Javascript.
Comment: Thanks! I missed this sentence while RTFM'ing:

"This is almost the same as Unix timestamps, except it's in milliseconds, so remember to multiply by 1000!" (From the [docs](https://github.com/flot/flot/blob/master/API.md#time-series-data))
Answer: This should give you a start - http://jsfiddle.net/TZWbN/
<code>  data: [

         [1308888000000, 2962],
      [1308974400000, 2963],
      [1309060800000, 2965],
      [1309147200000, 2969],
      [1309233600000, 2970],
      [1309320000000, 2974],
      [1309406400000, 2975],
      [1309492800000, 2976],
      [1309924800000, 2978],
      [1310702400000, 2979],
      [1310875200000, 2980],
      [1310961600000, 2981],
      [1311134400000, 2982],
      [1311566400000, 2983],
      [1311652800000, 2984]]
  };
</code>

Flot Time Series Date Labels Incorrect


How to count Terminal Zeros from subtraction

Question: How do you count the number of zeros that the subtraction 100$^{100}$ - 100! ends in? In particular, I want to know exactly why my approach is wrong, because I know from my source that the answer is 24, but I do not know why. Here are my steps to solving:
First I find the number of 5's in 100!; 100/5 = 20/5 = 4, so there are 24 5's in 100! and thus 24 10's, leading to 24 terminating zeros in 100!.
Then I make 100$^{100}$ into 10$^{200}$ by (10$^{2}$)$^{100}$. So there are 200 terminating zeros in 10$^{200}$.
Now for my attempt to solve. I really just interpreted the solution as subtracting the number of terminating zeros, but with experimenting small values of powers of tens, that approach was flawed. So, in truth, I really do not know how to get 24 terminating zeros from 100$^{100}$ - 100!. Any help will be appreciated, as I have tried understanding the theory behind the problem; I just do not know how to proceed after my steps to lead me to the correct solution.
Answer: If $0< n<100^{100}$ ($n=100!$ has this property), then  $n$ and $100^{100}-n$ have the same number of terminating zeros.
In fact, if $n$ has $d$ terminating zeros then $n=m10^d$ where $0< m<10^{100-d}$ and
$$100^{100}-n=100^{100}-m10^d=10^d(100^{100-d}-m)$$
which has $d$ terminating because $100^{100-d}-m>0$.
Comment: Oh, so since 100! has 10$^{24}$ as its max power of 10, but 100$^{100}$ can have more, such as 10$^{25}$, then 100! < 100$^{100}$, and therefore the terminating zeros are those of 100!? In this case being 24. How do you know that n and 100$^{100}$ - n will have the same terminating zeros, though?
Comment: @Ivan Ortiz Yes. See my edited answer.


How to retrieve all my active Facebook ads?

Question: I'm creating a dashboard for myself that helps me keep track of the Facebook ads I'm running.
What I've not been able to figure out is:
How can I retrieve an array of ad IDs for all ads that are active or could soon be active after no further action on my part?
In other words, I want all ads that I've set to Active and that exist within Adsets and Campaigns that are active (and therefore these ads are live right now)... plus all the ads that from my perspective are Active but that Facebook has set to another status such as Pending Review (and will soon set back to Active).
I have some code below, but the problem is that it also accidentally includes Pending ads that--once reviewed and approved by Facebook--will be inactive rather than active (because I've set them that way).  And I do NOT want this type of ad to be included in my report.
My report should only show me ones where I'm actively spending money or have the potential to spend money as soon as FB approves them.
I think I understand the difference between configured_status and effective_status in AbstractArchivableCrudObjectFields, but I don't know that it's enough to help me because I have lots of ads set to Active that are within Adsets that are Inactive, and I don't want to see those listed in my report.
Any recommendations?
public function getActiveAdIds() {
    $key = 'activeAdIds';
    $adIdsJson = Cache::get($key);
    if ($adIdsJson) {
        $adIds = json_decode($adIdsJson);
    } else {
        $adsResponse = $this->getAdsByStatus([ArchivableCrudObjectEffectiveStatuses::ACTIVE, ArchivableCrudObjectEffectiveStatuses::PENDING_REVIEW]);
        $ads = $adsResponse->data;
        $adIds = [];
        foreach ($ads as $ad) {
            $adIds[] = $ad->id;
        }
        $adIdsJson = json_encode($adIds);
        Cache::put($key, $adIdsJson, 1);
    }
    return $adIds;
}

public function getAdsByStatus($statuses) {
    $params = [\FacebookAds\Object\Fields\AbstractArchivableCrudObjectFields::EFFECTIVE_STATUS => $statuses];
    $adAccount = new AdAccount(self::ACT_PREPEND . $this->fbConfig['account_id']);
    $cursor = $adAccount->getAds([], $params);
    $response = $cursor->getResponse();
    $jsonString = $response->getBody();
    return json_decode($jsonString);
}

Comment: Any chance for you to share, how you solved this problem?
Comment: @Sigismund Still unsolved. If you find out, I'd love if you'd post the answer here.
Answer: I get stats based on assets for my active campaigns. I have 119 ad accounts. This is php code which I used it for this purpose (any suggestion to improve it will be appreciated):
    $fields = array(AdsInsightsFields::ACCOUNT_NAME,AdsInsightsFields::CAMPAIGN_ID,
                    AdsInsightsFields::CAMPAIGN_NAME, AdsInsightsFields::ADSET_ID,
                    AdsInsightsFields::ADSET_NAME,AdsInsightsFields::DATE_START,
                    AdsInsightsFields::DATE_STOP,AdsInsightsFields::REACH,
                    AdsInsightsFields::SPEND, AdsInsightsFields::IMPRESSIONS,
                    AdsInsightsFields::CLICKS, AdsInsightsFields::WEBSITE_CLICKS,
                    AdsInsightsFields::CALL_TO_ACTION_CLICKS,AdsInsightsFields::ACTIONS,
                    AdsInsightsFields::TOTAL_ACTIONS,AdsInsightsFields::CPC,
                    AdsInsightsFields::CPM,AdsInsightsFields::CPP,
                    AdsInsightsFields::CTR,AdsInsightsFields::OBJECTIVE,);
    $params_c['date_preset'] = AdDatePresetValues::YESTERDAY;
    $params_c['time_increment'] = 1;
    $params_c['action_attribution_windows'] = array('1d_view', '28d_click');
    $params_c['effective_status'] = AdStatusValues::ACTIVE;
    $params_c['level'] = AdsInsightsLevelValues::ADSET;
    $params_c['filtering'] = [array("field"=>"campaign.delivery_info",
                                   "operator"=>"IN",
                                    "value"=>array("active"))];
    $params_c['fields']= $fields;
    try{
         // Initialize a new Session and instanciate an Api object
        Api::init(self::api_key, self::secret_token, self::extended_token)->getHttpClient()->setCaBundlePath( $this->path_cert);

        // The Api object is now available trough singleton
        $api = Api::instance();
        $user = new \FacebookAds\Object\Business($business_id);
        $user->read(array(BusinessFields::ID));

        //get all ad_account from Business
        $accounts = $user->getAssignedAdAccounts(
                      array(
                    AdAccountFields::ID,
                 ),
                  array('limit'=>1000,)
                );

    } catch (FacebookAds\Exception\Exception $ex) {
        return $ex->getMessage();
    }

    if(isset($accounts) && ($accounts->count() > 0)):
        do{

            $ad_account = $accounts->current();
            $adset_insights = $ad_account->getInsights($fields,$params_c);

            do {
                $adset_insights->fetchAfter();
            } while ($adset_insights->getNext());

            $adsets = $adset_insights->getArrayCopy(true);
    }
    while ($accounts->current());
    endif;

Comment: Thanks for sharing. Although your code looks like it will probably help someone, I wonder if you don't understand the main part of my question (relating to the difference between `configured_status` and `effective_status` and how to retrieve all ads that either are actively spending money or could be approved by Facebook to spend money without any further action on my part).
Answer: If you include the adset{end_time} field in the query for the ad, you can assume that ad is not actually running if the end_time was in the past. This is how we get a base list of ads to query on.
The next step we take (which probably won't help you, unfortunately, but may help others) is building a batch of simple requests (one per ad) to see if there are any insights data for that day. If the response is an empty 'data' array, we can remove that ID from the ad list.
After we've reduced the size of the ad list with those two steps we can then make requests to run all of our breakdown reports. This method almost cut our API requests in half.
I have yet to find a way to do a "give me all ads that are for sure running this day" query in one step.
Edit:
I just found a better way to do this.... :
curl -G \
-d 'access_token=<ACCESS_TOKEN>' \
-d 'level=campaign' \
-d 'filtering=[{field:"ad.impressions",operator:"GREATER_THAN",value:0}]' \
'https://graph.facebook.com/v2.7/act_<ACCOUNT_ID>/insights'


Duvida de declaração de atributos no PHP 7

Question: Estou fazendo a migração do PHP 5 para o 7 e uma das mudanças foi que as variáveis globais pararam de existir. E possuo duas variáveis desse estilo em meu código:
$root = $GLOBALS['files']['siteRoot'];
$root = str_replace("//", "/", $root);
$pastas[] = "";
$pastas[] = "/controle/";
$pastas[] = "/pagseguro/";
$pastas[] = "/controle/auxiliar/";
$pastas[] = "/persistencia/";
$pastas[] = "/persistencia/DTO/";
$pastas[] = "/view/";
$pastas[] = "/view/classes/";
$pastas[] = "/view/relatorios/";
$pastas[] = "/library/";
$pastas[] = "/library/zip/";
$pastas[] = "/library/phpmailer/";

spl_autoload_register($nomeDaClasse) {
    globals $root, $pastas;
    $file = "";
    for ($index = 0; $index < count($pastas); $index++) {
        if (file_exists($root . $pastas[$index] . $nomeDaClasse . '.php')) {
            $file = $root . $pastas[$index] . $nomeDaClasse . '.php';
        }
    }
    if ($file == "") {
        return false;
    }
    include $file;
}

Me recomendaram a utilização do static mas não sei a forma de declarar as mesmas.
Comment: Variáveis estáticas e variáveis globais são conceitualmente distintas e uma não substitui a outra. Você usa a estrutura `globals` para importar para o contexto atual algo que foi definido em um contexto externo. Você tem maneiras mais elegantes de fazer o mesmo, tal como passar os valores por parâmetros se for uma função. Poderia [edit] a pergunta e apresentar o escopo completo de onde está utilizando tais variáveis?
Comment: Esse é todo o código
Answer: Primeiro, fazer:
spl_autoload_register($nomeDaClasse) {
    ...
}

Está errado e não faz sentido algum. A função spl_autoload_register é nativa do PHP e tem como objetivo registrar funções para o autoload. No trecho acima você não está nem chamando a função, nem definindo-a novamente. Ou seja, a sintaxe está completamente errada. Se tem dificuldades em visualizar isso, recomendo fortemente que revise a parte que mostra como chamar uma função e como defini-la.
O que você deve fazer é chamar a função e definir outra para ser registrada:
spl_autoload_register(function ($nomeDaClasse) {
    ...
});

Note que agora o código é spl_autoload_register(X), onde X é uma função anônima. Esta função anônima que será registrada no autoload. Você pode também fazer, caso preferir:
function minha_autoload($nomeDaClasse) {
    ...
}

spl_autoload_register('minha_autoload');

O resultado será o mesmo que utilizando a função anônima.
Ok, mas como passar os valores para escopo da função? Se for uma função anônima, você pode utilizar o use que serve justamente para isso:
$root = 1;
$pastas = 2;

spl_autoload_register(function ($nomeDaClasse) use ($root, $pastas) {
    // $root e $pastas existirão aqui com os mesmos valores
    ...
});

Onde $root e $pastas são variáveis definidas no mesmo escopo em que foi definida a função anônima.

Qual é a finalidade do comando "use" e qual é a sua relação com funções anonimas?
Comment: Muito obrigado pela ajuda, vou com toda certeza rever a parte de chamadas de funções. É uma linguagem nova para mim e estou ainda penando um pouco para dominá-la


CDF of Uniform random variable

Question: The problem is:
$Y \sim Unif[0,\theta]$ and we define $X = -Y$.
We want to find $ f_X(x)$ and $F_X(x).$
My solution:
$$F_X(x) = P(X<x)=P(Y>-x)=\int_{-x}^{+\infty}{\frac{1}{\theta} d\theta}$$
But from here I am unsure.I start the problem in this way because if I find the cumulative distribution function, i can derive it to find the Probability Density Function.
Comment: Make sure that what you've done so far is correct. Then after that why don't you calculate the integral? This gives you the CDF of X. Then after that you differentiate to find the PDF of X. After that you are done.
Comment: I would have thought you wanted to integrate over $y$ rather than $\theta$, and the density is only positive for some $y$, so $\int\limits_{-x}^{+\infty}{\frac{1}{\theta} } \mathbf I_{0\le y\le \theta} \,dy$
Comment: $Y$ takes values in $[-\theta,0]$ So the integral goes only up to $0$.
Comment: @KaviRamaMurthy I would have thought $Y$ only takes values in $[0,\theta]$
Comment: @Henry if i solve the integral i have :$$\left [ \frac{y}{\theta}I_{[0,\theta]} \right ]_{-x}^{+\infty} = +\infty-\frac{x}{\theta}I_{[0,\theta]} = +\infty$$ what's i am doing wrong?
Comment: $\frac{y}{\theta}I_{[0,\theta]} =0$ when $y>\theta$ or $y <0$
Comment: @Henry I finally understood thanks!
Answer: The PDF of the continuous uniform random variable Y on the interval $[0,\theta]$ is $f_Y(y)=\frac{1}{\theta}$ for values of $y$ in the given interval.
Therefore, we note that to find the PDF of X, we can do the following:
$F_X(x) = P(X<x)=P(Y>-x)=\int_{-x}^{\theta}{\frac{1}{\theta} dy}$
Note: the reason tht we go up to $\theta$ is that the PDF is $0$ for any value of x outside of the interval $[0,\theta]$
This evaluates to $F_X(x)=1+\frac{x}{\theta}=\frac{x+\theta}{\theta}$ by solving the integral. By differentiating we can find $f_X(x) = \frac{1}{\theta}$ and so we are done as we have found both the PDF and CDF of $X$.
Therefore, $X$~$Uniform[-\theta,0]$ which should be expected if we refer back to the definition of $X$ as being equal to $-Y$.
Comment: Why is the integral up to $0$ rather than up to $\theta$?
Comment: I've updated my answer. Thanks for the correction; slightly misread the question at first @Henry
Comment: Thanks for the help i finally understood!

CDF of Uniform random variable


Unable to update node entity fields using custom form

Question: There is a certain content type, in which there is a field to enter a node or taxonomy.
I want to create a new node for that content type using a custom form and register the node or taxonomy in the entity field.
<code>$form['client_company'] = [
  '#type' => 'entity_autocomplete',
  '#target_type' => 'taxonomy_term',
  '#tags' => TRUE,
  '#selection_settings' => array(
    'target_bundles' => array('vid', 'client'),
  ),
  '#weight' => '0',
];

$form['client_human'] = [
  '#type' => 'entity_autocomplete',
  '#target_type' => 'node',
  '#tags' => TRUE,
  '#selection_settings' => array(
    'target_bundles' => array('budle', 'client_human'),
  ),
  '#weight' => '0',
];
$form['url'] = [
  '#type' => 'url',
];

$node->field_project_refercompany->value = $form_state->getValue('client_company');
$node->field_project_referclienthuman->value = $form_state->getValue('client_human');
$node->field_project_url->value = $form_state->getValue('url');
$node->save();
</code>
The $node, field_refercompany, field_project_referclienthuman, etc. are nodes and their field names, no error there.
However, even though I can create a new node, the above fields are blank and nothing is entered.
Answer: Self Answer
<code>$node->field_project_refercompany->target_id = $form_state->getValue('client_company')[0]['target_id'];
$node->field_project_referclienthuman->target_id = $form_state->getValue('client_human')[0]['target_id'];
$node->field_project_url->uri = Url::fromUri($form_state->getValue('url'))->toString();
</code>


Como chamar API do youtube com vários parâmetros?

Question: Estou tentando pegar os dados de vários videos, porém a API do Youtube é separada para videos e playlist, então eu usei a API de playlist para obter os VideoID de cada vídeo que esta em determinada playlist, porém para chamar a API de videos eu quero chamar vários videos de uma vez para evitar fazer varias chamadas na API desnecessárias assim:
https://www.googleapis.com/youtube/v3/videos?part=snippet,statistics&id=VIDEOID1,VIDEOID2,VIDEOID3...&key={API_KEY}

Como passar esses videoid separados por virgula usando Retrofit? Andei pesquisando e li sobre mapa de strings, porém não parece ser oque preciso.
Atualmente estou usando o própio Adapter do RecyclerView passando a posição dentro do onBindViewHolder porém isso além de varias requisições desnecessárias, me trás problemas como os items da lista carregando durando o scroll, fica muito ruim.
Answer: A princípio você pode criar uma lista de videos, para depois concatenar criando uma StringBuilder. Veja
List <String> list = new ArrayList <String> ();
list.add("video_codigo_1");
list.add("video_codigo_2");
list.add("video_codigo_3");
list.add("video_codigo_4");

StringBuilder strB = new StringBuilder();
for (int i = 0; i < list.size(); i++) {

    if (i < (list.size() - 1))
        strB.append(list.get(i)).append(",");
    else strB.append(list.get(i));
}
String url = "https://www.googleapis.com/youtube/v3/videos?part=snippet,statistics&id="
   + strB.toString() + "&key={API_KEY}";

Veja funcionando no IDEONE.
Uma adaptação para o Retrofit,
class SuaActivity extends Activity {

    private static final String BASEPATH = "https://www.googleapis.com/youtube/v3/";

    private interface API {
        @GET("/videos")
        void getVideos(@QueryMap Map <String, String>
            params, new Callback <String> callback);
    }

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.your_layout);

        RestAdapter rest = new RestAdapter.Builder().setEndpoint(BASEPATH).build();
        API service = rest.create(API.class);

        List < String > list = new ArrayList < String > ();
        list.add("video_codigo_1");
        list.add("video_codigo_2");
        list.add("video_codigo_3");
        list.add("video_codigo_4");

        // concatena as strings separando por virgula
        StringBuilder strB = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {

            if (i < (list.size() - 1))
            strB.append(list.get(i)).append(",");
            else strB.append(list.get(i));
        }

        Map <String, String> params = new HashMap <String, String> ();
        params.put("part", "snippet,statistics");
        params.put("id", strB.toString());
        // aqui podes colocar outros parâmetros

        service.getVideos(params, new Callback <String> () {
            // aqui você faz o tratamento para listar os videos
        });
    }
}

Se houver mais alguma duvida em relação aos parâmetros da Youtube API, pode conferir na documentação.
Comment: funcionou valeu, não tinha sabia usar o string builder


Beethoven's Tempest sonata: tie or slur?

Question: I'm learning the Tempest sonata, and I don't know how to read measures 72-73:

In the measure right before the crescendo, that A-C chord with the right hand: is the A sustained while the C is released to hit the B-natural, or are both the A and the C released at the same time, i.e., is that line connecting the A's a tie or a slur?
It looks like a tie to me, but I've consulted many editions, and some write it as a slur, and others as a tie.
Comment: According to the context, I guess it should be a slur, i.e. you should play the A note twice, to follow the pattern of the bars around. However if I were the editor, I would have the slur/tie curve removed to avoid misconception.
Comment: What do you mean by "some write it as a slur"? Aren't two-note slurs indistinguishable from ties?
Comment: @Kilian Forth, at least on Musescore, the tie tends to hug the notes more closely than the slur.
Answer: Your best guide would actually be to listen to recordings & read the writings of acknowledged Beethoven specialists. That said, analysing the lines in the right hand provides some insight.
If we remove the octave transpositions & the rests we have this progression in the 4 bars you provided:

So you can see from what's happening in the counterpoint, both the A in 2nd & 3rd bars and the B♮ in the 3rd & 4th bars should be tied: the A being a suspended 7th on the prevailing B-dim harmony, delaying the onset of E-maj to the 4th bar. So re-striking the notes in both instances would undermine the harmony & counterpoint in the passage.
Update:
I listened to a few recordings & concentrated on the passage in question.

Schnabel: doesn't re-strike the A & B♮ (tie)
Brendel: doesn't re-strike the A & B♮ (tie)
Barenboim: doesn't re-strike the A & B♮ (tie)
Pollini: doesn't re-strike the A & B♮ (tie)
Grimaud: re-strikes the A & B♮ (slur)

So, in my non-representative sample the majority interpret the A-A & B♮-B♮ joins as ties.
Also, another clue is provided by the editor in the choice of rendering the A against B♮ in the 3rd bar in 2 voices. Some other editions have all of the chords in a single voice through this passage, others are rendered as yours.
Answer: The A would be held as a tie through the bar and the C would change to a B natural. If there was a marking like staccato on the second a there would be a break but since there isn't it would just be sustained. I also think the C to B would be a slur, so it would not be released in between.
Answer: Judging by the preceding and following two note 'chords' that all change, but with both notes changing, it should sound more uniform to replay the A at the beginning of that bar.


Best book to study Lie group theory

Question: I have been using the concepts of Lie group, Lie algebra and some of its properties for quite a while now in various geometry courses, but I had to pick those concepts along the way because they are always taken for granted. I want to fill this hole and I was wondering which (graduate) book will be best suited for this, some research led me to this list, although I am open for any suggestion:
-Brian C. Hall, Lie groups, Lie algebras and representations. Currently my least favorite option, mainly because of the answer given here. I do know differential geometry and I would like to study this subject in all generality. Still people seem to like this book, and it has a lot of problems, which I appreciate very much.
-V. S. Varadarajan, Lie groups, Lie algebras and their representations. I know very little about this book, I have been told that it is kind of a more general version of the last one (using differential geometry freely), but I did not manage to find a copy on any library to check it out. Does it have a good amount of problems?
-J. Harris and W. Fulton, Representation theory. Seems to be a classic, but (and I am judging just by the title for I could not get a copy of this one either) I am afraid this book will go too fast on the basics of Lie groups and Lie algebras. Also, how about the problems on this one?
Comment: What did you end up deciding? I'm debating between Hall and Varadarajan; I have some of the same concerns about Hall that you did, but do you think there was anything in Hall that I'd miss if I went straight for Varadarajan?
Comment: See this question:

https://math.stackexchange.com/questions/461029/getting-started-with-lie-groups
Comment: V. S. Varadarajan's book has a lot of exercises.
Answer: Hall's book is excellent. You can't go wrong there.
I would also suggest supplementing with Chapter 4 of Tu's book for more of a complete connection with the geometry (Hall's book largely focuses on the representation theory of Lie Groups and Lie Algebras, although there is geometry in that too in later chapters).
Comment: My main concern with this one is that it unnecessarily avoids talking about geometry from the beginning, so I am worried that would translate into a less thorough treatment of the subject. If you had a chance to look at Fulton's, how would you compare them?
Comment: I don't think I'm a great source for opinions on Fulton and Harris - I've used parts of it at times, but never thoroughly read it or worked through the problems. I will say though that my impression is that it's a decent reference book, but not a good introduction (ironic given the title). The reason I say this is that the proofs are very brief and often alluded to or described in words, rather than in maths, which is a personal pet peeve. At least when I've needed to use it. The problems are probably decent as per your original question, but that's true of any book on the topic these days imo
Comment: Further, I see no reason to read Fulton over Hall if you're specifically interested in Lie Groups. As I've said and have been mentioned in other answers on this site, the only possible draw back of Hall is you might want to focus on geometry over representation theory. Fulton's book is a book on representation theory, so that gets you nowhere if you want more geometry :)
Answer: Try Chevalley,Claude  Theory of Lie Groups (Dover) .An oldy but a goody .This book is a classic ,self contained for the most part and logically very clear .
Comment: Some remarks on how this "oldy" relates or compares to the books already provided in the body of the Question, or otherwise proffering how the book by Chevalley meets the request, would elevate this post from Comment-quality content to an Answer.
Comment: Managed to take a look of this one. It seems to be missing a big amount of material with respect the other books I am considering and, most importantly, it has no problems.

Best book to study Lie group theory


Meu codigo so filtra se digitar primeira letra Jquery, como filtrar digitando a palavra inteira (tabela)?

Question: Ex: palavra (ideal) se eu digitar na busca o "i" ele busca todas as palavra que contem a letra "i", Mas se eu digitar toda a palavra a busca some e fica em branco.
segue o código:
$('#myInput').keyup(function () {
      var searchitem = $('#myInput').val();
      if (searchitem == null || searchitem == undefined){
          $('#table tbody td').show();

      }
      else {
          searchitem = searchitem.toUpperCase();
          $('#table tbody tr').hide();
          $('#table tbody tr').each(function () {
              if ($(this).text().indexOf(searchitem) >= 0) {
                  $(this).show();
              }
          });
      }

  });

Comment: Por favor, edite a pergunta e elabore um [mcve]. Ao [edit] aproveite para descrever também como deve ser o comportamento do código quando a palavra só possua uma letra (exemplo: buscar pela palavra `é`).
Answer: Falta algumas informações para poder dar uma resposta mais concreta mas espero que o exemplo abaixo possa te ajudar:

$('#myInput').keyup(function () {
 const val = event.target.value.toUpperCase();
 $('#table td').each(function() {
  const tdText = $(this).text().toUpperCase();
  if (tdText.indexOf(val) >= 0) {
   $(this).parent().show();
  } else {
   $(this).parent().hide();
  }
 });
});

<input type="text" id="myInput" />

Lorem

ipsum

dolor

sit

amet

consectetur

adipisicing

elit


Como inserir dados no banco (mysql) recebidos de um formulário HTML separado por virgulas?

Question: Boa noite, eu vou receber uma informação vinda de um TEXTAREA html, e preciso receber isso no PHP e inserir essas informações no banco, como consigo fazer isso?
A informação vem do TEXTAREA da seguinte maneira:
0001, Aluno A, 10, 10, 20
0002, Aluno B, 8, 8, 16
as informações ja vem separadas por virgula, se fosse em um arquivo TXT ou CSV eu ja vi que conseguiria inserir através de um LOAD DATA mas no caso aqui um usuário vai digitar o texto e submeter através de um formulário HTML....
Comment: Dê uma olhada nisso http://php.net/manual/pt_BR/function.implode.php
Comment: poste o código, para verificarmos, sua pergunta não foi muito clara
Answer: Se eu entendi a sua pergunta. Você quer separar essas informações para inserir no banco de dados.
Se no textarea a informação vier pulando linha igual está no seu exemplo, eu faria assim:
Utilizaria o explode para separa as informações, depois criaria uma string única e subiria no banco de dados os valores:
<?php

    // aqui vem a informação do textarea
    $stringDoTextArea = $_POST['textArea'];

    // aqui eu inseri o
 para identificar que pulou linha
    $stringDoTextArea = nl2br($stringDoTextArea);

    // os dados agora são um array
    $dados = explode("
", $stringDoTextArea);

    // vamos criar a string que insere os dados no DB
    $stringDeInsercao = "INSERT INTO tabela(`campo1`, 'campo2', `campo3`, `campo4`) VALUES ";

    while($d = 0; $d < count($dados); $d++){

        // concatena linha por linha
        $dadoX = explode(",",$dados[$d]);
        $stringDeInsercao .= "('".$dadoX[0]."', '".$dadoX[1]."', '".$dadoX[2]."', '".$dadoX[3]."') ,";

    }

    // aqui eu retiro a ultima virgula
    $stringDeInsercao = substr($stringDeInsercao, 0, -1);

    // insere os dados de uma vez só
    mysqli_query($conexao, $stringDeInsercao);

?>

Isso é só um exemplo pois há varias formas de fazer.


Any way to prevent AUTOINCREASE on failed 'INSERT OR IGNORE'?

Question: Summary of the issue: With MySQL and SQLite, a failed INSERT OR IGNORE on a table with AUTOINCREMENT still increases the autoincremented value. This has been discussed here: INSERT IGNORE increases auto increment counter even no record is added?
My issue: a table with 99% failed inserts ends up with huge index numbers, for example record 1500 has the index 165200.
This is impractical, so I am looking for a way to counter this behaviour.
Since INSERT OR IGNORE is supposedly the same as INSERT ON CONFLICT IGNORE, I have thought of using INSERT ON CONFLICT FAIL or INSERT ON CONFLICT ABORT.
My problem is that I am inserting from a SELECT this way:
INSERT OR IGNORE INTO t1 (x,y,z,) SELECT * FROM t2
This syntax does not accept ON CONFLICT FAIL. Neither of those two work:
INSERT ON CONFLICT FAIL INTO t1 (x,y,z,) SELECT * FROM t2
INSERT  INTO t1 (x,y,z,) SELECT * FROM t2 ON CONFLICT FAIL
Any thoughts or hints?
Answer: First of all, on conflict is only for sqlite, and is used when you define the constraint (e.g. ... primary key on conflict abort ...). abort will not insert any rows if one of the rows fails. fail is even stranger: if you try to insert 5 rows and the 3rd row fails because of keys, it will insert the first 2 rows and stops then. So in short: don't use it. Both versions are NOT the same as ignore (at least for more than one row).
There is basically just one way to prevent the autoincrement when you insert multiple rows: don't insert rows that are already in the table.
The usual way to do that is to check if the row exists for yourself instead of the "lazy" on duplicate key/ignore. E.g. to check for duplicate values in a column y:
INSERT INTO t1 (x,y,z)
SELECT * FROM t2 main
where not exists (
    select * from t1 test
    where main.y = test.y);

Yes, I know, it will make your code longer. You will unfortunatly have to live with that.


What's it called when all the instruments cut out and only the vocals continue and then the instruments return?

Question: This is one of my favourite techniques within music (if it even is one). As such I would love to know what its called, thanks :)
Comment: Acapella? And after, tutti?
Comment: @Tim  minor nit:   A  capella ; two words.
Comment: @CarlWitthoft - many thanks. I just missed the space bar! Minor nit : ca**p**ella - source - she-goat. Actually a bright yellow star. Ca**pp**ella - source - chapel. Wearing that pointy hat again...
Comment: I use the term Vocal Break. Not sure where I picked the term up, maybe recording class.
Comment: Or tacet for orchestra?
Answer: If you're a musician, "tacet" ("silent") or "rest". If you're the vocalist, "a cappella" ("in the manner of the chapel").
If you're a sound engineer looking at a soundboard, you "solo" the channel (after the name of the button on the vocalist's channel on the board). This is very rare unless you're doing live looping and are doing your own sound.
Comment: I'm not objecting to the use of "vocalist" to refer to the singers; I'm objecting to the use of "musician" to refer to the instrumentalists.
Comment: Vocalists are musicians.  At least some of them are.
Comment: @phoog "musician who uses their voice" is a bit of a mouthful
Answer: This was posted 3 years ago, so I am sure you've found an answer by now (though I don't see one that feels right, I'm here looking for one too) but me and all my music friends call it a "false drop"! When it's a big full sound, the whole band, and then the band stops but the vocalist continues and you think they're going to end the song but then the whole band comes back in again!


What is the best way to pass values from one form to another with fapi?

Question: I have one form that is just an options input.  When I select a value then go to the next page there is another form that I want to have three hidden values based upon the chose value of the first form.
With Form API, what is the best way to pass the value from the first form to the next and have three values from the second form be determined by the single value chosen from the first form?
Comment: Normally you'd combine them both into a single [multi-step form](http://davidsonj.com/blog/how-create-multi-step-form-drupal-7) so the state is retained. I'd see if that's what you're looking for first, but if you can't use that method there are other ways so just update the question :)
Comment: @Clive will do, thanks for the point in the right direction
Comment: @Clive
I've created another question which is somewhat of an update of this one. http://drupal.stackexchange.com/questions/76550/why-is-my-multi-step-form-going-back-to-the-first-page-instead-of-moving-to-the
Answer: You can do a multistep form, there is a clear usage example in the Examples module. Here is an excerpt about it from the module's project page:

The Examples for Developers project aims to provide high-quality, well-documented API examples for a broad range of Drupal core functionality.
The Examples project contains many modules which hopefully illustrate best practices for implementing various Drupal APIs. These modules can be enabled individually, and will typically add menu items to your site, which should guide you through their features. You can then look through the code to see what they are doing.
Developers can learn how to use a particular API quickly by experimenting with the examples, and adapt them for their own use.
Note also that these modules demonstrate internals for Drupal development in PHP (and some JavaScript). Not all Drupal users will need these examples. There are many contributed modules which will do the majority of what a Drupal site-builder could need. Be sure and explore other contributed modules to see if you can find one that meets your needs.
Answer: Though multi-step form is your best choice, you can do it with two separate forms as well, using bit of trickery.
Say you have form_id_1 on your path1 URL. And another form_id_2 on your path2.
If you want pass values from the first form to the second, you have 2 options:
1) encode your values in form page path, like path2/arg1/arg2/arg3. Obvious downside is that arguments are visible to the user.
2) hijack Batch<->Form workflow. In form_id_1 submit handler use following code:
<code>$new_form_state = array();
// list path arguments that usually go into form_id_2 constructor from path2
$new_form_state['build_info']['args'] = array();
$new_form_state['method'] = 'post';
// list values you want to pass.
$new_form_state['values'] = array();
$_SESSION['batch_form_state'] = $new_form_state;
drupal_goto("path2");
</code>
User will be redirected to path2 and when form_id_2 is built for that page it will
have your values in its $form_state.


Como capturar todas as exceções em Python?

Question: Como capturar toda e qualquer exceção em Python? Há alguma palavra-chave para isso?
Como no Java que basta fazer um
try {
}
catch(Exception ex) {
}

Answer: É a mesma coisa. Só usar um try-except.
try:
    aluma_coisa()
except Exception as e:
    fazer_algo(e)

Comment: Isso @Wilker. Só que a Exception mais genérica do Python é a `BaseException`. Porém ela captura erros como `KeyboardInterrup` e `SystemExit` e geralmente não se quer isso.
Comment: para ver a exceção pode usar print(str(e))
Comment: Então Python, tem uma hierarquia semelhante ao Java? Vou estudar melhor.
Answer: Vou tentar acrescentar algo à resposta do @jbueno, visto que existem mais alguns detalhes no levantamento de exceções do Python. Só vou expor aqui o que considero mais importante, elucidando, principalmente, com exemplos. Explicação completa pode ser vista na documentação, nesse link.
Exception é a classe base para todas as exceções, se voce tem dúvidas de que o código pode levantar uma exceção, use o bloco try-except
try:
    f = open('file','w')
    f.write('testing Exception handling')
except IOError:
    print ("Erro, arquivo não encontrado ou erro nos dados")
else:
    print ('Sucesso na escrita do arquivo')

Clausula Except

Sem exceções
Veja que voce pode usar a clausula except sem explicitar a exceção, com isso voce vai considerar todas as exceções, mas isso não é considerado uma boa prática de programação, porque o desenvolvedor não consegue identificar a "raiz" do problema, em python tente sempre seguir uma das declarações da PEP 20 "Explicito é melhor que implicito".
Multiplas exceções
A cláusula except também aceita multiplas exceções.
try:
  # implementação
except (KeyError, IndexError)
  # Se houver qualque exception, execute esse bloco
...

Clausula try-finally

Voce pode usar finally junto com o try quando voce quer que um bloco seja executado de qualquer forma, ocorrendo exceção ou não.
try:
    f = open('file','w')
    f.write('testing Exception handling')
finally:
    # Esse bloco vai ser execudo de qualquer forma

Exemplos adicionais

Com try-finally-except.
try:
    f = open('file','w')
    try:
        f.write('testing Exception handling')
    finally:
        print ('Ok, fechando o arquivo')
        f.close()
except IOError:
    print "Erro arquivo ausente ou corrompido"

Um exemplo combinando exceções.
import sys

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except OSError as err:
    print("Erro de sistema operacional: {0}".format(err))
except ValueError:
    print("Impossível converter dados do arquivo em um inteiro.")
except:
    print("Erro inesperado:", sys.exc_info()[0])
    raise

Nesse exemplo, apresenta-se as informações da exceção.
def multply(x,y):
    try:
       r = (x*y)
    except Exception as e:
       print('Erro :')
       print ('Tipo: ', type(e))
       print ('Argumentos: ', e.args)
       print (e)
    else:
        return r

>>> multply('a','b')
Erro :
Tipo:  <class 'TypeError'>
Argumentos:  ("can't multiply sequence by non-int of type 'str'",)
can't multiply sequence by non-int of type 'str'

Easter Egg

Abra o console do python e digite:
>>> import this

Referencia
Errors and Exceptions.
PEP 20, O Zen do Python.


Inicializar apache e mysql no windows 7 32 Bits utilizando o Xampp

Question: Gostaria de inicializar o Apache e Mysql do Xampp assim que o sistema for inicializado, dei umas pesquisadas e achei isso:

Instalação do serviço: No C:/xampp/apache duplo-clique em "apache_installservice.bat".
  Desinstalação do serviço: No C:/xampp/apache duplo-clique em "apache_uninstallservice.bat"
Instalação do serviço: No C:/xampp/mysql duplo-clique em "mysql_installservice.bat". Desinstalação do serviço: No
  C:/xampp/mysql duplo-clique em "mysql_uninstallservice.bat"

Mas me deparei com o seguinte problema, quando executo ambos aparecem as seguintes mensagens a seguir, respectivamente:

Installing Apache2.4 as an Service
  Installing the 'Apache2.4' service
  (OS 5)Acesso negado.  : AH00369: Failed to open the Windows service manager, per
  haps you forgot to log in as Adminstrator?
  Now we Start Apache2.4 :)
  O nome de serviço é inválido.
Para obter mais ajuda, digite NET HELPMSG 2185.
Pressione qualquer tecla para continuar. . .

Installing MySQL as an Service
  O sistema não pode encontrar o arquivo especificado. Install/Remove of
  the Service Denied! Try to start the MySQL deamon as service ... O
  nome de serviço é inválido.
Para obter mais ajuda, digite NET HELPMSG 2185.
Pressione qualquer tecla para continuar. . .

Alguém poderia ajudar, agradeço!
Comment: Okay, deu certo! Obrigado!
Comment: Execute o `apache_installservice.bat` e `mysql_installservice.bat` como **Administrador** clicando o botão direito do mouse.
Comment: Você qr inicializar o apache e o mysql junto com o windows, é isso?
Comment: Sim @gato, quando o sistema iniciar ele já inicie, o apache e o mysql.
Comment: @LaércioLopes, Executando como Administador...  Installing MySQL as an Service
O sistema não pode encontrar o arquivo especificado.
Install/Remove of the Service Denied!
Try to start the MySQL deamon as service ...
O nome de serviço é inválido.

Para obter mais ajuda, digite NET HELPMSG 2185.

Pressione qualquer tecla para continuar. . .
Comment: Vai no **Painel de Controle**, **Contas de Usuário**, **Alterar configurações de Controle de Conta de Usuário** e abaixa o botão todo, reinicia o computador e tente novamente.
Comment: Vou colocar como resposta e você aceita ok?
Answer: Esta solução funciona para mim.
Abra o XAMPP Control Painel, e clique no botão config. Veja:

em seguida basta você habilitar o Autostart correspondente ao Mysql e o Apache e clicar no botão Save. Veja abaixo:

Mas, é necessário iniciar o XAMPP junto com o Windows, para fazer isso basta colar o caminho do atalho do XAMPP para esta pasta:

C:\Users\ USERNAME \AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

ou

C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp

No meu PC o caminho da pasta de inicialização do Windows é este:

C:\Users\Gato\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
Answer: Isto está acontecendo porque você está tentando executar esses arquivos .batsem os privilégios de uma conta de Administrador ou o Controle de Conta de Usuário está habilitado.
Para desabilitar o controle de conta vá em:

Painel de Controle, Contas de Usuário, Alterar configurações de
  Controle de Conta de Usuário, abaixa o botão todo, reinicia o
  computador e quando o Windows iniciar novamente tente executar os arquivos
  .bat.


Retrieve Facebook Profile Posts (Status) on Android

Question: I am new to Android and Java Development and I am trying to figure out a way to retrieve the current users Profile posts and save it in a Text File on my smart phone for further processes.
I am able to retrieve User Name, Email, Gender, Age Range and Birthday. so far everything works fine and the text file is being written when Facebook is connected with my Application.
Below class is how its coded in order to retrieve the mentioned Data, If anyone does know of how to retrieve posts as well via this method, please suggest?
Thanks!
package com.example.daunte_pc.anique;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.widget.Toast;

import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;

public class SocialActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
    private static final String TAG = "SocialActivity";
    LoginButton loginButton;
    CallbackManager callbackManager;
    ProgressDialog progressDialog;
    URL profile_pic;
    String id;
    DrawerLayout drawerLayout;
    ActionBarDrawerToggle actionBarDrawerToggle;

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

        drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
        actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.open,R.string.close);
        drawerLayout.addDrawerListener(actionBarDrawerToggle);
        NavigationView navigationView = (NavigationView)findViewById(R.id.navigation);
        actionBarDrawerToggle.syncState();
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        navigationView.setNavigationItemSelectedListener(this);

        FacebookSdk.sdkInitialize(getApplicationContext());
        loginButton = (LoginButton)findViewById(R.id.login_button);
        callbackManager = CallbackManager.Factory.create();
        loginButton.setReadPermissions(Arrays.asList("public_profile", "email", "user_birthday", "user_status","user_posts"));

        loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(final LoginResult loginResult) {
                progressDialog = new ProgressDialog(SocialActivity.this);
                progressDialog.setMessage("Please Wait! Anique_Profile's being processed!");
                progressDialog.show();
                String accessToken = loginResult.getAccessToken().getToken();
                Log.i("accessToken",accessToken);

                GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
                    @Override
                    public void onCompleted(JSONObject object, GraphResponse response) {
                        Log.i("Test",response.toString());

                        Bundle bFacebookData = getFacebookData(object);
                        String name = bFacebookData.getString( "name");
                        String email = bFacebookData.getString( "email");
                        String gender = bFacebookData.getString( "gender");
                        String profilepic = bFacebookData.getString( "profile_pic");
                        String age_range = bFacebookData.getString( "age_range");
                        String birthday = bFacebookData.getString( "birthday");
                        String posts = bFacebookData.getString( "posts{message}");

                        Intent in = new Intent(SocialActivity.this, Facebook_Profile.class);
                        in.putExtra("name", name);
                        in.putExtra("email", email);
                        in.putExtra("gender", gender);
                        in.putExtra("Image", profilepic);
                        in.putExtra("posts", posts);

                        startActivity(in);

                        try{
                            File root = new File(Environment.getExternalStorageDirectory(),"Anique Text Files");
                            if (! root.exists()){
                                root.mkdir();
                            }

                            File filePath = new File(root, "myFile.txt");
                            FileWriter writer = new FileWriter(filePath);
                            writer.append("Name : "+ name+"\n");
                            writer.append("\n");
                            writer.append("Email : "+ email+"\n");
                            writer.append("\n");
                            writer.append("Gender : "+ gender+"\n");
                            writer.append("\n");
                            writer.append("Age : "+ age_range+"\n");
                            writer.append("\n");
                            writer.append("Birthday : "+ birthday+"\n");
                            writer.append("\n");
                            writer.append("Posts : "+ posts+"\n");
                            writer.append("\n");
                            writer.flush();
                            writer.close();
                            Toast.makeText(SocialActivity.this,"Success!! Logged into Anique_Profile as per given user information. ",Toast.LENGTH_LONG).show();
                            Toast.makeText(SocialActivity.this, "Data is Written!", Toast.LENGTH_LONG).show();
                        }catch (Exception ex){
                            ex.printStackTrace();
                        }

                        progressDialog.hide();
                        finish();
                    }
                });

                Bundle params = new Bundle();
                params.putString("fields", "id, name, email, gender, age_range, birthday, posts, feed");
                request.setParameters(params);
                request.executeAsync();
            }

            @Override
            public void onCancel() {
            }

            @Override
            public void onError(FacebookException error) {
            }
        });
    }

    private Bundle getFacebookData(JSONObject object) {

        Bundle bundle = new Bundle();
        try{
            id = object.getString("id");
            profile_pic = new URL("https://graph.facebook.com/" + id + "/picture?width=200&height=200");
            Log.i("profile_pic", profile_pic +"");
            bundle.putString("profile_pic",profile_pic.toString());
        }catch (JSONException ex){
            ex.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        bundle.putString("idFacebook",id);

        if(object.has("name")){
            try{
                bundle.putString("name", object.getString("name"));
            }catch (JSONException ex){
                ex.printStackTrace();
            }
        }

        if(object.has("email")){
            try{
                bundle.putString("email", object.getString("email"));
            }catch (JSONException ex){
                ex.printStackTrace();
            }
        }

        if(object.has("gender")){
            try{
                bundle.putString("gender", object.getString("gender"));
            }catch (JSONException ex){
                ex.printStackTrace();
            }
        }

        if(object.has("age_range")){
            try{
                bundle.putString("age_range", object.getString("age_range"));
            }catch (JSONException ex){
                ex.printStackTrace();
            }
        }

        if(object.has("birthday")){
            try{
                bundle.putString("birthday", object.getString("birthday"));
            }catch (JSONException ex){
                ex.printStackTrace();
            }
        }

        if(object.has("posts")){
            try{
                bundle.putString("posts", object.getString("posts"));
            }catch (JSONException ex){
                ex.printStackTrace();
            }
        }

        return bundle;
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);
    }

}

Comment: _"to retrieve the current users Profile posts and save it in a Text File on my smart phone for further processes"_ - you need to do something with the data that more or less directly benefits the user's "in-app experience" to begin with ... Facebook will not approve this in review, if the sole purpose is background analysis of the data that has no direct connection to the user experience.
Comment: I understood. I want to get current users profile statuses for catching particular key words to predict something. There is no objection in showing the posts to user on my App. But that doesn't seem inappropriate since prediction is involved here. To be clear, still the user has nothing to do with his posts directly. Your suggestion? is it yet okay? @CBroe
Comment: Unless you are making that "prediction" for the benefit of the user - no.
Answer:
I want to get current users profile statuses for catching particular key words to predict something. There is no objection in showing the posts to user on my App. But that doesn't seem inappropriate since prediction is involved here.

You need to do something with the data that more or less directly benefits the user's "in-app experience" to begin with ... Facebook will not approve this in review, if the sole purpose is background analysis of the data that has no direct connection to the user experience.
The permission necessary to read a user's posts would be user_posts, but documentation lists this as one of the non-applicable use cases:

Non-visible use of this data such as sentiment analysis or guarding against spam bots.

https://developers.facebook.com/docs/facebook-login/permissions/v3.0#reference-user_posts
Comment: Thanks @CBroe, i figured out a way.


Colocar tag html no Jquery

Question: Não consigo colocar a tag
 do html no jquery.
$('#test').change(function(){
    $('#doenca_atual').val($('#doenca_atual').val()+"
 "+$('#test option:selected').text());
});

Ao invés de pular a linha com o
, ele simplesmente coloco o
 em modo texto

 Z98   Outr estados pos-cirurgicos
 Z95   Presenca implantes enxertos cardiacos vasc

Teria que ficar assim
Z98   Outr estados pos-cirurgicos
Z95   Presenca implantes enxertos cardiacos vasc

Comment: Mas o que é $('#doenca_atual')?? Um **input**, se for, não tem como dar quebra de linha neste elemento.
Comment: textarea não aceita br você tem que trocar por contrabarra N
Comment: eh um textarea do html
Answer: Você dá a entender que está adicionando as opções a um <textarea>, a quebra de linha para esse elemento não é o
, mas sim o \r\n. Também não é necessário substituir todo o conteúdo, basta adicionar a nova seleção.

$('#test').change(() => {

  let selecionado = $('#test option:selected');

  if (selecionado.val() != "")
    $('#doenca_atual').append(`${selecionado.text()}\r\n`);

  //remove o item da lista
  selecionado.remove();
  //retorna a seleção para o primeiro item
  $('#test').val("");

});

<select id="test">
  <option value="">selecione</option>"
  <option value="doenca 1">doenca 1</option>
  <option value="doenca 1">doenca 2</option>
  <option value="doenca 1">doenca 3</option>
  <option value="doenca 1">doenca 4</option>
  <option value="doenca 1">doenca 5</option>
</select>

<textarea id="doenca_atual" rows="10"></textarea>

Colocar tag html no Jquery