What is different about the q-value and local FDR?

Question: What is different about the q-value and local FDR when both are defined as posterior probabilities of the null being true?
For example in Storey (2010),

Under these modeling assumptions, it follows that q-value(pi) = mint≥pi Pr(Hi = 0|Pi ≤ t), which is a Bayesian analogue of the p-value – or rather a "Bayesian posterior Type I error rate."

But the definition of the local FDR given just a few lines later seems quite the same

This connects the pFDR to the posterior error probability Pr(Hi = 0|Pi = pi), making this latter quantity sometimes interpreted as a local false discovery rate (Efron et al. 2001, Storey 2001).

I can see the mathematical definitions are different, but what's different conceptually?
Answer: q-value is a tail probability as you can see by your definition, it is the minimum pFDR in which you will still reject the corresponding hypothesis.
pFDR is defined as $E(V / R | R > 0)$, which I encountered also as Bayesian FDR.
The local FDR ($fdr$) is the probability that the hypothesis comes from the null at a specific value of the statistic.
The connection between the two is the following:
$pFDR(z) = P(H_i = 0| R_i = 1) = E_{Z|R_i=1}P(H_i=0|Z)=E_{Z|R_i=1}fdr(Z_i)$
Comment: Keep in mind that any frequentist-based method that uses null hypotheses is going to suffer from higher type I and type II errors when multiplicity adjusting than can be achieved with simple likelihood ratios.  Most multiplicity errors come from using null hypotheses instead of demanding that differences be non-trivial (i.e, using null hypotheses where something greater than zero is hypothesized).  See https://www.statisticalevidence.com/
Comment: @FrankHarrell I agree. I find a parameter estimation approach and aiming to reduce Type M and Type S errors --- the underlying cause of classical Type I and Type II errors. I find Bayesian modeling to be ideal for this, and if I do a hypothesis test, Bayes Factors are preferable. Nevertheless I like to understand other perspectives and FDR seems far more agreeable within a frequentist context than FWER.
Comment: Just note that likelihood ratios are much simpler than Bayes factors here, and work extremely well.  But I prefer global Bayesian modeling if computational issues not too severe.


Rudimentary results in iterated forcing.

Question: What are some relatively basic and fun results using iterated forcing that I can include in my undergraduate thesis in the section I'm going to title "Rudimentary applications." It's the section following the section titled "Fundamental Theorems of Iterated Forcing."
Eventually, in some other section, I'm going to include the result by Dow, Tall, and Weiss on the consistency of the Normal Moore Space conjecture, which is obtained by an iteration of cohen forcing of supercompact length.
Comment: It depends what you call basic. You can control the exponential function on regular cardinals (Easton). If this seems too involved, you can do it for countably many consecutive cardinals without much effort. There is the consistency of Martin's axiom. Many of the consistency results regarding the Cichon diagram.
Comment: @AndrésE.Caicedo Perhaps basic can be taken to mean around the difficulty of consitency of MA (which I've seen somewhat). These results on Chichon diagram I find very beautiful and interesting. Do you happen to know off the top of your head which of them use an infinite iteration?  (Or some recommended bibliography.)
Comment: I would suggest reading Blass's chapter in the Handbook of set theory and some of the Bartoszynski-Judah book for inequalities among classical cardinal characteristics, together with Baumgartner's paper on iterated forcing. The reason for the latter is that many of these arguments require understanding of countable support iterations.
Answer:
The grandfather, O.G., result by iteration: Martin's Axiom.
You can include also its more sophisticated offspring, $\sf PFA$ and $\sf MM$ or other forcing axioms, but then you need to start with a supercompact cardinal.

Another very interesting result would be the Mitchell proof that assuming a weakly compact cardinal, it is consistent that $\aleph_2$ has the tree property. This is done with a mixed-support of Levy collapses and Cohen reals.

And of course, if we are talking about nontrivial supports, then Easton's theorem that assuming $\sf GCH$, any function on regular cardinal satisfying: $F(\kappa)\leq F(\lambda)$ for $\kappa\leq\lambda$, and $\operatorname{cf}(F(\kappa))>\kappa$ is a possible continuum function for regular cardinals.
(Of course, Easton's original proof is by using a product, but you can also use an iteration. And a product is a kind of iteration, after all...)
Comment: @JPLK A finite iteration $\mathbb P*\dot{\mathbb Q}$ involves a poset in the ground model and a poset in the extension. A product $\mathbb P\times\mathbb Q$ involves two posets in the ground model. Finite products can be seen as finite iterations, but in general the poset with $\mathbb P$-name $\dot{\mathbb Q}$ is a genuinely new object. There are differences between the two procedures. For instance, you may want to read about the differences between the product $\mathsf{RAN}_{\omega}\times\mathsf{RAN}_{\omega}$ and the iteration $\mathsf{RAN}_{\omega}*\dot{\mathsf{RAN}_{\omega}}$.
Comment: @JPLK: Okay. I think that maybe it would be a good idea for you to learn more about what are products and iterations. Because your understanding is completely wrong.
Comment: With the exception of possibly MA, I'm not sure these could be called "rudimentary." But they're all good examples.
Comment: True, not very rudimentary, but not very complicated, and quite important, I'd say, to the development of iterated forcing.
Comment: Oh of course (and I upvoted) - I just wanted to clarify for the OP that these are difficult results.
Comment: I think the consistency of $\mathsf{MM}$ is too technical if one is actually going to provide all details.
Comment: @Andrés: MM or MA? Because the MM one was only there as an anecdote. I wouldn't even suggest to include PFA in an undergraduate thesis...
Comment: $\mathsf{MM}$. I read your item 1 as a suggestion to include the arguments for all three of $\mathsf{MA}$, $\mathsf{PFA}$, and $\mathsf{MM}$.
Comment: Oh, no. I meant that MA is the one to be included, PFA and MM are just worth a mention, since the technique is "essentially the same, modulo the difference in the technical complexity of the definitions and the actual details"... :)
Comment: What do you mean when you say "you can also use an iteration" for Easton's result? D you mean an infinite iteration instead of (finite) a product? Where can I read this version of the proof? (My understanding is that it is called an interation it is of infinite length and a product if finite.)
Comment: (@JPLK Here, $\mathsf{RAN}_\omega$ is the poset for adding a random real, as computed in the ground model. So, in the iteration, the second factor is the poset that adds a random real to the extension.)
Comment: @AsafKaragila You're right, I had forgotten some of the terminology, I understand the difference (as explained very clearly in Andres' comment). Can you guide me towards the iteration version of Easton's result? Thank you for your time.
Comment: @JPLK: I think that Jech's big book should have something on that. I think that taking Andrés suggestion on your question and looking at a finite set of cardinals would be a very good first step in this area.
Comment: @JPLK Note that part of my answer (the second paragraph) is all about the difference between iterations and products, even in the finite case.
Answer: The proof of the consistency of ZFC+$\neg$CH+MA uses an iterated forcing argument; I wouldn't necessarily call it "rudimentary," but it's definitely simpler than the consistency of the normal Moore space conjecture.
A simpler result, which is however of less general interest in my opinion, is the consistency relative to ZFC of ZFC+"There are exactly three degrees of constructibility of real numbers." The proof is a two-step iteration of Sacks forcing over a model of ZFC+V=L: the first step produces a unique nonzero constructibility degree of a real, and the second step produces a unique nonzero constructibility degree of a real above the first one. This is a nice case where we see vividly the difference between the product and the support, since the product $\mathbb{S}\times\mathbb{S}$ of two Sacks forcings over $L$ yields four degrees of constructibility of reals: the trivial one, the left generic, the right generic, and their join. (A nice coda to this is the observation that the crucial property is that the Sacks forcing of a generic extension is not the same as the Sacks forcing of the ground model.)
Finally, there are cardinal characteristic separations. These are simpler than the MA case and more inherently interesting in my opinion than the "three degrees" result. There are many of them, and I'll leave it to you to pick a favorite.


Can we revert a last git pull on my local machine only?

Question: I have pulled data from a shared repository, but seems to be some errors on the remote. I can not fix his errors and commit back the code. I want to revert my code before pull and work on the feature on which I was working on.
Doing only git revert sha will work? I don't want to push my revert to the server.
What should I do?
Answer: git revert generates a new commit. Try to git reset --hard sha where sha is the commit id of your last working commit.
That will reset your HEAD to that commit and so deletes all following commits, which should be the commits you just pulled.
Caution: Can cause data loss on wrong usage.
Comment: Note that `git reset --hard` will delete any uncomitted changes.
Comment: @phortx / @ikke : This is my git status
`$ git status
# On branch develop
nothing to commit, working directory clean`

I think there would have no any loss, right?
Comment: Then it's no problem. To be sure, just copy your directory ;)


I'm trying to compare 2 variables with my enum's type

Question: I created an Enum wearState and then gave wearState as a type for two variables. But when I try to put them in a if condition with '||' or '&&', it doesn't work.
It says : "error : bad operand types for binary operator '||' "
enum wearState {
        WRIST_MOVE,
        WRIST_IMMOBILE,
        BELT_NECK_MOVE,
        BELT_NECK_IMMOBILE,
        OTHER_IMMOBILE_STATE;
    }

enum chargingState {
        YES,
        NO,
    }

wearState lastState;
wearState currentState;
chargingState lastStateCharging;
chargingState currentStateCharging;

if (((currentState = wearState.BELT_NECK_IMMOBILE) || (currentState = wearState.WRIST_IMMOBILE)) &&
    (lastStateCharging = chargingState.NO)) {

              /* .... */
 }

Comment: Compare with `==`, not `=` . Single `=` is for assigning a value only .
Comment: You are doing an assignment currentState = wearState.BELT_NECK_IMMOBILE
no matter which value currentState had originally, after this condition, it's value is BELT_NECK_IMMOBILE, you need to use == instead
Answer: if (((currentState == wearState.BELT_NECK_IMMOBILE) || (currentState == wearState.WRIST_IMMOBILE)) &&
(lastStateCharging == chargingState.NO))

while comparing whether two variables please use "==",
= is an assignment operator.
it can be used only for assigning a value to variable like,
String name="Joe";

to compare to variable we should use comparison operators.
==,<=,>=,!=,<,>
are the comparison operators;
Comment: so far you add no additional information when compared to the comments. You don't even state why it should be == instead of =
Comment: thank you for info. i didn't notice the above comments
Comment: don't recommend to compare 'variables' using ==. Especially not if later on you use a String variable as example how = is assigning a value. == should only be used for primitives, singletons (why even) and enums


How to return value into the script of another Vue file? Or how to sent returned value into another Vue file?

Question: In the main page, I got the value I want which are "time" and "breedKey" already. Now, how can I use them in another Vue file like the example I provide next
   data() {
        return {
          time:[]
        }
    },

    computed: {
       breedKey() {
         return this.breeds[this.currentBreed].key;
        }
      }

This is the child page


Well-ordering of natural numbers from axioms of real numbers

Question: Let $(\mathbb R,+,\times,<)$ be an ordered field that is Dedekind complete. Let $\mathbb N$ be the intersection of all additive submonoids $M \subseteq \mathbb R$ with $1 \in M$. The question is, can we prove that every subset of $\mathbb N$ has a least element (i.e. well-ordering principle)? If not, can we "construct" a model of $\mathbb R$ such that $\mathbb N$ does not have the well-ordering principle (apologize for the language as I am not a model theorist)?
This is inspired by the answer https://math.stackexchange.com/a/2214227/553409, although I don't think Proposition 3 in the cited answer works. In particular, elements of $\mathbb N$ may get arbitrarily closed to each other.
[1]: https://math.stackexchange.com/a/2214227/553409
Comment: @QiaochuYuan isn't the point to not "know" what the usual $\mathbb{N}$ and its properties are?
Comment: Yes, and it's not necessary to assume Dedekind completeness, this is true for any ordered field. Just show that $\mathbb{N}$ is the additive submonoid generated by $1$ and that this monoid is isomorphic to the usual $\mathbb{N}$.
Answer: If you already know that the usual naturals exist and are a monoid, than per Qiaochu Yuan's comment it's kind of immediate.
However, you can prove it without this fact.  That is, without the axiom of infinity, (and, for that matter, without using completeness of the reals, which is unnecessary and generally not helpful*), just starting from the fact (taken as axiom) that $\mathbb R$ is an ordered integral domain, you can argue that the smallest inductive subset (i.e., a subset $S\subseteq \mathbb R$ such that $1\in S$ and such that $x\in S$ implies $x+1\in S$) is well-ordered.
From that, you can show (essentially by the same induction-type arguments used in the link, or you can use actual induction since you have established well-ordering) that such a minimal inductive set is a submonoid, and therefore the minimal submonoid containing $1$ is contained in the minimal inductive set.  But a submonoid containing $1$ is itself inductive, so the minimal such submonoid then coincides with the minimal inductive set, and is therefore well-ordered as well.
update
I missed the fact that since we are talking about additive monoids, we should slightly alter the definition of inductive set to say that $S$ is inductive if $0\in S$ and whenever $x\in S$, $x+1\in S$.  All of the arguments (including at the link) still go exactly the same way.
*(I also do not understand proposition 3 at the link you provided, it seems unjustified to me.)
Answer: $1\in M \implies \mathbb N \subseteq M$
$\forall M, 1\in M\implies \forall M, \mathbb N\subseteq M$
$\mathbb N \cap M = \mathbb N.$
Let $E\subseteq  \mathbb N, E \ne \emptyset$.
$x\in E \implies x>0$.
So E is non-empty and bounded below.
Every non-empty subset of the reals that is bounded below has a greatest lower bound as a corollary of the Completeness Axiom of the Reals.
So $\exists \alpha\in \mathbb R, x\in E \implies \alpha \le x.$
$ \exists x\in E | \alpha \le x\le \alpha+1 $ otherwise $\alpha +1$ itself would be a lower bound of E contradicting the assumption that $\alpha$ is the g.l.b.
Suppose $\alpha< x \le \alpha +1, y\in E$.
$\alpha \le x \le \alpha +1 \le x+1$ and suppose $x<y<x+1$
Then $\alpha -x \le 0 \le \alpha +1-x\le 1$ and $0<y-x<1$. This implies $x$ and $y$ are elements of a non-minimal sub-monoid.
So $x$ is a greater lower bound. Again contradicting the assumption that $\alpha$ is the greatest lower bound.
So $x=\alpha \in E$.
So every non-empty subset of the natural numbers  contains a least element: This is the well-ordering principle.
Comment: I'm not quite following this update. You supposed $y\in E$ with $x<y<x+1$, then concluded $y-x\in (0,1)$, but how does that imply anything about $y$ and $x$ individually?


Symfony 3 JSONResponse on Android

Question: so im using a createQuery to connect to my symfony database with Doctrine like this
// JSON ACTION
public function jsonAction()
{
$em = $this->getDoctrine()->getEntityManager();
$query = $em->createQuery('SELECT pa FROM CBMedBundle:Patients pa');
$myArray = $query->getArrayResult();
return new JsonResponse($myArray);
}

At url : http://localhost/Symfony/web/app_dev.php/json
Now i want to export the result (jsonreponse) on Android (eclipse android) and show the response there !
How can i do that ?
I found this code on google about showing a json code on Android but i don't know how to adapt it for my problem . Thanks
    public class MainActivity extends Activity {
        TextView t;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            t = (TextView) findViewById(R.id.text1);
         StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
         StrictMode.setThreadPolicy(policy);
         t.setText(getServerData(strURL));
        }
         public static final String strURL = "http://10.0.2.2/connexion.php";

         private String getServerData(String returnString) {
             InputStream is = null;
             String result ="";

             ArrayList<NameValuePair> nameValuePaires = new ArrayList<NameValuePair>();
             nameValuePaires.add(new BasicNameValuePair("tblville","tblville"));
             // Envoie de la commande Http
             try{
                 HttpClient httpclient = new DefaultHttpClient();
                 HttpPost httppost = new HttpPost(strURL);
                 httppost.setEntity(new UrlEncodedFormEntity(nameValuePaires));
                 HttpResponse response = httpclient.execute(httppost);
                 HttpEntity entity = response.getEntity();
                 is = entity.getContent();
         }
         catch(Exception e){
          Log.e("log_tag","Error in http connection "+e.toString());
           }

         //conversion de la réponse en chaine de caractère
            try
            {
             BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));

             StringBuilder sb  = new StringBuilder();

             String line = null;

             while ((line = reader.readLine()) != null)
             {
                  sb.append(line + "\n");
             }

             is.close();

             result = sb.toString();
            }
            catch(Exception e)
            {
             Log.e("log_tag","Error converting result"+e.toString());
            }
            //recuperation des donnees json
            try{
              JSONArray jArray = new JSONArray(result);

                 for(int i=0;i<jArray.length();i++)
                 {

                       JSONObject json_data = jArray.getJSONObject(i);
                       Log.i("log_tag","ID_ville : "+json_data.getString("ID_ville")+" , Nom_ville : "+json_data.getString("Nom_ville")
                               );
                        returnString += "\n\t" + jArray.getJSONObject(i);

                }
            }
                catch(JSONException e){
                 Log.e("log_tag","Error Parsing data"+e.toString());
                }
                return returnString;

    }
    }

EDIT : The JSONresponse Result
[{"id":1,"nom":"Kane","prenom":"Samba","DateNaissance":{"date":"1995-03-08     00:00:00","timezone_type":3,"timezone":"Europe\/Paris"},"LieudeNaissance":"Nouakchott","sexe":"Homme","adresse":"Tunis","profession":"Etudiant","NumerodeTel":"+21629760962","Email":"email@example.com","SituationFamilial":"Mari\u00e9"},{"id":2,"nom":"Bebeskho","prenom":"AllStar","DateNaissance":{"date":"1995-02-08 00:00:00","timezone_type":3,"timezone":"Europe\/Paris"},"LieudeNaissance":"Bamako","sexe":"Homme","adresse":"Tunis","profession":"Cuisinier","NumerodeTel":"+2167583486","Email":"firstname.lastname@example.com","SituationFamilial":"C\u00e9libataire"},{"id":3,"nom":"Vecenzo","prenom":"Gaimno","DateNaissance":{"date":"1995-01-01 00:00:00","timezone_type":3,"timezone":"Europe\/Paris"},"LieudeNaissance":"Tunis","sexe":"Homme","adresse":"Ariana","profession":"Etudiant","NumerodeTel":"+21654758","Email":"vecenzogo","SituationFamilial":"Mari\u00e9"},{"id":4,"nom":"Diara","prenom":"Bakary","DateNaissance":{"date":"1995-06-10 00:00:00","timezone_type":3,"timezone":"Europe\/Paris"},"LieudeNaissance":"Dakar","sexe":"Homme","adresse":"Dakar Sacr\u00e9 Coeur","profession":"Etudiant","NumerodeTel":"+2214753526","Email":"firstname.lastname@example.com","SituationFamilial":"C\u00e9libataire"}]

JsonResponse Image
Now , i just want to show this result on my Android emulator application (eclipse)
Comment: Can you paste the JSON response that your server generates? You'd want to parse this JSON in your Android code  -so it will help us to see how it looks like and we can advise you.
Answer: To adapt the code for your purposes - you need to change the URL to point to your server. Change public static final String strURL = "http://10.0.2.2/connexion.php"; to something like http://<your-server-ip-address>/Symfony/web/app_dev.php/json (I am assuming HTTP-GET request returns the JSON array you pasted). You then modify the JSON processing code to extract details that are contained in your JSON file - like this:
    for(int i=0;i<jArray.length();i++)
     {

        JSONObject personJSONData= jArray.getJSONObject(i);
        String id = personJSONData.getString("id");
        String nom = personJSONData.getString("nom");
        //do the same for the other attributes
        //note that according to your JSON file, DateNaissance is a JSONObject - so you have to do something like
       JSONObject dateNaissanceObject = personJSONData.getJSONObject("DateNaissance");

 }

But I'd really recommend that you use something like Gson to parse the incoming JSON payload into a list of "Person" objects, for instance. As an example, and assuming you have created a Person class, you'd do this:
List<Person> persons = gson.fromJson(result, new TypeToken<List<Person>>(){}.getType());
. Here is a nice example of this - and here is another nice example using Gson - there's also a good tutorial here.

Symfony 3 JSONResponse on Android


Usando entrada e saída padrão no Android

Question: Quando aprendi a programar em Java usava muito a entrada e saída padrão (stdin e stdout). Agora que tenho curiosidade em aprender o que posso fazer no Android, queria saber se por questão de praticidade posso fazer o mesmo que fazia na plataforma Java SE, que é: criar um aplicativo "console".
Com um aplicativo console nós podemos fazer coisas bem práticas como por exemplo:
Direcionar a saída do programa para outros utilitários Unix (no Android requer o Busybox).
am start -n com.example.android/.MainActivity | sort -u | sed ... > saída.txt

Ou então direcionar a saída de outros programas para entrada padrão do meu programa.
logcat|am start -n com.example.android/.MainActivity

Cheguei a experimentar o Jackpal Terminal Emulator e percebi que ele usa estes recursos:

Android absolutely supports pipes as well as unix domain sockets. Use
  of exec is somewhat discouraged, but works at the moment.
See the source of any android terminal emulator with a local shell
  option for an example of how to do it. Essentially your gui just
  replaces the terminal emulator, and your engine replaces the shell.
  Chris Stratton

Ver também

Redirecting STDIN and STDOUT of C program in Android
Console input cannot be read when c++ Android NDK app is build as executable
How to run a specific Android app using Terminal?
Comment: Não precisa remover pra fazer uma nova pergunta, entenda que o contexto daqui foi respondido, basta fazer uma nova como se fosse sequencia desta. Eu mesmo faço várias perguntas, teve algumas sobre [tag:ngnix] que eram uma sequencia de necessidade da outra, claro que você pode editar. Só uma dica, não somos um fórum, somo uma Q&A ;)
Comment: Reverti a pergunta para o original e pra você não ter trabalho aqui esta o seu texto pra fazer uma nova pergunta http://pt.stackoverflow.com/revisions/125795/5
Comment: Mas usando o AndroidStudio ou AndroidEclipse os `System.out.print` mostra no terminal do proprio IDE a saida pra você depurar e se você estiver com o cabo ligado do celular e os drivers devidamente instalado para o aparelho você poderá instalar seu app em desenvolvimento diretamente no celular e a saida irá voltar para o IDE, mesmo que rodando no celular. Outra coisa o ADT tem emulador. -- Pra ser sincero não entendi a sua pergunta.
Comment: Obrigado pela observação @GuilhermeNascimento, então, disso eu já estou consciente. Mas por exemplo, seu eu sair com meu Smartphone, estiver na rua e quiser deixar um aplicativo rondando no background e também quiser ver sua saída? Queria uma sugestão em como posso visualizar logs no próprio Smartphone.
Comment: então você teria que criar um campo de texto no proprio app e trocar `System.out` por um método de append no textfield e o background rodaria em um trhead
Comment: se eu aceito uma resposta outros ainda podem responder ou eu tenho que desmarcar a resposta? @GuilhermeNascimento
Comment: @guiwp uma pergunta pode ter inumeras respostas, porém, somente uma aceita. E isso não impede que outros continuem postando respostas.  Mas no caso desta, não é possivel mais responder, pois foi fechada como pendente. Veja as orientações no quadro amarelo e, se já tiver feito as alterações solicitadas, aguarde até que a mesma seja reaberta.
Comment: Obrigado @DiegoF, fiz as alterações esclarecendo melhor minha pergunta colocando mais detalhes e inclusive mudando o título da pergunta. Tudo para ficar mais claro.
Comment: Outros podem responder sim, mesmo que já tenha uma resposta aceita, todavia eu discordo da sua edição, quando for assim faça uma nova pergunta. Vou fazer um rollback porque você mudou o contexto do que foi perguntando.
Comment: DiegoF, @GuilhermeNascimento, se vcs quiserem eu solicito que remova essa pergunta para que eu possa fazer outra com mais detalhes (não hoje, outro dia)! De qualquer forma muito obrigado, estou aprendendo a mexer nisso daqui! abraço!
Comment: Gostei dessa "não somos um fórum, somo uma Q&A ;)" kkkk. Tudo ok amigo, espero entender melhor esse negocio aqui para não da trabalho para vcs!
Comment: hoje dei uma olhada sobre o assunto e aprendi coisas novas e resolvi compartilhar atualizando o corpo do texto
Answer: Conforme o SOen uma maneira de pegar os dados do console seria:
// Create a stream to hold the output
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);

// IMPORTANT: Save the old System.out!
PrintStream old = System.out;

// Tell Java to use your special stream
System.setOut(ps);

System.out.println("Foofoofoo!");
// Put things back
System.out.flush();
System.setOut(old);

baos.toString(); //Pega os dados

Depois pegue esse baos.toString(); e coloque em um TextField ou similar.
Também pode-se trocar System.out.print por uma função própria que faria um append no TextField.
Comment: Parece uma alternativa interessante, vou estudá-la.


Set boolean (single on/off checkbox) value while creating a user

Question: I am creating a user programmatically and there is a boolean field (single on/off checkbox) being used as a terms of use inside the users profile.
How do I set the value of it when creating a user object? I need it to be checked or 1.
<code>$new_user = array(
                'name' => $username,
                'mail' => $email,
                //'pass' => $pass,
                'signature_format' => 'full_html',
                'status' => 1,
                'access' => 0,
                'timezone' => 'America/New_York',
                'init' => $email,
                'field_user_account_terms' => array(
                    'attributes' => array(
                        'checked' => 'checked',
                    ),
                ),
              );

$account = user_save(NULL, $new_user);
</code>
i've also tried
<code>                    'field_user_account_terms' => array(
                    'und' => array(
                        0 => array(
                            'value' =>  1,
                        ),
                    ),
                ),
</code>
I've also tried setting the default value and a bunch of other syntax. Nothing seems to be working for me.
is this even possible? What is the correct syntax for setting the value of a checkbox, to be saved in a users profile?
Comment: Are you sure "1" is the checkbox key? You'll need to use the field value key there, as per your second solution above.
Comment: @DavidThomas i'm not sure I just assumed 0 or 1 because it's boolean. or checked because it's a checkbox. I can't find a working solution.
Answer: The help message for this field says: If left empty, "1" will be used and if left empty, "0" will be used. So I left this field blank and assumed you could programmatically set the value while creating a user. This doesn't work at all for me.

You actually have to explicitly define the On and Off values in order to be able to set them while creating a user.

Then you can set the value in the user object.
<code>'field_user_account_terms' => array(
                'und' => array(
                    0 => array(
                        'value' =>  1,
                    ),
                ),
            ),
</code>


Prove that $\sec^2x$ is $C^{\infty} $on $(-\pi /2, \pi /2) $?

Question:
How can I prove that $\sec^2x$ is a $C^{\infty} $  map on $(-\pi /2, \pi /2) $?

If I just try repeated differentiation the expression get complicated.  So how can I see that every derivative will be continuous?
Answer: Use the facts that $x \mapsto \cos x$ is smooth on $(-\frac{\pi}{2}, \frac{\pi}{2})$, that $x \mapsto x^2$ is smooth everywhere, and that $x \mapsto \frac{1}{x}$ is smooth on $(0,\infty)$. Moreover, the composite of smooth functions is smooth.
Comment: @Alexander: This method does that.
Comment: I want to show that it is $C^{\infty} $
Comment: OK understand now, thanks!


Show that $f$ has no rational root.

Question:
Question: Let $f(x)=a_0+a_1x+a_2x^2+a_3x^3$ be a polynomial with integer coefficients such that $a_0,a_3$ and $f(1)$ are odd. Show that $f$ has no rational root.

Solution: Let us assume for the sake of contradiction that $f(x)$ has a rational root $\frac{p}{q}$ where $p,q\in\mathbb{Z},q\neq 0$ and $\gcd(p,q)=1$. Thus by rational root theorem, we can conclude that $p|a_0$ and $q|a_3$. Now since $a_0$ is odd, implies that $p$ is also odd. Similarly, $q$ is also odd. Now since $f(1)=a_0+a_1+a_2+a_3$ is odd and both $a_0$ and $a_3$ are odd, implies that $a_1+a_2$ is also odd.
Also since $\frac{p}{q}$ is a root of $f(x)$, implies that $$a_0+a_1\frac{p}{q}+a_2\frac{p^2}{q^2}+a_3\frac{p^3}{q^3}=0\\\implies a_0q^3+a_1pq^2+a_2p^2q+a_3p^3=0\hspace{0.5 cm}...(i).$$
Thus two cases are possible: (1) $a_1$ is odd and $a_2$ is even, (2) $a_1$ is even and $a_2$ is odd.
Now if (1) is true then, $a_0q^3,a_1pq^2,a_3p^3$ are all odd and $a_2p^2q $ is even. This implies that $a_0q^3+a_1pq^2+a_2p^2q+a_3p^3$ is odd. But, by $(i)$, we have $a_0q^3+a_1pq^2+a_2p^2q+a_3p^3=0,$ which is even. Hence, we arrive at a contradiction. Hence $f(x)$ has no rational root in this case.
Working similarly we will arrive at a contradiction for Case (2) also.
Thus, we can conclude that $f$ does not have a rational root.
Is this solution correct. If yes, then, is there a better solution?
Answer: If $p/q$ is a root such that $\gcd(p,q)=1$, then by Gauss Lemma, $qx-p$ is a factor of $f(x)$ over $\mathbb{Z}$. It's also clear that $p,q$ are both odd. But this is a contradiction, since $q-p$ (an even number) is a factor of $f(1)$, which is odd,
Answer: Your solutions is correct for me.
I propose another solutions: looking the polynomial modulo $2$ we have only two possible cases:
\begin{gather}
f_1(x) = x^3+x^2+1\\
f_2(x) = x^3+x+1
\end{gather}
But they have degree $3$ and they have no roots in $\mathbb Z/(2)$. Hence they are irreducible and $f(x)$ is irreducible.

Show that $f$ has no rational root.


how to find the weblogic server start time in unix box

Question: how to find the weblogic server start time in unix.
i have give ps -f | grep port number
but it is showing my current system time.
how to find this
Answer: I use this in in Linux and Solaris to find a process in ps based listening ports.
ps -ef | grep `lsof  -i :7001 | grep "LISTEN"|awk '{print $2}'`
Answer: Add e(Select all processes) argument:
<code>ps -ef | grep PORT_NUMBER
</code>
Answer: It depends on the time resolution you need. If the process started more than 24 hours ago you'll have only the date of its start given in ps -ef output.
Try looking into the system's logs. There's a good chance that the starting server wrote a line or two into the log.


Another proof of $\lim\limits_{\theta \to 0} \frac{\sin\theta}{\theta} = 1$

Question: I am sorry if this is a duplicate question, but as far as I searched I have not come across this question.

$\lim\limits_{\theta \to 0} \frac{\sin\theta}{\theta} =  1$. This formula is famously proven by geometrical means using area of a circle and so on..

I want to know if this method of proof over l-hopital's Rule is also acceptable.
$$\lim\limits_{\theta \to 0} \frac{\sin\theta}{\theta} = \lim_{\theta \to 0} \frac{\cos \theta}{1} = 1$$
If there is any other method to prove apart from the two methods above. Please Share. Thank You!
Comment: Lots of ways to do this: see [here](https://math.stackexchange.com/questions/75130/how-to-prove-that-lim-limits-x-to0-frac-sin-xx-1).
Comment: The fact that derivative of $\sin x$ with respect to $x$ is $\cos x$ already includes the fact that the limit in question is $1$ (via special case $x=0$). So your approach is circular / roundabout.
Comment: L'Hospital's rule is circular because that limit shows up in the derivation of the derivative of the sine function.
Comment: You can use Taylor series or just Mean Value Theoem.
Comment: Squeeze theorem always works with $y = x^2 + 1$ and $y = -x^2 + 1$.
Answer: Hint $:$ $\sin x < x < \tan x$ for $x \in \left (0, \frac {\pi} {2} \right )$ and $\tan x < x < \sin x$ for $x \in \left (-\frac {\pi} {2} , 0 \right ).$ Now use Squeeze theorem to conclude.
Answer: $$sin(\theta)=\sum_{n=0}^\infty \frac{(-1)^n{\theta}^{2n+1}}{(2n+1)!}=\theta-\frac{(\theta)^3}{3!}+\frac{(\theta)^5}{5!}+....$$then$$\frac{sin(\theta)}{\theta}=1-\frac{(\theta)^2}{3!}+\frac{(\theta)^4}{5!}+....$$ and the limit as $\theta\rightarrow 0$ is 1
Answer: An other proof using the definition of the derivative, actually it is equivalent to the Hospital Rule but you explain why this result works. We have on one hand $\sin'(0)=\cos(0)=1$. On the other hand $\sin'(0) =\lim\limits_{\theta \to 0} \frac{\sin\theta - \sin 0}{\theta - 0} =\lim\limits_{\theta \to 0} \frac{\sin\theta}{\theta}$. So $\lim\limits_{\theta \to 0} \frac{\sin\theta}{\theta}=1$.


specify group_by variables programmatically in targets workflow with static branching

Question: I'm using the targets package in R to organize data processing and analysis for some studies that involve multiple different data sources (surveys, performance metrics on different tasks, etc).  Because some of the tasks produce large quantities of data, I have to use dynamic branching to limit how much data I'm trying to load into R at any given time.
I've started using static branching as well to better organize the workflow, but I'm running into an issue, and I'm hoping there is a work-around.  I would like to be able to define the variables I want to group by in tar_group_by or tar_group_select in my list/tibble of parameters to send to tar_map, as seen in the following reprex:
library(targets)

targets::tar_dir({
  targets::tar_script({
    library(targets)
    library(tarchetypes)
    library(tidyverse)

    df1 <- data.frame(
      g1 = rep(LETTERS[1:3], 2),
      x = 1:6,
      y = 1:6
    ) |>
      group_by(g1)

    df2 <- data.frame(
      g1 = rep(LETTERS[1:3], 2),
      g2 = rep(LETTERS[4:6], 2),
      x = 1:6,
      y = 1:6
    ) |>
      group_by(g2)

    list(
      label = c("group1", "group2"),
      source = c("df1", "df2") |> syms(),
      by = c("g1", 'g2')  # group by g1 for df1 and g2 for df2
    ) |>
      tar_map(
        names = "label",
        tar_group_select(
          result,
          identity(source),
          # by = 'g1' # works (because g1 is defined in both data sets)
          by = by
        )
      )
  })

  tar_manifest()
  tar_make()
})
#> ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.1 ──
#> ✔ ggplot2 3.3.6     ✔ purrr   0.3.4
#> ✔ tibble  3.1.7     ✔ dplyr   1.0.9
#> ✔ tidyr   1.2.0     ✔ stringr 1.4.0
#> ✔ readr   2.1.2     ✔ forcats 0.5.1
#> ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
#> ✖ dplyr::filter() masks stats::filter()
#> ✖ dplyr::lag()    masks stats::lag()
#> ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.1 ──
#> ✔ ggplot2 3.3.6     ✔ purrr   0.3.4
#> ✔ tibble  3.1.7     ✔ dplyr   1.0.9
#> ✔ tidyr   1.2.0     ✔ stringr 1.4.0
#> ✔ readr   2.1.2     ✔ forcats 0.5.1
#> ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
#> ✖ dplyr::filter() masks stats::filter()
#> ✖ dplyr::lag()    masks stats::lag()
#> • start target result_group1
#> ✖ error target result_group1
#> • end pipeline: 0.105 seconds
#> Error : tar_group() must take a grouped data frame from dplyr::group_by()
#> ✖ Problem with the pipeline.
#> ℹ Show errors: tar_meta(fields = error, complete_only = TRUE)
#> ℹ Learn more: https://books.ropensci.org/targets/debugging.html
#> Error:
#> ! problem with the pipeline.

Created on 2022-08-04 by the reprex package (v2.0.1)
Replacing by = by with by = g1 or by = 'g1' works just fine, so this seems to be an issue where tar_map isn't looking to my list to get a result for by.  Any solutions/work-arounds that don't involve hand-coding all my tar_group_* statements?
(I usually use tar_group_by when they are not in a static branch.  I was hoping tar_group_select would allow me to pass my group variables in the context of tar_map, but that doesn't seem to be working.)
Comment: Can you use `by = starts_with('g')`
Comment: This would work in the reprex, but in the actual data sets, I'm often grouping by multiple variables (with a variety of different names)
Answer: tar_map() works on the command and pattern settings of regular target objects, but it doesn't see the by argument of special target factories like tar_group_select(). So instead, I recommend something tar_eval(), which straightforwardly substitutes symbols in the expression you give it.
# _targets.R file
library(targets)
library(tarchetypes)
library(tidyverse)
library(rlang)

df1 <- data.frame(
  g1 = rep(LETTERS[1:3], 2),
  x = 1:6,
  y = 1:6
) |>
  group_by(g1)

df2 <- data.frame(
  g1 = rep(LETTERS[1:3], 2),
  g2 = rep(LETTERS[4:6], 2),
  x = 1:6,
  y = 1:6
) |>
  group_by(g2)

tar_eval(
  values = list(
    name = c("result1", "result2"),
    label = c("group1", "group2"),
    source = c("df1", "df2") |> syms(),
    by = c("g1", "g2")  # group by g1 for df1 and g2 for df2
  ),
  tar_group_select(
    name = name,
    command = identity(source),
    by = all_of(by)
  )
)


Windows 10 Enterprise LTSC - Installed updates differ between Windows Update and Installed Updates

Question: Windows Update - View Update History and Installed Updates show different things:

Kiosks running Windows 10 Enterprise LTSC 1809 - 17763.2061.
I'd assumed these should list the same things, but they don't. Would I be right in thinking that Installed Updates should be correct one?
What's the more appropriate way (nicely date ordered) to do this on the command line or in Powershell?
Answer: It looks like your update history is showing some failed updates, whereas your control panel on the right is showing only updates that have actually installed.
You could try get-hotfix to show any installed updates on your kiosk.


Prove that if $f : \mathbb Z_p \to G$ is a homomorphism, then $f$ is either injective or trivial(i.e. $f(x)=1$ for all x).

Question: I'm stuck on the last part that I assume there is one element other than $0$ and $1$ belongs to the kernel and I try to prove that $f(1)=1$, but I didn't see any clue to do that.
Answer: The kernel of $f$ is a subgroup of $\mathbb{Z}_p$.  By Lagrange's theorem, the order of the kernel is either 1 or $p$.  If the kernel has order 1, then $f$ is injective. If the kernel is all of $\mathbb{Z}_p$, then $f$ is trivial.
Comment: Thanks, I figure out that the p is prime and all the problems are done
Answer: Hint: Assuming $p$ is prime, $\mathbb{Z}_p$, under addition, has only two subgroups
Comment: @user179822 The statement is not true when you let $p$ be any natural number, for example, $f:\mathbb{Z}_4\to\mathbb{Z}_2$, $f(0)=f(2)=0$, $f(1)=f(3)=1$.
Comment: but p is not guaranteed to be a prime.P can be any natural number.
Comment: Use Lagrange's Theorem, let $H \leq G$, then $|H| \mid |G|$
Comment: Thanks a lot for taking this example out to make it clear, I believe this is the question's fault to not indicate that p is a prime number. Also thanks to paw88780


Aurally distinguishing between head voice and chest voice

Question: This is a query that does not involve producing a head voice or chest voice, but how to distinguish between them in what I hear. Granted there are ways or techniques in properly creating sound that are distinct to both schools of thought, but this query is not about how to produce head voice or chest voice.
For example, when I hear something I want to be able to tell whether I am hearing a head voice rendition or that of a chest voice.
Comment: @EffectorDhanushanth A large part of community upkeep is in fact based around **moderating questions**; it's hardly an absurd proposition. [Music Fans Stack Exchange](https://musicfans.stackexchange.com/), by the way, is not just a bunch of people "sucking up" to the musicians; it's an entirely different site within the Stack Exchange Network. At the moment, your question seems valid on this site. For future reference, any user may edit their own questions and answers without restriction, so if you feel something needs to be changed, including tags, you should make the change yourself.
Comment: Hi and welcome to the music stack exchange. I wonder if this question is better suited for the music fans stack exchange... And, your tag is a bit misleading - this is more ear-training than voice-training. There are many questions about singing in these different registers on here... as far as hearing the differences, you will not likely be able to, if you are listening to any singer who is worth their salt...
Comment: How may I ask can this question be solved by "fans" when all they (fans) do is suck up to the musicians? This is a technical query. One that does not involve in entertainment in the way that you think it does, but more on the technical side of things.
Comment: Yeah - I can't migrate the question because I don't have the creds yet. You yourself say the question is not how to produce a head or chest voice but, how to hear it... it's ear training, not voice training (I will change that for you assuming you can't do it yourself.) As it stands, your question is more about music appreciation than music theory. It's not likely to get a lot of foot traffic, unfortunately. Finally, you are not likely to get a better answer than "there is no way to tell"
Answer: There is no sure-fire way to tell and no substitute for experience listening. A general rule of thumb is how "breathy" the voice is. The breathier, the more likely to be a head voice. But you also have to take into account the individual singer and their range. Furthermore, there are singers who are so adept at making their head voice sound consistent with their "normal" voice that they are very very hard to distinguish.
To some extent you can train you ear to recognize it by listening to known examples from one or more given singers with whom you take the time to familiarize yourself. Example: "How Can You Mend A Broken Heart" by the Bee Gees. Compare the first line of the chorus ("How can you men a broken heart" -- head voice) to the second ("How can you stop the rain from falling down" -- normal).


Choice of prior and combination with likelihood, sample from exp distribution

Question: I am taking a course in Statistical Theory of Science. We have an exercise where we are comparing "Classical" and Bayesian parameter estimation.
We have a sample $(x_1,...,x_5) = (0.28,0.30,0.94,0.42,1.76)$ from an exponential distribution with parameter $\theta$, the pdf is given as
$$f(x|\theta) =\theta e^{-\theta x}, \quad \theta, x > 0$$
We need to estimate $\theta$ by choosing an appropriate prior, combining it with the likelihood and estimating it from the posterior distribution.
My question is about the prior, what would be appropriate? My guess is that it should be a Gamma distribution based on the fact that our parameter exists in $\mathbb{R}^+$. Is this correct?
If the above is correct, am I supposed to add a guess for the parameters in the Gamma? Or should they stay as variables?
How do I interpret "combine with the likelihood", is this the calculation of the posterior?
Comment: Any prior is "appropriate". There are no good and bad priors!
Answer: The Gamma prior is certainly a good option as it is conjugate with the exponential likelihood. This means that the posterior will also be a Gamma distribution, and the update (prior $\rightarrow$ posterior) do not rely on any simulation.
Say you have a prior $\Gamma(a,b)$ whose density is:
$$
p(\theta ; a,b) \propto \theta^{a-1}e^{-\theta b}
$$
and the exponential likelihood based on observations $(X_1,\dots,X_n)$:
\begin{align*}
p(X \mid \theta) &= \prod \theta e^{-\theta X_i} \\
&= \theta^n e^{-\theta \sum X_i}
\end{align*}
What we are interested in is the posterior distribution of $\theta$, that is the distribution of $\theta$ after observing the data.
We get this posterior from the bayes theorem:
$$
p(\theta \mid X) = \frac{p(\theta) p(X \mid \theta)}{p(X)}
$$
which is sometimes written as $p(\theta \mid X) \propto p(\theta) p(X \mid \theta)$.
 Here $p(\theta)$ is the prior distribution and $p(X \mid \theta)$ is the likelihood of the model.
Thus the posterior distribution of $\theta \mid X$ is proportional to the product of the prior and the likelihood (and I think this is what is meant by combine with the likelihood):
\begin{align*}
p(\theta \mid X) &\propto p(\theta ; a,b) p(X \mid \theta) \\
& \propto \theta^{a-1}e^{-\theta b} \theta^n e^{-\theta \sum X_i} \\
& \propto \theta^{a+n-1} e^{-\theta(b+\sum X_i)}
\end{align*}
The last line, seen as a function of $\theta$, is proportional to the density of a $\Gamma(a+n, b+ \sum X_i)$, which is the posterior distribution of $\theta$.
The posterior is completely determined an you can easily compute posterior mean/median or credible intervals without relying on any simulation.
You have to choose the parameter $(a,b)$ for the prior distribution of $\theta$. This should reflect you prior belief on the plausible values of $\theta$. This parameters $(a,b)$ are fixed, but can sometimes be considered themselves as random, but this is advanced bayesian statistics.
Comment: Thanks for this answer, very good! If I do not have any prior belief, as this is just an exercise with no context, what numbers for $a$ and $b$ would make a good choice? We are supposed to compare the result with estimation using MLE.
Comment: To repeat myself, there is no good or bad choice of $(a,b)$. Bayesian analysis is relative to the prior measure, the posterior indicates how the data modifies this prior measure. Within Bayesian analysis it thus makes no sense to compare two priors.


Does Atomic operation need synchronization in Java

Question: As far as I understand atomic operation are one that are indivisible that is one thread can see the state of a system before thread 2 changes it or after the change made by thread 2 but not in between.
say for example I have a method on a shared object betwwen 2 threads:
public void incrementMe() {
 //incrementing a shared int for this example
 atomicInt.incrementAndGet();
}

that for example that the initial value of our atomic int is 5. Now thread 1 and thread 2 are both calling incrementMe at the same time. what will happen? as far as I understand thread 1 will see the value 5 and increment it to 6 at the same time thread 2 will see the value 5 since the increment is atomic so thread 2 can see the value after change of after but no in between so it increment it to 6 and at the end I will have the value 6 instead of 7. Am I right? Do I miss somthing?
Thank u in advance
Comment: Nothing in the `java.util.concurrent` package requires synchronization; that's the entire point of the classes.
Comment: This should help too http://stackoverflow.com/questions/17691983/implementation-of-the-addandget-in-atomicinteger-class
Answer: That is incorrect.  Atomics by definition are completed in a single operation.  Behind the scenes the JVM is using the Unsafe.compareAndSwap method, which models a single processor instruction that will increase a value without the fear of pre-emption.  So, Thread 1 will increment the value to 6 and Thread 2 will increment the value to 7.
Comment: Thank for your answer. But I still not understand, after all no side effects of an atomic operation is visible until the action/operation is complete.So if 2 threads try to in increment shared value simultaneously not thread can see the effect of the other...
Comment: Not true.  I think you do not trust or understand what we are saying.  When using atomics only one thread at a time can modify the value.  Think of it like this, when a thread goes to read or write an atomic then all context switching is disabled.  That's not what really happens, but it's a decent model.
Comment: @disrvptor Can you provide any references to information regargin JVM using Unsafe.compareAndSwap? I need to understand how pre-emption will be avoided.
Comment: https://stackoverflow.com/questions/26995856/strange-behavior-in-sun-misc-unsafe-compareandswap-measurement-via-jmh is a good writeup of how to examine what's going on. Examples of the CAS function can be found at https://www.baeldung.com/java-unsafe and https://github.com/openjdk-mirror/jdk7u-jdk/blob/master/src/share/classes/java/util/concurrent/atomic/AtomicInteger.java
Answer: It is completely adjusted for precisely that use case. If two threads read one will come before the other. One will receive 6, the other 7. Neither will see the value 5.
Remeber to keep the incremented value, though.
 public void incrementMe() {
   int xx = atomicInt.incrementAndGet();
 }


Recover simulated affine transformation for matched asift features (Morel's implementation)

Question: Has anyone tried to recover the simulated affine transformation for the ASIFT feature detector? (From the author's implementation). In the original paper the simulated affine is clearly recovered by the equation 2.2 but I cannot seem to find a clear point where this is performed. Has anyone tried before? The function compensate_affine_coor1 in compute_asift_keypoints.cpp seems to be what I'm looking for but the scale seems to be normalized plus, the center of coordinates to perform the transformation is not clear to me.
Answer: It is performed in function you mentioned. Center coordinates are shifted because when you rotate image, top-left corner(origin) is moved, so they have to compensate it. And scale doesn`t change at all.


How to decode javascript file using perl script?

Question: I obfuscated javascript files using stunnix tool through buildscript which is perl script.How to decode the obfuscated file using perl??
Comment: Prevent easy decoding is what obfuscation is meant for. If a simple script was enough to unobfuscate, there would be no interest in obfuscating.
Comment: i cant help it..thats the requirement.
Answer: In general, you can't.
You could parse the JavaScript AST and then pretty-print it, which would go a long way towards improving its readability, but you cannot, for example, recover the original variable names or function names.
Comment: we can use malzilla but it takes one file at a time


Custom drag e drop Javascript não funciona no firefox

Question: estou fazendo um leitor de XML ao qual eu faça o upload de um arquivo e ele leia o conteúdo, no chrome está funcionando tudo ok, porém no firefox por algum motivo o drag e drop não está entrando em $('#xmlenvio').change(..., não estou procurando que façam pra mim, só preciso entender o que está acontecendo, pois não gera nenhum erro no console.
Firefox version: 61.0.2 (64-bit)
Chrome version: 69.0.3497.92 (64-bit)

function dropHandler(ev) {
    ev.preventDefault();
    var file;

    if (ev.dataTransfer.items) {
        for (var i = 0; i < ev.dataTransfer.items.length; i++) {
            if (ev.dataTransfer.items[i].kind === 'file') {
                document.querySelector('#xmlEnvio').files = ev.dataTransfer.files;
            }
        }
    }
    removeDragData(ev)
}

function dragOverHandler(ev) {
    ev.preventDefault();
}

function removeDragData(ev) {
    if (ev.dataTransfer.items) {
        ev.dataTransfer.items.clear();
    } else {
        ev.dataTransfer.clearData();
    }
}

$('#xmlEnvio').change(function(e){
    alert('chrome works');
    var input = this;
    file = input.files[0];
    $('.form-control.image-preview-filename').val(file.name);

    var reader = new FileReader();
    reader.onload = function() {
        var parsed = new DOMParser().parseFromString(this.result, "text/xml");

        console.log(parsed);
    }
    reader.readAsText(file);
    console.log('... file[' + 0 + '].name = ' + file.name);
});
.upload-drop-zone {
    height: 200px;
    border-width: 2px;
    margin-bottom: 20px;
}

.upload-drop-zone {
    color: #ccc;
    border-style: dashed;
    border-color: #ccc;
    line-height: 200px;
    text-align: center
}

.upload-drop-zone.drop {
    color: #222;
    border-color: #222;
}

.image-preview-input {
    position: relative;
    overflow: hidden;
    margin: 0px;
    color: #333;
    background-color: #fff;
    border-color: #ccc;
}

        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

                    <form id="upload" action="#" method="POST" enctype="multipart/form-data" accept-charset="UTF-8">

                            Select XML archive

                                <input placeholder="" type="text" class="form-control image-preview-filename" disabled>

                                        Search
                                        <input id="xmlEnvio" type="file" accept=".xml" name="xml"/>

                                    <button type="submit" class="btn btn-labeled btn-primary">

                                        Upload
                                    </button>

                                Or drag XML to this area.

                    </form>

Answer: No Firefox, nesse trecho, quando você seta os arquivos no input, o evento não é disparado, já no chrome ele é disparado automaticamente.
document.querySelector('#xmlEnvio').files = ev.dataTransfer.files;

Para disparar manualmente, você pode usar o seguinte código
document.querySelector('#xmlEnvio').dispatchEvent(new Event('change'));

O problema é que ele disparará duas vezes no Chrome.
Mas lembre-se de que você NÃO precisa usar o input para dar parse nos XMLs. Você pode dar parse diretamente no dropHandler
function dropHandler(ev) {
    ev.preventDefault();

    const file = ev.dataTransfer.files[0];
    if ( ! file) return;

    const reader = new FileReader();
    reader.onload = function() {
        var parsed = new DOMParser().parseFromString(this.result, "text/xml");

        console.log('RESULT', parsed);
    }
    reader.readAsText(file);

    removeDragData(ev);
}

Edição: Desse jeito você consegue aproveitar o código e funcionar cross-browser :)
function parseXML(file) {
    const reader = new FileReader();
    reader.onload = function() {
        const parsed = new DOMParser().parseFromString(this.result, "text/xml");

        console.log('RESULT', parsed);
    }
    reader.readAsText(file);
}

function dropHandler(ev) {
    ev.preventDefault();
    const file = ev.dataTransfer.files[0];
    parseXML(file);
    removeDragData(ev)
}

function dragOverHandler(ev) {
    ev.preventDefault();
}

function removeDragData(ev) {
    if (ev.dataTransfer.items) {
        ev.dataTransfer.items.clear();
    } else {
        ev.dataTransfer.clearData();
    }
}

$('#xmlEnvio').change(function(e){
    var input = this;
    const file = input.files[0];
    if ( ! file) return;

    parseXML(file);
});

Comment: Eu preciso é que ele fique no onchange por questão de reaproveitamento, pois vou utilizar a função tanto para a questão do drag e drop quanto para quando o cliente seleciona o arquivo
Comment: Quanto ao disparar 2x no chrome eu já havia encontrado uma "solução" desta forma, porém ela não é satisfatória.
Comment: Fácil, crie uma função que se chama "parse" com a leitura do FileReader, e chame-a tanto no dropHandler quanto no onChange do input
Answer: O Firefox só dispara o evento change se o usuário alterar diretamente o campo file, ao contrário do Chrome.
O que você pode fazer é disparar o evento manualmente na função removeDragData(), mas isso irá disparar o evento change 2 vezes no Chrome. Para evitar que o evento seja disparado 2 vezes no Chrome, você pode usar uma variável de controle. Se a variável for true, a função do evento é ignorada com um return, se for false executa a função e altera o valor para true e um setTimeout() de 1 segundo altera novamente para false. Desta forma, quando o evento for disparado pela segunda vez irá entrar no return e sair da função.
Adicione um trigger no fim da função removeDragData(ev):
function removeDragData(ev) {
    if (ev.dataTransfer.items) {
        ev.dataTransfer.items.clear();
    } else {
        ev.dataTransfer.clearData();
    }

    $('#xmlEnvio').trigger('change');
}

Crie uma variável (global) de controle:
var mudou;

E no início da função do evento change insira 3 linhas que tratam da variável:
if(mudou) return;
mudou = true;
setTimeout(function(){ mudou = false }, 1000);

No final, o código ficará desta forma:
function dropHandler(ev) {
   ev.preventDefault();
   var file;

   if (ev.dataTransfer.items) {
      for (var i = 0; i < ev.dataTransfer.items.length; i++) {
         if (ev.dataTransfer.items[i].kind === 'file') {
            document.querySelector('#xmlEnvio').files = ev.dataTransfer.files;
         }
      }
   }
   removeDragData(ev)
}

function dragOverHandler(ev) {
    ev.preventDefault();
}

function removeDragData(ev) {
    if (ev.dataTransfer.items) {
        ev.dataTransfer.items.clear();
    } else {
        ev.dataTransfer.clearData();
    }

    $('#xmlEnvio').trigger('change');
}

var mudou;

$('#xmlEnvio').change(function(e){

   if(mudou) return;
   mudou = true;
   setTimeout(function(){ mudou = false }, 1000);

    alert('chrome works');
    var input = this;
    file = input.files[0];
    $('.form-control.image-preview-filename').val(file.name);

    var reader = new FileReader();
    reader.onload = function() {
        var parsed = new DOMParser().parseFromString(this.result, "text/xml");

        console.log(parsed);
    }
    reader.readAsText(file);
    console.log('... file[' + 0 + '].name = ' + file.name);
});


How to Pitch Camera Around Origin

Question: I am trying to implement a camera which orbits around the origin, where I have successfully implemented the ability to yaw using the gluLookat function. I am trying to implement pitch, but have a few issues with the outcome (pitch only works if I yaw to a certain point and then pitch).
Here is my attempt so far:
float distance, // radius (from origin) updated by -, + keys
      pitch,    // angle in degrees updated from W, S keys (increments of +- 10)
      yaw;      // angle in degrees updated from A, D keys (increments of +- 10)

view = lookAt(
        Eigen::Vector3f(distance * sin(toRadians(pitch)) * cos(toRadians(yaw)), distance * sin(toRadians(pitch)) * sin(toRadians(yaw)), distance * cos(toRadians(pitch))),
        Eigen::Vector3f(0.0f, 0.0f, 0.0f),
        Eigen::Vector3f(0.0f, 0.0f, 1.0f));

proj = perspective(toRadians(90.0f), static_cast<float>(width) / height, 1.0f, 10.0f);

I feel like my issue is the Up vector, but I'm not sure how to update it properly(and at the same time I think its fine, as I always want the orientation of the camera to stay the same, I really just want to move the position of the camera)
Edit: I wanted to add that I'm calculating the position based info found here: http://tutorial.math.lamar.edu/Classes/CalcIII/SphericalCoords.aspx I'm not sure if the math discussed here directly translates over so please correct me if wrong.
Answer: It might be a matter of interpretation. Your code looks correct but pitch might not have the meaning that you think.
When pitch is 0, the camera is located at the north pole of the sphere (0, 0, 1). This is a bit problematic since your up-vector and view direction become parallel and you will not get a valid transform. Then, when pitch increases, the camera moves south until it reaches the south pole when pitch=PI. Your code should work for any point that is not at the poles. You might want to swap sin(pitch) and cos(pitch) to start at the equator when pitch=0 (and support positive and negative pitch).
Actually, I prefer to model this kind of camera more directly as a combination of matrices:
view = Tr(0, 0, -distance) * RotX(-pitch) * RotY(-yaw)

Tr is a translation matrix, RotX is a rotation about the x-axis, and RotY is a rotation about the y-axis. This assumes that the y-axis is up. If you want another axis to be up, you can just add an according rotation matrix. E.g., if you want the z-axis to be up, then
view = Tr(0, 0, -distance) * RotX(-pitch) * RotY(-yaw) * RotX(-Pi/2)

Comment: thank you so much. Idk why, but i was so hung up on using gluLookAt that i didnt even bother to think about just doing some simple matrix combos.

How to Pitch Camera Around Origin


Directional derivatives and limit rules

Question: I am having some problems understanding directional derivatives and limit rules. I was hoping someone might be able to help.
Basically, the result is the $f'(x, -a)$ = $-f'(x,a)$. To show this (after some manipulations, we have:
(1) $f'(x, -a) = \lim\limits_{(-h) \to 0} \frac{f(x+(-h)a) - f(x)}{(-h)} = -f'(x,a)$ (2)
I had two questions:

Firstly, can I intepret the result as (1) the instantenous rate of change in the direction opposite to $a$ is equal to (2) the instantaneous rate of change in the opposite direction to $a$?
I don't understand the second equality. When I write out $-f(x,a)$ according to the definition, I have:

$-f'(x, a) = \lim\limits_{h \to 0} \frac{-f(x+ ha) + f(x)}{h}$
It's not obvious to me why the two are equal. Is it because $\lim\limits_{h \to 0}$ is equivalent to $\lim\limits_{(-h) \to 0}$?
Thank you.
Answer: The equality that you wish to prove means that the instantaneous rate of change in the opposite direction of $a$ is the symetric of the instantaneous rate of change in the direction of $a$. And the answer to your final question is affirmative.
Comment: Thank you José Carlos. Just so I am clear, is it correct to say, in general, that $\lim\limits_{(-h) \to 0} \frac{f(x+(-h)a) - f(x)}{(-h)}$ = $\lim\limits_{(h) \to 0} \frac{f(x+ha) - f(x)}{(h)}$?
Comment: Yes, that is correct.

Directional derivatives and limit rules


How to password protect terms in Taxonomy

Question: I have a taxonomy vocab "region"
in the region, I have a bunch of provinces as the terms, and subpages for each province.
I would like to add a password protect or only allow authorized users to access the provinces.
etc, only username "ontario" "password" can access the term "ontario" in the taxonomy. Is this possible?
Answer: These modules may help, for D7 & D8 on DEV version is Taxonomy Access Control Lite, on approved versions (recommended): D7 is Taxonomy Access Control and for D8 is Permissions by Term, review wich one fit best your needs.


Ter duas versões do Python no OSX, sem sobrescrever

Question: Há alguma maneira de instalar a versāo 3.x do Python sem sobrescrever a versão pré-instalada (essencial) do OSX?
Eu já conheço o virtualenv mas gostaria de evitá-lo, até porque eu só uso Python para estudar.
Há alguma maneira de manter as duas versões paralelas e "vivendo em harmonia"?
Eu imagino que teria como fazer algo assim:
Iniciar Python 2

MBP:~ jbueno$ python

Iniciar Python 3

MBP:~ jbueno$ python3

Answer: Basta instalar Homebrew pelo terminal (precisa do Xcode instalado):
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Depois basta instalar o Python 3 através do comando brew:
brew install python3

Para executar algo usando Python 3 basta usar o comando python3 em vez de apenas python.
python3 --version

Comment: No link http://brew.sh você pode ter mais detalhes, é apenas um instalador de pacotes.


Como gerar diversos ZIPs dinamicamente em memória, com Python?

Question: Estou lendo um dataframe em Python, e pra cada linha do mesmo, preciso salvar a coluna que contém um XML em um arquivo, em memória, para posteriormente zipar estes arquivos. Até aí tudo bem. A questão é que eu preciso gerar estes ZIPs dinamicamente, de acordo com uma determinada chave presente dentro dos arquivos. Se a chave for igual à anterior, deve gravar o XML no mesmo diretório. Caso contrário, deverá gerar um zip diferente para essa nova chave. Todos os arquivos com a mesma chave devem ficar juntos. Ou seja, caso existam 20 chaves diferentes, preciso gerar 20 ZIPs diferentes.
Abaixo, segue o código até o momento:
<code>.
.
.
arrayKeys = []
memoryZip = BytesIO()
memoryXml = StringIO()
today = datetime.today()
todaysYear = str(today.year)
todaysMonth = str(today.month)
todaysDay = str(today.day)
todaysHour = str(today.hour)
todaysMinute = str(today.minute)
todaysSecond = str(today.second)

for line in range(len(dataFrame)):
.
.
.
    # Busca a chave:
    key = str(dataFrame['KEY'][line])
    directory = 'key='+key

    # Se a nova chave já existir na lista, deve gravar os dados no mesmo zip:
    if key in arrayKeys:
        with zipfile.ZipFile(memoryZip, 'w', compression=zipfile.ZIP_DEFLATED, compresslevel=9) as zf:

            # Cria a estrutura de pastas:
            path = 'folder1\\folder2\\'+directory+'\\xml'+line+'.xml'

            # Salva os arquivos na estrutura necessária
            dataFrame.iloc[line,:].to_csv(memoryXml, header=False, index=False, escapechar='\\', quoting=csv.QUOTE_NONE)
            zf.writestr(path, memoryXml.getvalue())

            # Nome do zip:
            zipName = key+'_'+todaysYear+todaysMonth+todaysDay+todaysHour+todaysMinute+todaysSecond

    # Se não, deve gravar em outro zip
    else:
        arrayKey.append(directory)

        # Gerar outro zip dinamicamente, para cada chave
        with zipfile.ZipFile(memoryZip, 'w', compression=zipfile.ZIP_DEFLATED, compresslevel=9) as newZf:

            # Cria a estrutura de pastas em memória:
            path = 'diretorio\\'+key+'\\xml'+line+'.xml'

            # Salva os arquivos na estrutura necessária
            dataFrame.iloc[line,:].to_csv(memoryXml, header=False, index=False, escapechar='\\', quoting=csv.QUOTE_NONE)
            newZf.writestr(path, memoryXml.getvalue())

            # Nome do zip:
            zipName = key+'_'+todaysYear+todaysMonth+todaysDay+todaysHour+todaysMinute+todaysSecond

# Função que faz o upload dos zips (a implementação dela é irrelevante, nesse caso)
# Aqui, preciso que sejam enviados todos os zips em memória
upload('storage', memoryZip.getvalue(), f'{zipName}.zip')
</code>
Comment: O problema está descrito inclusive no título da pergunta.
Comment: Qual é a mensagem de erro gerada?
Comment: Timeout. Não sei se é pelo fato dele percorrer todas as tags de todos os XMLs.
Comment: Não seria mais interessante criar um RAM Disk, salvar esses zips dentro desse RAM Disk e passar para a função a referência desse RAM Disk com os arquivos ZIP salvos?
Answer: Problema solucionado: basicamente, foi necessário abrir apenas um ZipFile (ao invés de 2, como mostrado acima) em memória, e ir salvando os arquivos de acordo com a chave. Após o laço, o ponteiro de memória da variável memoryXml foi setado pra 0 (memory.seek(0)) e depois truncado (memoryXml.truncate(0)).


Aceder a servidor através do linux

Question: Eu gostaria de com a minha aplicação em Java (netbeans) aceder à base de dados que está no servidor, mas isto ficou complicado, por ser através de uma maquina com Linux.
Alguém poderia me explicar como fazer isto?
A classe de conexão que eu uso é:
public Connection LigaBD() {
    try{
        System.out.println("Entrei !!!");
        Class.forName("org.sqlite.JDBC");
        conn = DriverManager.getConnection("jdbc:sqlite:pesquisa.db");
        System.out.println("Passei a segunda fase !!!");
    }
    catch(Exception e){
        e.printStackTrace();
    }
    System.out.println("Nao consegui entrar na BD");
    return null;
}

Acedendo localmente eu consigo, o pior é mapear em Linux, sou novo em Linux.
Comment: Tu já tentou conectar via pgAdmin?
Answer: Você se conecta a sua base de dados usando uma das seguintes formas:

jdbc:sqlite:meu_banco.db
jdbc:sqlite://dirA/dirB/meu_banco.db
jdbc:sqlite:/DRIVE:/dirA/dirB/meu_banco.db
jdbc:sqlite:///COMPUTADOR/shareA/dirB/meu_banco.db

No caso, a solução para seu problema seria usando a última forma:
conn = DriverManager.getConnection("jdbc:sqlite:jdbc:sqlite:///NOME_SERVIDOR/caminho_do_arquivo/pesquisa.db");

Voê tem que criar um compartilhamento de arquivo no servidor, o que não é recomendável, já que pode abrir uma brecha na segurança do seu sistema.
O SQLite não é recomendado para aplicações cliente/servidor. Para isto, utilize outro SGBD. Use MySQL ou PostgreSQL (eu prefiro o PostgreSQL).
Comment: Duplicou `jdbc:sqlite:jdbc:sqlite:///...`

Aceder a servidor através do linux


Como duplicar um triangulo randomicamente dentro do canvas?

Question: Estou tentando duplicar um triangulo aleatoriamente dentro do canvas quando pressiona alguma tecla, tipo, barra de espaço ou outra qualquer. Mas não sei como fazer para duplicar, se tenho que usar algum tipo de constructor/array.
Ate o momento so tenho o canvas e o triangulo:
HTML
<!DOCTYPE html>

   <meta charset="utf-8">
   <title>Canvas</title>

Triangle

    <canvas id="myCanvas" height="500" width="500" style="border: 1px solid black"></canvas>

    <button type="button" id="resetbtt" name="button">Reset</button>

JS:
let canvas;
let ctx;
let dx = 10;
let dy = 10;
let x = 250;
let y = 250;
let WIDTH, HEIGHT = 500;

function setUp(){
   canvas = document.getElementById("myCanvas");
   ctx = canvas.getContext("2d");
   let resetbtt = document.getElementById('resetbtt');
   drawTriangle();
}

function drawTriangle(){

    ctx.save();
    ctx.translate(x,y)
    ctx.beginPath();
    ctx.moveTo(0, 0);
    ctx.lineTo(-15, 15);
    ctx.lineTo(15, 15);
    ctx.closePath();
    ctx.stroke();
    ctx.restore();

Answer: let canvas;
let ctx;
let dx = 10;
let dy = 10;
let WIDTH, HEIGHT = 500;

function setUp(){
   canvas = document.getElementById("myCanvas");
   ctx = canvas.getContext("2d");
   let resetbtt = document.getElementById('resetbtt');

   document.body.onkeydown = function(e){
        if(e.keyCode == 32){
            var x = randomInt(0,500);
            var y = randomInt(0,500);
            drawTriangle(x, y);
        }
    }
}

function drawTriangle(x, y) {

    ctx.save();
    ctx.translate(x, y)
    ctx.beginPath();
    ctx.moveTo(0, 0);
    ctx.lineTo(-15, 15);
    ctx.lineTo(15, 15);
    ctx.closePath();
    ctx.stroke();
    ctx.restore();

}

function randomInt(min, max) {
    return Math.floor(min + (Math.random() * ((max + 1) - min)));
}

Comment: Tomás, não está funcionando. O triângulo não está reaparecendo randomicamente qdo aperta a barra de espaço
Comment: a barra de espaço às vezes cria conflitos


How to change column length of existing table in SQL?

Question: I have one SQL table which will contain (TEXT/VARCHAR) columns of some length.
How can I change the existing column length without dropping or hardcode existing database table.
2020_02_13_065846_create_users_documents_table.php
public function up()
    {
        Schema::create('user_documents', function (Blueprint $table) {

            $table->increments('id');
            $table->string('upload_url', 200)->nullable();
            $table->string('user_name', 50)->nullable();
        });

Now I want to change the length of column user_name to 200 by creating a new table.
Comment: You etheir correct it in that file and refresh the migration (deletes everything) or you make a new migration and add the alteration statement in it (production solution).
Comment: i never used that solution @MohamedGamalEldin because it needs the package `doctrine/dbal` when you can do it with a statement.
Comment: "_by creating new table_"? Why a new table?
Comment: You can change columns with [`change()`](https://laravel.com/docs/8.x/migrations#modifying-columns) method.
Comment: I know that if small changes can use a statement but for big projects, I think `doctrine/dbal` is better. @N69S
Answer:
Development solution

you correct it in that file and refresh your migration with php artisan migrate:fresh but you lose all the data in your database

Production solution

Make a new migration with the alter statement.
public function up()
{
    \DB::statement('ALTER TABLE user_documents ALTER COLUMN upload_url VARCHAR (200)');
}

Answer: you just have to modify you columns:
The change method allows you to modify the type and attributes of existing columns. For example, you may wish to increase the size of a string column
make a new Migration, set this statement:
Schema::table('users', function ($table) {
    $table->string('upload_url', 500)->change();
 $table->string('user_name', 500)->change();
});


Why phonegap application always shows own default page after override index.html

Question: Hi I have made a hello world type of application in PhoneGap. I have index.html in www directory but it is displaying something default home page of phonegap. Please see attached screenshot that it is displaying always.
index.html

        <meta charset="utf-8" />
        <meta name="format-detection" content="telephone=no" />
        <meta name="msapplication-tap-highlight" content="no" />

        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
        <link rel="stylesheet" type="text/css" href="css/index.css" />
        <title>Hello World</title>

        <form>
            Select your favourite color: <input type="color" name="favcolor">

            <input type="button" value="SUBMIT" />
        </form>

But when I run the app in android phone it always display this. I have done 3-4 rebuild complete project but still same.
I am not sure what is going wrong or missing.
Thanks in advance.
Comment: Try to manually change the www folder contents before building in the platforms you have added and then take the build and see if it works.
Comment: @ashfaq.p Yes I changed & uploaded code as well in the question.
Answer: I think you are making changes to www folder present inside the platforms added.
Try to make changes in the www folder which is present in the root folder of your project and then take a build and it will definitely work.
Check This:
Comment: But your code is working fine for me in the emmulator as well as my android device. can you upload your complete demo folder to dropbox.
Comment: No do not change anything inside platform. It automatically gets updated when you take a build with all the changes you have made in the root www folder.
Comment: See this https://www.dropbox.com/s/f00yh7up7uygbpb/8.png?dl=0 I edited in this index.html
Comment: I see there is platform folder also there then android then platform_www .. do i have to add there ?


Anyone can tell their experience with 10g Ethernet adapters on Linux

Question: I wonder if any of you have an experience with 10g NICs (Intel, Myricom, SMC tiget, napatech, or by any other brand).
Questions are:

Was it easy to install, or a hassle,
How does this adapter appear on the interface list (ifconfig), as a single one or as two -
given the fact, both forms (sfp+ and rj45) formed in two seperate ports (RX and TX).
And most of all, have you used libpcap based application (e.g. tcpdump) to capture the traffic, were there any issues at that part, or all went smooth?

These are the concerns that popped up in my mind but feel free to share and add any piece of information which you think might be relevant to me nevertheless important.
Thanks in advance!
Comment: You imply that your particular NIC has one interface but two ports - is it a dual-personality card that can use either SFP+ or RJ45? If so, it will show up as a single interface. Or does it really separate RX and TX functions into two different ports? That's kinda strange - can you share the card model?
Comment: Sorry for misleading you, I have no card yet! All Iwas saying that I have seen on the web two types of NICs rh45 and sfp+ - both have two ports and apparently appear as eth0 and eth1 - thus as two seperate adapters.
Answer: Yep, all of our OEL/RHEL 5.3/5.4 boxes (generally HP BL460c G6's) simply have dual 10Gbps LOM NICs by Broadcom. Ours work just fine with the standard drivers from the HP PSP driver pack, show up as eth0 and eth1 - no confusion with interface type - and we have indeed used tcpdump - all went smoothly.
Comment: well, you are shading light on my darkness dude. may I ask then, have you ever happened to debug the traffic with tcpdump? if so, how did you managed to sync both channels? since it was stored in tow separate files
Comment: The HP adapters don't have two channels, they're SFP+ only, that's why it's easier.
Comment: Chopper, what do you mean "no two channels"? They still appear as eth0 and eth1 right? that brings my next questions which is after capturing both interfaces, how can I replay (retransmit) those two files (rx.cap and tx.cap) in a synchronous way so to emulate the original sessions?
Comment: Yes, my dual-port cards appear as two channels but I don't get two channels for each port (i.e. only one capture per physical port, I have no splitting).
Answer: bcom, mellanox aned chelsea all work like normal NICs, no rx/tx splitting in the dump. iirc, Intels do the same.
The only difference is when you check the kernel messages, you'll see a higher negotiated speed, that's all


Repetições e combinações de valores

Question: Tenho uma tabela (quina) com 5 campos, cada campo pode ter o valor de 1 a 80.
Gostaria de saber se é possível em SQL ou apenas no Delphi, pegar os duques (combinações de 2 números) entre 1 e 80 nos campos de c1 ate c5. não importando onde se encontram os valores na linha.
Exemplo: combinação de 01 e 02: 20 vezes.
(Mas o 01 pode estar no c1, c2 ou c3, e o 02 pode estar no c4 ou c5. O mesmo número não pode se repetir na mesma linha).
Answer: --alinhando
select c1 c from tabela
union all
select c2 c from tabela
union all
select c3 c from tabela
union all
select c4 c from tabela
union all
select c5 c from tabela

--lendo como uma tabela
select virtual1.*
from
(
select c1 c from tabela
union all
select c2 c from tabela
union all
select c3 c from tabela
union all
select c4 c from tabela
union all
select c5 c from tabela
) virtual1

--forcando um cartesiano
select virtual1.*,virtual2.*
from
(
select c1 c from tabela
union all
select c2 c from tabela
union all
select c3 c from tabela
union all
select c4 c from tabela
union all
select c5 c from tabela
) virtual1,
(
select c1 c from tabela
union all
select c2 c from tabela
union all
select c3 c from tabela
union all
select c4 c from tabela
union all
select c5 c from tabela
) virtual2
where virtual1.c <. virtual2.c

A ideia básica é fazer um "unpivot" da tabela e depois forçar um cartesiano.
Comment: nossa, eu vou tentar, e mando uma resposta
Comment: o v1 e v2 seriam os valores correto? entao eu colocaria 1.*, 2.*? porque ele está dando erro de sintax no from do primeiro select select v1.*, v2.*
Comment: É o "alias" da tabela virtual , montei com um nome e chamei por outro , corrigido ...
Comment: infelizmente nao deu certo. eu fiz em delphi, mas ele demora uns 30min para finalizar as leituras.. porque ele combina os valores X e Y em todos os campos e em toda as linhas e ainda faz a soma dos mesmo.
Comment: O que deu errado ?

Repetições e combinações de valores


R setting xlim in xts plot

Question: I am trying to expand the X-axis of my time series plot to be prepared for adding new data into the plot later on. However, whatever I try I get the Error in plot.window(...) : invalid 'xlim' value error.
Here is a minimal code snippet:
Data construction:
time_series <- xts(rnorm(100),seq(as.POSIXct("2012-01-01 00:00:00"), as.POSIXct("2012-01-05 03:00:00"), by="hour"))

Plotting:
plot(time_series, type='l');

The result is, as expected, a nice time series plot.
Now, I wanted to expand the x-axis and I tried:
xlim <- seq(as.POSIXct("2012-01-01 00:00:00"), as.POSIXct("2012-01-06 03:00:00"), by="hour")
plot <- (time_series, xlim = xlim, type='l')

but this is not working but results in Error in plot.window(...) : invalid 'xlim' value.
Trying the following results in the same error:
xlim <- c(as.POSIXct("2012-01-01 00:00:00"), as.POSIXct("2012-01-05 00:00:00"))

From the documentation I know that xlim has to be numeric and can be set like xlim = c(0,100) but how does it work when using xts data?
Edit: I know that this question is similar to the question Time series plot range. However, as I don't know the data that needs to be plotted in the future I am interested in this particular solution.
Comment: I'm not familiar with `plot.xts`, but `xlim` in base graphics is normally a vector with exactly two values (min and max) and not a sequence.
Comment: I should have mentioned that I also tried a vector including mix max POSIXct values. Sorry, I will add this to my question.
Comment: In general, I suggest using `plot.zoo` or `xtsExtra::plot.xts`
Answer: Like this:
plot(time_series, type='l',
     xlim=as.POSIXct(c("2012-01-01 00:00:00","2012-01-06 03:00:00")))

Comment: Okay, it definitely works. I am not sure why I was convinced it won't - sorry. Unfortunately, axis label seems to be missing in the plot but that's something I can live with.
Answer: Or you make a subset in xts before: df2.xts<-df.xts["2012-01-01/2012-02-01"] and Then plot(df2.xts).

R setting xlim in xts plot


Why is the exp map in the case of the Heisenberg group just the identity map?

Question: I would like to know why, in the case of  the 3-dimensional Heisenberg group $H^3$, We can identify $H^3$ with its Lie algebra $h_3$ through the exponential function $$\exp= id : h_3 \to H^3 .$$
i.e.; why $\exp= id$ ?
Answer: I would say that $\exp$ is not id. However, the exp map is a bijection.
The Lie algebra $\frak h_3$ consists of matrices
$$\pmatrix{0&a&b\\0&0&c\\0&0&0}$$
and the group $H_3$ consists of matrices
$$\pmatrix{1&r&s\\0&1&t\\0&0&1}.$$
The exponential map takes
$$\pmatrix{0&a&b\\0&0&c\\0&0&0}\mapsto\pmatrix{1&a&b+ac/2\\0&1&c\\0&0&1}.$$
From this we see that $\exp$ is a bijection, but an identity map? Not likely!
Answer: It depends on which coordinates you use! As Angina Seng says above, if you think of the Heisenberg group and its Lie algebra as subsets of $M_3(\mathbb{R})$, then the map will not be the identity. (In fact you can see this just by noting that the subsets are disjoint, by looking at the diagonal of the matrix).
However, since exp is a diffeomorphism, you can define a group law on $\mathbb{R}^3$ and a Lie algebra structure on $\mathbb{R}^3$ such that the resulting group is isomorphic to $H^3$, the resulting Lie algebra is isomorphic to $h_3$, and the exponential map between the two is the identity.
This is called "using exponential coordinates", and it can be done whenever exp is a diffeomorphism (for instance, whenever the group is simply connected and nilpotent).
Explicitly, set $X = (1,0,0), Y = (0,1,0), Z=(0,0,1) \in \mathbb{R}^3$,
and define the Lie structure by $[X,Y]=Z, [X,Z]=[Y,Z]=0$.
By linearity, this means the Lie structure in these coordinates is
$$ [(a,b,c),(a',b',c')] = (0,0, ab' - ba'). $$
(So the Lie algebra is isomorphic to $h_3$).
Now, we use the Campbell-Baker-Hausdorff formula, which relates the Lie group law to its Lie algebra; since all nested commutators of depth three or more vanish (e.g. $[[X,Y],Y] = 0$), we get a group law
$$ A*B = A + B + \frac{1}{2}[A,B] $$
which translates in our coordinates to
$$ (a,b,c)*(a',b',c') = (a+a',b+b',c+c'+\frac{1}{2}(ab'-ba')).$$
Note that this is a different group law than what you get if you identify $H^3$ with $\mathbb{R}^3$ by just taking the upper triangular entries of the matrix. So the exponential coordinates are not necessarily the first coordinates you would have thought to choose. But again, the point is that under these definitions of $H^3$ and $h_3$, exp is the identity map.
Of course, this is an instance of a much more general principle, that is, whenever you have a bijection between two objects, you can think of them as having the same underlying set and go from there. So you can turn any bijection into the identity map by redefining things a little, and it's usually not deeper than that.


Rate of change in length of hypotenuse

Question: I am absolutely stumped here. I got this problem on my Calc 1 exam and have no clue how to solve it.
We are given a triangle like this:
https://i.stack.imgur.com/h2jn5.jpg (Sorry I can't post images)
Then we are told that when θ = π/6, x = 20
So, I have sin θ = 10/x = 1/2
We are asked to find the change in x when θ changes by -0.05 radians. We are not allowed to use a calculator.
Any help with this would be hugely appreciated.
Comment: Check your question. Are you sure it's a *rate* of change you're asked to find for $x$ rather than simply a change for $x$? Or did they give the *rate* of change of $\theta$ in terms of radians per second?
Comment: So you have as a starting point that $\sin \theta = \frac{10}{x}$, or, rearranging it, $x \sin \theta = 10$. You can take an implicit differentiation of both sides with respect to $t$ to get a term for $\frac{dx}{dt}$ and a term for $\frac{d\theta}{dt}$, and then take the ratio to find $\frac{dx}{d\theta}$.
Comment: @Deepak yeah I think you're right, I believe they just want the change in x
Answer: Check your question. Are you sure it's a rate of change you're asked to find for $x$ rather than simply a change for $x$?
Assuming what they're asking for is the estimate of a small change of $x$ for a small change of $\theta$ of $-0.05$ radian, you would work it out like so:
The initial conditions help you verify that the triangle is right (you can't assume from a drawing).
$x = \frac{10}{\sin\theta}$
$\frac{dx}{d\theta} = - \frac{10\cos\theta}{\sin^2\theta}$
For the approximation of small changes, you can rearrange to:
$\delta x \approx - \frac{10\cos\theta}{\sin^2\theta} \delta \theta$
and if you're given $\delta\theta = -0.05$ radian, you get:
$\delta x \approx - \frac{10\frac{\sqrt 3}{2}}{(\frac 12)^2} \delta \theta = - \frac{10\frac{\sqrt 3}{2}}{(\frac 12)^2} (-0.05) = \sqrt 3$
The answer would be the same numerically if you had been given the rate of change of $\theta$ in terms of radian per time, e.g. $\frac{d\theta}{dt} = -0.05 rad/sec$ but there, the chain rule based equation you'd be using would be $\frac{dx}{dt} = \frac{dx}{d\theta} \cdot \frac{d\theta}{dt}$ which would give the same numerical value (except the units would be in terms of length over time and this would be exact, not an approximation).
Comment: Beautifully solved. Thanks so much for the help!
Comment: @Someguy most welcome

Rate of change in length of hypotenuse


Can I build an Azure Only infrastructure for my small business?

Question: I have small business, 63 people now, but we are growing slowly. We have no Active Directory, we use Office 365 for email, and about 25% use Macs. We are kind of spread out, 3 offices with more than 5 people, and several folks work from home 100%
I'd like to have:

Active directory (management, security, etc)
Network drive for shared storage
Integration/Federation with Office 365
No local servers

I'm thinking of building several IaaS VMs in Azure:

Domain controller to federate with Azure AD (or do I need separate ADFS or DirSync)
Direct Access server and deploy the client to all my workstations (works with Macs?)
File Server with 500GB shared drive
Anything else I'd need?
Comment: You might be able to make this work, but if you're asking I'd assume you think this is all somewhat easy to setup but have never done any of it before... This looks like a good job for a consultant.
Answer: I don't think there's any official deployment guides for AD on Azure - and yes, you would still need to deploy ADFS or DirSync, because your AD (even in a cloud) wouldn't magically trust Office 365's infrastructure.
Direct Access only works on Windows 7 or 8, Enterprise Edition or Ultimate (for 7.) No Mac client. Domain join via DA can be tricky although I understand it works better with Win2012 R2 now.
For shared storage, why don't you just use SkyDrive and/or SharePoint in Office 365? That's what it's there for.
Instead of AD, which really doesn't do this well yet, perhaps you can look into things like InTune or some other MDM (mobile device management) tool?
Comment: Thanks! Intune does look very promising for device management. I was hoping to not have to go Sharepoint just yet, that would be cross platform supported though. Thank you for the feedback!


how to change the format of the columns of csv exported- laravel excel

Question: I exported a csv file with laravel-excel 3.1 and when reviewing the values are enclosed in quotes, so they are exported as strings, but I need it to be in type number
Exported csv file:
"ano_plantacion","zona","sitio","manejo","sup_ha","codigo","rpend"
"2018","87","3","10","30.69","2042201801",""
"2017","87","3","10","14.86","2042201701",""

What I want or should be:
ano_plantacion,zona,sitio,manejo,sup_ha,codigo,rpend
2018,87,3,10,30.69,2042201801,
2017,87,3,10,14.86,2042201701,

Class SuperImport:
<?php

namespace App\Exports;

use App\Super;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use Maatwebsite\Excel\Concerns\WithColumnFormatting;

class SuperExport implements FromCollection,WithHeadings, WithColumnFormatting
{
    use Exportable;

    protected $superficie;

    public function __construct($superficie = null)
    {
        $this->superficie = $superficie;
    }
    public function headings(): array
    {
        return [
            'ano_plantacion',
            'zona',
            'sitio',
            'manejo',
            'sup_ha',
            'codigo',
            'rpend',

        ];
    }

    public function columnFormats(): array
    {
        return [
            'A' => NumberFormat::FORMAT_GENERAL,
            'B' => NumberFormat::FORMAT_GENERAL,
            'C' => NumberFormat::FORMAT_GENERAL,
            'D' => NumberFormat::FORMAT_GENERAL,
            'E' => NumberFormat::FORMAT_GENERAL,
            'F' => NumberFormat::FORMAT_GENERAL,
            'G' => NumberFormat::FORMAT_GENERAL,
        ];
    }

    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        return $this->superficie ?: Super::all();
    }
}

Controller:
$super = Super::select('ano_plantacion','zona','sitio', 'manejo','sup_ha','codigo','rpend')->get();
Excel::store( new SuperExport($super), 'export/Super.csv' );

It is assumed that with the columnFormats() method it is possible to change the format, but I don't see in the documentation what format is available, and when executing the code the problem continues.
Help pls :(
Comment: I Find the formats https://phpoffice.github.io/PhpSpreadsheet/1.11.0/PhpOffice/PhpSpreadsheet/Style/NumberFormat.html, and change to FORMAT_NUMBER and continue exporting with quotes :(
Answer: I found another solution, instead of using laravel excel, I tried another library: https://github.com/rap2hpoutre/fast-excel
So was my controller:
  (new FastExcel(Super::all()))->export(storage_path('app/export/SuperFast.csv'), function ($super) {
      return [
          'ano_plantacion' => $super->ano_plantacion,
          'zona' => $super->zona,
          'sitio' => $super->sitio,
          'manejo' => $super->manejo,
          'sup_ha' => $super->sup_ha,
          'codigo' => $super->codigo,
          'repend' => $super->repend,
      ];
  });

This is how my csv was: http://prntscr.com/squjh5


Possible to create a multi-user/shared session/instance in Java EE?

Question: I am attempting to write a Java EE application where multiple clients share the state of an instance of an application, the instance could be something like a document. Think something like Google Docs where multiple users edit the same document.
The approach I'm taking so far is to save the state to the database, using an Entity, with every change by a client. At such a change I then send the new state to the other clients connected (subscribing) to the instance.
My worry with this approach is, what happens when/if the application scales? At the moment any change is registered to the DB even if it is just for a short while, like a quick change that is overridden by another user. Also, information such as which users are connected to the instance and history of changes is stored to the DB. This seems inefficient to me to go back and forth between the DB.
With this my questions are:

Can I create multiple instances who's individual states are stored in an EJB, or something else?
Can I have an individual instances live for as long as there are users connected to this instance?
Can I share the state of an individual instance between multiple connected clients?
Can I detect when the last user disconnects from an instance so I can save its final state?

The questions might be large but I am mainly interested in, what concepts in Java EE should I be looking into?
Comment: I'm not able to answer fully, but would application scope be of any use here? http://docs.oracle.com/javaee/6/tutorial/doc/gjbbk.html
Answer: It seems that your problem matches to a publish / subscribe mecanism like the one into JMS queues ?
https://docs.oracle.com/javaee/6/tutorial/doc/bnceh.html


Express each of the following statements using quantifiers

Question: Let F(x, y) be the statement x can fool y. Where the universe of discourse is the
set of all people in the world

(a) Everybody can fool Gavin.
(b) Everybody can fool somebody.
(c) No one can fool everybody.
(d) There is someone who can't be fooled by anyone.
(e) No one can fool themselves.

Here is my attempt. I just want to confirm which is correct and which isn't. Thank you!

a) ∀x F(x, Gavin)
b) ∀x ∃y F(x, y)
c) ¬∀x ∀y F(x, y)
d) ∀x ∃y ¬[F(x, y)]
e) ¬∀x ∃x F(x, x)
Comment: Welcome to MSE. For some basic information about writing mathematics at this site see, *e.g.*, [basic help on mathjax notation](/help/notation), [mathjax tutorial and quick reference](//math.meta.stackexchange.com/q/5020), [main meta site math tutorial](//meta.stackexchange.com/a/70559) and [equation editing how-to](//math.meta.stackexchange.com/q/1773).
Answer: The first two are correct.

No one can fool everybody. That is, there does not exist someone who can fool everybody, so should be $\neg \ \exists x \ \forall y \ F(x,y)$. Your answer translates to 'not everyone can fool everyone' which is different.

There is someone who can't be fooled by anyone. So should be $\exists y \ \forall x \ \neg \ F(x,y)$. Your answer means 'everyone has a person they cannot fool'

No one can fool themselves. Simply $\forall x \ \neg F(x,x)$. It doesn't make sense to apply two different quantifiers to the same variable.
Comment: Ahh, I was getting confused between the order.
And the 2nd expression on no. 5 was a typo, haha
Thank you very much!


Capturar nome do arquivo

Question: Tenho um form que eu procuro o caminho de um arquivo em .mdb (banco de dados do Access), porém eu queria saber como que eu posso limitar e pegar exatamente a string do arquivo entre a última barra do OpenFileDialog e o ponto do .mdb.
Até agora fiz esse formato:
private void button1_Click(object sender, EventArgs e)
{
    OpenFileDialog dlg = new OpenFileDialog();
    dlg.Filter = "Database Files|*.mdb";

    if (dlg.ShowDialog() == DialogResult.OK)
    {
         string dbfile = dlg.FileName;
         label1.Text = dbfile;

         string file_name = dbfile.Split('\\')[5];

         string first = file_name.Split('.').FirstOrDefault();
    }
}

Eu gostaria que não fosse necessário chamar a última barra do diretório do 5º array (pois assim o item poderia estar em qualquer pasta, não necessariamente na quarta pasta do computador), e sim um dado dinâmico que conseguisse ler a última barra e o .mdb.
Answer: A melhor forma é usar um método já pronto como o GetFileNameWithoutExtension().
Coloquei no GitHub para referência futura.
Answer: Você pode usar a classe FileInfo, nela você irá encontrar diversos métodos para trabalhar com arquivos
FileInfo fileInfo = new FileInfo(dbfile);
//Mostra o nome do arquivo
string fileName = fileInfo.Name;
//Mostra a extensão do arquivo
string fileExtension = fileInfo.Extension;
//Mostra o caminho completo do arquivo junto com o nome
string fileFullName = fileInfo.FullName;

Comment: posso transformar esse `Console.WriteLine(fileInfo.Name);`em uma variável?
Comment: Vou editar o exemplo pra usar como variável

Capturar nome do arquivo