How to fetch objects from arraylist and set on text view

Question: I am trying to make a quiz app and want to fetch objects from array list an set on text view. I want to change the content of text view as well as radio buttons on the click of button. I have tried every possible way to do that but I still can't make it work.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Iterator;

public class MainActivity extends AppCompatActivity {
TextView tv;
RadioGroup radioGroup;
RadioButton radioButton;
Button btnnext;
int id,j;
Questions q1,q2,q3,q4,q;
ArrayList<Questions> list;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tv=(TextView)findViewById(R.id.ques);
    radioGroup=(RadioGroup)findViewById(R.id.rg1);
    btnnext=(Button)findViewById(R.id.button);
    id=radioGroup.getCheckedRadioButtonId();
    radioButton=(RadioButton)findViewById(id);
    q1=new Questions();
    q1.setQues("Ques 1.What is the full form of SMTP?");
    q1.setOption1("Simple Mail Transfer Protocol");
    q1.setOption2("Simple Mail Text Person");
    q1.setOption3("Simple Message Transfer Protocol");
    q1.setOption4("Sound Mail Text Pattern");

    q2=new Questions();
    q2.setQues("Ques 2.What is the full form of TCP?");
    q2.setOption1("Transfer Control Protocol");
    q2.setOption2("Text Control Protocol");
    q2.setOption3("Transfer Communication Person");
    q2.setOption4("Text Control Person");

    q3=new Questions();
    q3.setQues("Ques 3.What DNS stands for?");
    q3.setOption1("Domain Name System");
    q3.setOption2("Domain Name Server");
    q3.setOption3("Distributed Name Server");
    q3.setOption4("Distributed Name System");

    q4=new Questions();
    q4.setQues("Ques 4.What is a port?");
    q4.setOption1("Numbered Socket");
    q4.setOption2("Protocol");
    q4.setOption3("Server");
    q4.setOption4("Path");
    list=new ArrayList<>();
    list.add(q1);
    list.add(q2);
    list.add(q3);
    list.add(q4);

    String one=q1.getQues();
    tv.setText(one);
    ((RadioButton) radioGroup.getChildAt(0)).setText(q1.getOption1());
    ((RadioButton) radioGroup.getChildAt(1)).setText(q1.getOption2());
    ((RadioButton) radioGroup.getChildAt(2)).setText(q1.getOption3());
    ((RadioButton) radioGroup.getChildAt(3)).setText(q1.getOption4());
    String Ques[]=new String[4];

   /* for(int i=0;i<list.size();i++)
    {
        Questions q=list.get(i);
        tv.setText(q.getQues());
    }*/
   btnnext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            while(j<=list.size()){
                q=list.get(j);
                tv.setText(q.getQues());
                j++;
            }

        }
    });

}
}
Questions.java
public class Questions {

private String ques;
private String option1;
private String option2;
private String option3;
private String option4;

public String getQues() {
    return ques;
}

public void setQues(String ques) {
    this.ques = ques;
}

public String getOption1() {
    return option1;
}

public void setOption1(String option1) {
    this.option1 = option1;
}

public String getOption2() {
    return option2;
}

public void setOption2(String option2) {
    this.option2 = option2;
}

public String getOption3() {
    return option3;
}

public void setOption3(String option3) {
    this.option3 = option3;
}

public String getOption4() {
    return option4;
}

public void setOption4(String option4) {
    this.option4 = option4;
}
}

main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:text="Test Paper 1"
    android:textSize="25dp"
    android:id="@+id/test"
    android:textAlignment="center"
    android:layout_marginTop="30dp"/>

<LinearLayout
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="300dp"
    android:layout_below="@+id/test"
    android:layout_marginTop="30dp"
    android:id="@+id/queslay">
    <TextView
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:textSize="18dp"
        android:padding="18dip"
        android:id="@+id/ques"
        android:textColor="#ffffff"></TextView>
    <RadioGroup
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:id="@+id/rg1"
        android:layout_marginLeft="30dp"
        android:layout_weight="0.4">
        <RadioButton
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/rg1ansl"
            />
        <RadioButton
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/rg1ans2"
            />
        <RadioButton
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/rg1ans3"
            />
        <RadioButton
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/rg1ans4"
            />
    </RadioGroup>
</LinearLayout>
<Button
    android:layout_width="120dp"
    android:layout_height="wrap_content"
    android:text="Next"
    android:layout_marginLeft="230dp"
    android:layout_below="@+id/queslay"
    android:id="@+id/button" />

<Button
    android:layout_width="120dp"
    android:layout_height="wrap_content"
    android:layout_below="@+id/queslay"
    android:text="Previous"
    android:layout_marginLeft="30dp"
    android:id="@+id/button2" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/button2"
    android:layout_marginTop="20dp"
    android:id="@+id/textView"
    android:layout_centerHorizontal="true"/>
</RelativeLayout>

Answer: first of all use constructor of your model
make int count =0; asa global variable
     public Questions(String ques, String option1, String option2, String option3, String option4) {
            this.ques = ques;
            this.option1 = option1;
            this.option2 = option2;
            this.option3 = option3;
            this.option4 = option4;
        }

and get your data on depend on the count
then on click of the next button click on count

      btnnext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if(count<=list.size()){

                    count++;
                    setQuestion();
                }

            }
        });
public void setQuestion(){
 tv.setText(list.get(count).getQuestion());
((RadioButton) radioGroup.getChildAt(0)).setText(list.get(count).getOption1());
    ((RadioButton) radioGroup.getChildAt(1)).setText(list.get(count).getOption2());
    ((RadioButton) radioGroup.getChildAt(2)).setText(list.get(count).getOption3());
    ((RadioButton) radioGroup.getChildAt(3)).setText(list.get(count).getOption4());
}

and in setQuestion() set your textview and radio button content and call setQuestion() in onCreate() for 0 position question
Comment: Thanks for the help @Avinash. "get your data on depend on the count " how to do this.I am new to android.
Comment: just make a global(field) variable int count =0;


Alternativa ao Miktex

Question: Olá. Estou fazendo um documento em RMD no Rstudio e gostaria de exporta-lo para word ou pdf. Vi que para isso eu preciso instalar o Miktex. No entanto, mesmo seguindo todos os passos ( o tutorial mais resumido está aqui, que sintetiza o que eu encontrei em vários outros lugares ) eu não consigo terminar de instalar o programa, pois ele não consegue extrair / instalar o arquivo initexmf.exe . Procurei em vários fóruns mas não encontrei uma solução definitiva para resolver esse problema e instalar o Miktex. Eu trabalho com o Windows 10 64 bit.
Alguém sabe como eu posso terminar de instalar o Miktex ou se existe alguma alternativa para eu conseguir exportar o RMD para word?
Answer: Ao contrário do Linux e macOS, as distribuições de LaTeX para o Windows são um lixo. Quase sempre dá algum conflito e é muito difícil consertar sem acesso a um bom terminal, coisa que o Windows não tem.
O que tenho sugerido nos últimos meses pra quem quer usar R e LaTeX no Windows é a instalação do pacote TinyTex. Sim, é um pacote pro R, mas ele instala uma versão do Tex Live que funciona muito bem. Instalar ela é muito fácil.
Em primeiro lugar, desinstale o MikTex.
Em segundo lugar, rode os seguintes comandos dentro do R:
library(devtools)
install_github(c("yihui/tinytex", "rstudio/rmarkdown"))
tinytex::install_tinytex()

Vão aparecer um aviso e duas mensagens de erro durante a execução do segundo comando. Ignore-as dando OK no prompt que aparecer e pronto. Após os procedimentos necessários, seu computador vai estar com o LaTeX instalado.
Feche e abra o RStudio antes de compilar o relatório pela primeira vez.
É basicamente isso. O mínimo do LaTeX vai estar instalado no teu PC. Caso mais pacotes sejam necessários, o próprio TinyTex vai instalar o que for preciso, desde que o teu computador esteja conectado à internet.
Vai ser possível criar relatório em RMarkdown dentro do RStudio ou compilar arquivos .tex a partir de editor de textos externos, como TexWorks e WinEdt.
Comment: Marcus muito obrigada! Funcionou perfeitamente!

Alternativa ao Miktex


NVMe PCIe Hard Disk on Freescale LS2080A not recognised

Question: I have a Freescale LS2080 box for which I am developing a custom linux 4.1.8 kernel using the Freescale Yocto project.
I have an NVMe hard disk attached to the LS2080 via a PCIe card, but the disk is not recognised when I boot up the board with my custom linux kernel.
I plugged the same combination of NVMe disk and PCIe card into a linux 3.16.7 desktop PC and it was detected and mounted without problem.
When building the LS2080 kernel using the Yocto project, I have enabled the NVMe block device driver and I have verified that this module is present in the kernel when booting on the board.
The PCIe slot on the board is working fine because I have tried it with a PCIe Ethernet card and a PCIe SATA disk.
I suspect that I am missing something in the kernel configuration or device tree, but I'm not sure what. When I add the NVMe driver to the kernel using menuconfig, the NVMe driver dependencies are supposed to be resolved.
Can anyone provide insight into what I am missing?
Comment: Did you try to add the nvme_core.default_ps_max_latency_us=5500 attribute? https://stackoverflow.com/a/78090806/5081063
Answer: First make sure that PCIe device is recognized using lspci.
If device is not shown in lspci list this is enumeration problem, to check the error use PCIe analyzers.
If the device is shown in the list then simply add the device vendor id and device ID to NVMe driver and recompile to load the driver for your device.


Drupal file upload field via popup

Question: So I'm using a "file" type input inside a form which is called within a popup...but then whenever I submit that form inside the popup after having selected a file, the popup always return an error....
Is there a way to prevent this from happening and to successfully submit the form accordingly even with a file upload?
Comment: Some more detail is needed to actually answer this question. Please explain in great detail what's going on and maybe post some code snippets as well to illustrate.
Comment: What's the error?
Comment: it's a custom error message...it calls the Popups.errorMessage function in popups.js pretty much
Answer: I made it by creating 'VIEWS' by selecting the facebook style micro publisher images as 'field' and filtered according to my requirement.

Drupal file upload field via popup


How to migrate a project to another machine

Question: I want to migrate an Android project developed in Android Studio from one machine to another machine so I can continue working.
I tried to copy the project directory to the target machine; but, when opening the project in Android Studio (File→Open) on the target machine, it doesn't load it as an Android project, instead it considers it to be just a directory.
How can I migrate a project to another machine?
Comment: It's a good time to start thinking about using version control. There are free options out there. If your project only lives on your computer, you will lose it eventually.
Comment: save your code onto github.com, or dropbox  then retrieve from same on other box
Comment: If reopened, would be a duplicate of [this question](http://stackoverflow.com/questions/30773258/how-to-migrate-project-from-android-studio-to-android-studio)
Comment: @MsYvette Indeed. I checked age and the other having an accepted answer already. But yes, those criteria are totally valid.
Answer:
So how this can be done?

Copy the project directory.
I usually clean out the bits that wouldn't go into version control (e.g., build/, *.iml, .gradle/, .idea/) before importing the copied directory into Android Studio.
Answer: When opening the project in the new machine in  android studio for the first click on the folder directory and android studio will automatically sync the files and set up the new project.
Select app to include in project.
Next time when you click to open the project it will appear as a project and not a directory.

In addition to  Commonwares answer.
I keep all my projects either in a google drive directory, both locally on my machine and online or on github usually both locally, but always remotely. Anything that requires version control is on github.
That way if anything happens to a machine (which has happened in the past) all the projects are accessible to me.
If I need to use another machine I can download the complete project.
The other way is to copy the project to a removeble drive or usb stick and upload it to your other machine.
Answer: Usually this problem occurs, only when you try to load the project for first time. Instead of an android project, it considers to be just a directory.

However, I found a way around, which can fix this issue.

Copy the project directory to target Machine.
From Android Studio, go to File->Open; Browse the project directory.
Expand the project directory and open build.gradle. It will complete the required set up automatically and load the project.

Next time, when you will open the project, it will consider it an Android Project.


Generators of $\mathbb{Z}_{5}\times\mathbb{Z}_{11}$

Question: My task was to find all groups of order 55 and then describe each of them with generators. I found that there is only 1 abelian group, $\mathbb{Z}_{5}\times\mathbb{Z}_{11}$. I don't know how to find generators of this group. Any hints?
P.S.  Also I found that there is only 1 non-abelian group with generators: $G = C _ { 11 } \times _ { \phi } C _ { 5 } = \langle x , y | x ^ { 11 } = 1 , y ^ { 3 } = 1 , y x = x ^ { 4 } y \rangle$
Comment: After you ask a question here, if you get an acceptable answer, you should "accept" the answer by clicking the check mark $\checkmark$ next to it. This scores points for you and for the person who answered your question. You can find out more about accepting answers here: [How do I accept an answer?](http://meta.math.stackexchange.com/questions/3286/), [Why should we accept answers?](http://meta.math.stackexchange.com/questions/3399/), [What should I do if someone answers my question?](https://math.stackexchange.com/help/someone-answers).
Answer: Hint: this group is isomorphic to $\mathbb{Z_{55}}$.
Comment: So: $x ^ { 11 } = 1 , y ^ { 5 } = 1 , y x y ^ { - 1 } = x ^ { r } , \text { for some } r , 1 \leq r < 11$?
Comment: You wrote your task was to find all the groups of order $55$ up to isomorphism. So instead of $\mathbb{Z_5}\times\mathbb{Z_{11}}$ you can take the group $\mathbb{Z_{55}}$ as they are isomorphic according to the Chinese remainder theorem. And it is obvious that $\mathbb{Z_{55}}=\langle 1\rangle$. If for some reason you still want to work with $\mathbb{Z_5}\times\mathbb{Z_{11}}$ you can prove the element $(1,1)$ has order $55$, hence generates the whole group.
Answer: You can work with $\Bbb Z_{55}$ and there will be $\varphi (55)=40$ generators, corresponding to integers coprime with $55$.
Answer: Since $5$ and $11$ are relatively prime, the element $(1_5, 1_{11})$ will generate $\mathbb{Z}_5\times \mathbb{Z}_{11}$


How to log GuestAssignment Compliance Status' and output as a CSV

Question: I have the following GuestConfiguration with several compliance status':

I want to be able to view these records in the log analytics workspace or something similar and eventually, output the results as a CSV for auditing.

I tried to use the policy assignment. However, this only gives me the overall "is the VM compliant": YES/NO. I'm trying to keep the compliance granularity per VM.
Answer:
I want to be able to view these records in the log analytics workspace or something similar and eventually, output the results as a CSV for auditing.

As there is no feature in Log Analytics to export query results to Excel, you can achieve the same scenario by using a Logic App.
Here is the steps to send Log Analytics query result to CSV using Logic Apps.

Run your KQL query in Log Analytics
Create a below design in Logic App

3.After running the Logic App flow, the CSV file generated by the KQL query has been uploaded to the Storage account as shown below.

CSV File

Reference: Connect to Log Analytics or Application Insights from workflows in Azure Logic Apps
Comment: Thank you for your answer. However, I ended up solving this problem another way. I also used a KQL query. I used the Azure Resource Graph Explorer and queried the GuestAssignment resources from there.


Why doesn't the JButton added to the DefaultTreeCellRenderer display?

Question: I write a subclass of DefaultTreeCellRenderer, inside the method getTreeCellRendererComponent, I added a JButton to the DefaultTreeCellRenderer Object, I'd like to see each node of the JTree have a JButton rendered. but the JButton does not display, please see the code and screenshot. Thanks in advance!
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;

public class TreeDemo{
    TreeDemo(){
        JFrame jFrame = new JFrame("TreeDemo");
        DefaultMutableTreeNode rootNode = initNodes();
        JTree jTree = new JTree(rootNode);
        jTree.setCellRenderer(new CustomRenderer());
        jFrame.getContentPane().add(jTree);
        jFrame.setMinimumSize(new Dimension(400, 300));
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jFrame.setVisible(true);
    }

    DefaultMutableTreeNode initNodes(){
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
        DefaultMutableTreeNode sub1 = new DefaultMutableTreeNode("sub1");
        DefaultMutableTreeNode sub2 = new DefaultMutableTreeNode("sub1");
        DefaultMutableTreeNode sub1_1 = new DefaultMutableTreeNode("sub1_1");
        DefaultMutableTreeNode sub1_2 = new DefaultMutableTreeNode("sub1_2");
        DefaultMutableTreeNode sub2_1 = new DefaultMutableTreeNode("sub2_1");
        DefaultMutableTreeNode sub2_2 = new DefaultMutableTreeNode("sub2_2");
        root.add(sub1);
        root.add(sub2);
        sub1.add(sub1_1);
        sub1.add(sub1_2);
        sub2.add(sub2_1);
        sub2.add(sub2_2);

        return root;
    }

    class CustomRenderer extends DefaultTreeCellRenderer{
        @Override
        public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
            JButton button = new JButton("Button");
            setLayout(new BorderLayout());
            add(button, BorderLayout.LINE_END);
            setText("Node");

            return this;
        }
    }

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

Screenshot of the result of the code above
Comment: *"I'd like to see each node of the JTree have a JButton rendered"* Why? And what is supposed to happen when the user activates the button? See [What is the XY problem?](http://meta.stackexchange.com/q/66377)
Comment: `DefaultTreeCellRenderer` is (an extension of) a `JLabel` - not intended to receive and display buttons (BTW `getComponent` can be called a lot of times - each cell when updating the tree - lot of buttons being created)
Answer: Event though JLabel extends java.awt.Container, I don't think you can use it like a JPanel.
A tree cell renderer must implement interface javax.swing.tree.TreeCellRenderer. It doesn't need to extend DefaultTreeCellRenderer. Also note that JTree will use the same renderer instance to render all the tree nodes.
The below code is your code, but with a different tree cell renderer. It creates a single JButton and that button is displayed for every tree node.
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeCellRenderer;

import java.awt.Component;
import java.awt.Dimension;

public class TreeDemo{
    TreeDemo(){
        JFrame jFrame = new JFrame("TreeDemo");
        DefaultMutableTreeNode rootNode = initNodes();
        JTree jTree = new JTree(rootNode);
        jTree.setCellRenderer(new ButtonRenderer());
        jFrame.getContentPane().add(jTree);
        jFrame.setMinimumSize(new Dimension(400, 300));
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jFrame.setVisible(true);
    }

    DefaultMutableTreeNode initNodes(){
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
        DefaultMutableTreeNode sub1 = new DefaultMutableTreeNode("sub1");
        DefaultMutableTreeNode sub2 = new DefaultMutableTreeNode("sub1");
        DefaultMutableTreeNode sub1_1 = new DefaultMutableTreeNode("sub1_1");
        DefaultMutableTreeNode sub1_2 = new DefaultMutableTreeNode("sub1_2");
        DefaultMutableTreeNode sub2_1 = new DefaultMutableTreeNode("sub2_1");
        DefaultMutableTreeNode sub2_2 = new DefaultMutableTreeNode("sub2_2");
        root.add(sub1);
        root.add(sub2);
        sub1.add(sub1_1);
        sub1.add(sub1_2);
        sub2.add(sub2_1);
        sub2.add(sub2_2);

        return root;
    }

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

class ButtonRenderer implements TreeCellRenderer {
    private JButton  button;

    public ButtonRenderer() {
        button = new JButton("Button");
    }

    @Override
    public Component getTreeCellRendererComponent(JTree    tree,
                                                  Object   value,
                                                  boolean  selected,
                                                  boolean  expanded,
                                                  boolean  leaf,
                                                  int      row,
                                                  boolean  hasFocus) {
        return button;
    }
}

And here is a screen shot of the running application...


Topology, Normal Spaces - Proving a function is continuous knowing that any composition is continuous.

Question: my question is regarding topology.

Given two topological spaces $X, Y$ and we know that $Y$ is $T_4$.
Let $f:X \rightarrow Y$ be a function such that for any continuous function $\phi:Y \rightarrow \mathbb{R}$, the composition $\phi \circ f$ is continuous.
Show that $f$ it self is continuous.

My attempt:
we want to show that for any open set $V$, $f^{-1}[V]$ is open. If we could find a function $g$ such that $g:Y \rightarrow \mathbb{R}$ would be zero in exactly $Y \setminus V$ and positive else where, then we could take the preimage of the open set $(0,\infty)$ which would be open in $X$ and be exactly $f^{-1}[V]$.
As I looked around, it seems we can build such a function when knowing that a set is $G_{\delta}$, and the space is normal but here we don't know that the set is $G_{\delta}$.
In the exam from which I took the question, the first question was to quote Urysohn's lemma, so the solution probably uses the lemma.
Any suggestions?
Comment: We need only assume the space is completely regular - $T_3$. It doesn't have to be Hausdorff
Answer: We prove that $f$ is continuous at each point, i.e for every $x\in X$ and $V$ an open neighborhood of $f(x)$, $f^{-1}(V)\subset X$ contains an open neighborhood of $x$.
Let $x\in X$ and let $f(x)\in V\subset Y$ be open. The sets $\{f(x)\}$ and $Y\setminus V$ are disjoint and closed. Therefore by Urysohn's lemma (as $Y$ is normal) there exists a continuous function $\phi:Y\to [0,1]$ such that: $$\phi(x)=0,\,\phi(Y\setminus V)=\{1\}$$
Thinking of $\phi$ as a function from $Y$ to $\mathbb{R}$ (via the continuous inclusion $\iota:[0,1]\to\mathbb{R}$), we have: $$\phi^{-1}(\mathbb{R}\setminus\{1\})\subset V$$ Hence: $$x\in f^{-1}(\phi^{-1}(\mathbb{R}\setminus\{1\}))\subset f^{-1}(V)$$
And $f^{-1}(\phi^{-1}(\mathbb{R}\setminus\{1\}))$ is an open subset that contains $x$. This concludes the proof.
Comment: @Amit There is a definition of continuity and point-wise continuity. What I proved is that $f$ is pointwise continuous at each point, and hence is continuous.
Comment: @Amit, to show that a set is open you can show that it can be presented as a union of open sets, and that is what GBA showed.
Repeating the process for each $ x \in f^{-1}[V}$ will show the set is open.
Comment: Why is it enough for $f^{-1}(V)$ to *contains* an open neighborhood of $x$? The definition of continuous function states that $f^-1(V)$ *is* an open neighborhood of $x$.
Comment: Got it, Thanks!


singing without lyrics

Question: I was recently listening to some music while working on a book I'm writing and an orchestral piece came on. There was a woman singing over this instrumental but it wasn't lyrical words, more just sustained vowels. An example of the kind of music I'm talking about is the song 'Ocean Lullaby' by Henrik Astrom. It is a part of the 'Submersive - Colossal Trailer Music' album (which you can find on youtube). My only way of describing it was like a sirens song but I'd really like to know the name of the technique if anyone has any ideas or knows what I'm talking about.
Comment: Not exactly the same, but check out *scat* singing.
Answer: That's called a "vocalise" (pronounced "vocal-ease")

Vocalise dates back to the mid-18th century. Jean-Antoine Bérard's 1755 compilation L'art du chant includes a selection of songs (sans paroles) by composers such as Lully (1632–1687) and Rameau (1683–1764), chosen for their value as exercises in vocal technique. Accompanying the exercises were instructions on mastering the technical challenges they posed. By the 19th century vocalises were commonly composed specifically for pedagogical purposes rather than being adapted from existing songs.
A related tradition of vocalise sprang up in the 19th century, with wordless technical etudes set to piano accompaniment, following the fashion of the time of setting even the most mechanical of études to piano accompaniment with the thought that this would inspire the performer to execute the music more artistically.
In the early 20th century, many orchestral scores incorporated wordless choruses (especially female choruses) for coloristic effects, and such choruses may be found in works by Debussy, Ravel, Vaughan Williams, Holst, and in many film scores.
https://en.wikipedia.org/wiki/Vocal_warm_up#Vocalise

singing without lyrics


How to compute the correlation between the min and max of two random variables?

Question: A joint bivariate function (PDF) with variables $A,B$ is given in the function:
$f_{A,B}(a,b) = Cab(a+b),  \quad 0<a<1, \quad 0<b<1.$
where $C$ is just a constant. Assume that $Q=\min(A,B)$ and $R = \max(A,B).$
Compute Corr($Q,R),$ ie the correlation.
From $f(a,b)= \int_0^1\int_0^1 Cab (a+b) dxdy = 1,$ $C = 18/5.$ so that
$$f_{AB}(a,b)= \frac{18}{5} ab (a+b) da db, \ 0 < a, b < 1.$$
UPDATE:
\begin{align*}
f_A(a) & =
 1/5 \ (9a^2 + 6a), \ 0 < a < 1\\
f_B(b) &= 1/5 \ (9b^2 + 6b), \ 0 < b < 1
\end{align*}
$$E(A) = 1/5 \int_0^1 a \cdot(9a^2 + 6a) da =17/20 = E(B)$$
$$E(A^2)=1/5 \int _0^1 \left(9a^4 + 6a^3\right) da = 33/50 = E(B^2)$$
\begin{align*}
1 - F_Q(q) & =  P(A >q)P(B > q)\text{ (CDF of min)}\\
& =
\int _q^1 1/5 (9a^2 + 6a) da \cdot \int _q^1 1/5 (9b^2 + 6b) db\\
& =
\left(\frac{1}{5}(-3q^3-3q^2+6)\right)^2, & \ 0 \le q < 1
\end{align*}
The expectation and variance of $Q$ are:
\begin{align*}
\mathbb{E}(Q) & = \int_0^1  \frac{1}{5}(-3q^3-3q^2+6)dq +
\int_1^2  \frac{1}{25}(-3q^3-3q^2+6)^2 dq =
9.85234\\
\mathbb{E}(Q^2) & = \int_0^1 \frac{2q}{5}(-3q^3-3q^2+6)dq
+
\int_1^2  \frac{2q}{25}(-3q^3-3q^2+6)^2 dq = 32.9597\\
\text{Var}(Q) & = \mathbb{E}(Q^2) - (\mathbb{E}(Q))^2   \\
& =  32.9597 - (9.85234)^2 \\
& = \text{negative number; but variance is nonnegative}
\end{align*}
I got stuck-in here because I got the variance to be negative which is wrong and I don't know where I went wrong. This is why this question is different to the other one. Thank you.
Comment: Evidently $(A,B)$ are independent Uniform$(0,1)$ variables, right?  If so, please state that; if not, your derivation fails at the outset.  Then, please explain what this question might have to do with $f:$ it seems like $f$ is superfluous and you are just reasking a previous question at https://stats.stackexchange.com/questions/604386.  If $f$ is intended to be a density, then this is really the same as your previous question but with a minor variation in $f$ and you can apply the techniques that were successful there.
Comment: The original question for this posted question did not say that $A$ and $B$ are independent but after obtaining their marginal PDF it suggest that they are independent.
Comment: Please, that question [here](https://stats.stackexchange.com/questions/604386/correlation-between-min-and-max-of-two-different-uniform-distribution) is different to this one since it is a different function, although they may look similar but not the same question
Comment: $f$ is the joint PDF.
Comment: The only difference I see is one of computing the integrals.  Is there a new statistical question?  BTW, having equal marginals does not imply independence.
Comment: Re the edits: (1) What is "$U$"?? (2) Please graph your expression for $F_U.$  (3) The expression you give for $1-F_U$ ought to be a perfect square, because it is one expression times itself.  Your results clearly are not a perfect square.  That's an algebraic mistake.  (4) Why do you give two identical cases for that result?  One of them gives the square and the other does not.
Comment: (1) $U$ was meant to be $Q.$ (2) [Graph](https://www.desmos.com/calculator/bjjd7pw58c) (3) I've corrected it (4) It was a mistake.
Comment: Re (2): Does that look anything like a CDF or survival function to you??
Comment: It looks completely different. That is why I am wrong:)
Comment: Yes.  If you get the CDF wrong, it's unlikely anything you calculate with it will be correct.  It's always a good idea to sketch the graph of any CDF you are working with, whether you derived it yourself or someone gave it to you.  At a minimum it will give you a sense of the basic properties of the distribution: its support, its continuity or lack thereof, its location, its spread, and perhaps a little about its skewness.
Comment: You are absolutely right.
Comment: @whuber, could you please help me to unravel this question? Thank you.
Answer: Because this is really the same as your previous question, changing only the details, permit me to outline a general approach to finding moments of the max and min of a bivariate random variable.
So, generally, let $(X,Y)$ be any bivariate random variable and write $M=\max(X,Y),$ $m=\min(X,Y)$ for its extrema.  For any numbers $(i,j)$ (usually natural numbers) the (raw) $(i,j)$ moment of $(M,m)$ is
$$\mu_{i,j}(M,m) = E[M^i m^j].$$
These are relevant because correlation is a function of some of these moments.  One formula for it is
$$\rho(M,m) = \frac{\mu_{1,1}(\bar M, \bar m)}{
\sqrt{\mu_{2,0}(\bar M, \bar m)\ \mu_{0,2}(\bar M, \bar m)}}$$
where $\bar M = M - \mu_{1,0}(M,m)$ and $\bar m = m - \mu_{0,1}(M,m)$ are the centered versions of $M$ and $m.$
The idea is to condition the calculation of the expectation according to which variable(s) $X$ and $Y$ correspond to $M$ and $m.$  There are three possibilities:

When $X \gt Y,$ $X=M$ and $Y=m.$

When $X \lt Y,$ $X=m$ and $Y=M.$

When $X = Y,$ $X=Y=M=m.$

Thus, according to the basic properties of conditional expectation,
$$\begin{aligned}
\mu_{i,j}(M,m) &= E[X^i Y^j\mid X\gt Y]\Pr(X\gt Y)\\
& + E[Y^i X^j\mid X\lt Y]\Pr(X \lt Y)\\
& + E[X^{i+j}\mid X=Y]\Pr(X=Y) \\
\\
& = E[X^i Y^j\text{ and }X\gt Y] + E[Y^i X^j\text{ and }X\lt Y] +E[X^{i+j}\text{ and }X = Y].
\end{aligned}$$
When $\Pr(X=Y)=0,$ as when $(X,Y)$ has a continuous distribution, the third term drops out.
When $(X,Y)$ has a density function $f,$ it is continuous.  Fubini's Theorem usually applies and reduces the foregoing to

$$\begin{aligned}
&\mu_{i,j}(M,m) \\ &= \int_{-\infty}^\infty y^j \left(\int_y^\infty x^if(x,y)\mathrm dx\right)\mathrm dy + \int_{-\infty}^\infty y^i \left(\int_{-\infty}^yx^j f(x,y)\mathrm dx\right)\mathrm dy.
\end{aligned}\tag{*}$$

Example
Suppose, as in the present question,
$$f(x,y) = C xy(x+y)\ \mathcal{I}_{[0,1]\times [0,1]}.$$
The indicator function $\mathcal I$ explicitly states the density is zero unless $0\le x \le 1$ and $0 \le y \le 1.$
We plug this $f$ into $(*)$ and compute
$$\begin{aligned}
\mu_{i,j}(M,m) &= \int_{-\infty}^\infty\int_y^\infty x^i y^j  C xy(x+y)\mathcal{I}_{[0,1]\times [0,1]}\,\mathrm dx\mathrm dy \\
&+ \int_{-\infty}^\infty\int_{-\infty}^y y^i x^j  C xy(x+y)\mathcal{I}_{[0,1]\times [0,1]}\,\mathrm dx\mathrm dy\\
&= C\int_0^1 \int_y^1 x^i y^j   xy(x+y)\,\mathrm dx\mathrm dy
+ C \int_0^1\int_{0}^y y^i x^j  xy(x+y)\,\mathrm dx\mathrm dy\\
&= C\int_0^1\left\{\int_y^1 x^{i+2}y^{j+1} + x^{i+1}y^{j+2}\,\mathrm dx+ \int_0^y x^{j+2}y^{i+1} + x^{j+1}y^{i+2}\,\mathrm dx\right\}\mathrm dy
\end{aligned}$$
The rest is just calculations.  For the values of $i$ and $j$ needed in the question (natural numbers), this formula involves the sum of four univariate integrals over $x.$  Just evaluate them (all four have such similar forms that you need only evaluate one and apply that result in all four cases), integrate that with respect to $y,$ and plug the answers into the formula for $\rho(M,m).$  (The constant $C$ can be found using the formula for $\mu_{0,0}.$)
Comment: Not so much can be obtained from the internet about this approach. Any textual reference(s) for me to delve into it more?
Comment: My understanding is that I will need to compute $\mu_{0,1} (x=M, y=m)$ using $(*),$ then subtract it from $M,$ to obtain $\bar M.$ That is:
\begin{aligned}
\bar M & = M-\mu_{0,1} (x=M, y=m)\\
& = x - \mu_{0,1} (x, m), \qquad (**)
\end{aligned}
(similarly for $\bar m$). Then I compute $\mu_{1,1,} (\bar M, \bar m), \ \mu_{2,0} (\bar M, \bar m), \ \mu_{0,2,} (\bar M, \bar m).$ using $(*)$ with its input arguments from $(**).$ Am I thinking right?
Comment: Yes, that is how to apply the formulas.
Comment: Look for books on order statistics.  N. Balakrishnan is one authority.
Comment: I got the following after substituting and integrating for $\mu_{0,1}(x,m)$ but not quite sure: \begin{aligned}
\mu_{0,1} (x, m) &=  C\int_0^1\left\{ \left( \int_m^1 x^{i+2} m^{j+1} + x^{i+1}m^{j+2}\,\mathrm dx \right) + \left( \int_0^m x^{j+2} m^{i+1} + x^{j+1} m^{i+2}\,\mathrm dx \right) \right\}\mathrm dm\\
 &=  \frac{18}{5} \int_0^1\left\{ \frac{1}{3} m^{2} + \frac{1}{2} m^{3} - \frac{1}{24} m^{5} \right\}\mathrm dm \\
  &=  \frac{18}{5} \left( \frac{1}{9} + \frac{1}{8} - \frac{1}{24} \right)=  \frac{7}{10}.
\end{aligned}
Then,
$ \bar M = x - (7/10), \quad  \bar m = y - (7/10).$
Comment: Are $\bar M$ and $\bar m$ correct? I just want to make sure since the rest of the computations depend on them
Comment: I'm just checking with you to verify if my computations in the comments above are accurate?


"Relay access denied" overflowing postfix mail.log

Question: My mail.log is overflowing with random spammers attempting to send spam through my server.
Is this typical or have I misconfigured something?
Is there a way to ban an IP after several attempts of relaying
or is there a way not to log these attempts? (latter might be a bad idea)
Answer: Once they find an IP that answers to port 25, they'll try everything they can to relay through it or guess valid email addresses that they can deliver spam to.  I don't think you want to quit logging it just in case something does come through that you later need to diagnose.
fail2ban and iptables --recent would cut down on the log entries by firewalling the IPs that are attempting to connect multiple times.  Each has a 'window' of opportunity for a spammer to try before getting blocked.  fail2ban would be better in this case as it would block based on failure messages.  iptables --recent is much less discriminate and might block legitimate connections that passed a threshhold.
You could alter your syslog configuration to log only .info to your maillog, and .warn/.err to a separate file.
Comment: Thanks, working on setting up fail2ban as you recommended.
Answer: You can also set these options for postfix to reject connections from rogue clients.
<code>smtpd_error_sleep_time = 10s
smtpd_soft_error_limit = 10
smtpd_hard_error_limit = 20
</code>
Comment: can you please elaborate on how these limits could be used to block "relay access" attacks?


BUS (Discrete mathematics)

Question: Q.: There are 4 buses with full capacity of 40 people. 163 fans of local FC goes to other city with those 4 buses. Please, use proof by contradiction, that in some bus there are more than 40 people. Thank you!
Comment: Pigeonhole?${}$
Comment: seems, yes and kind of
Answer: HINT: Suppose that Bus $1$ contains $b_1$ people, Bus $2$ contains $b_2$ people, and so on. Then we must have
$$b_1+b_2+b_3+b_4=163\;.$$
If every bus has at most $40$ people, then $b_1\le 40$, $b_2\le 40$, $b_3\le 40$, and $b_4\le 40$. Add these four inequalities; what does that tell you about $b_1+b_2+b_3+b_4$?
Answer: This is a simple case of the pigeonhole principle application, but the OP explicitly asked for a proof by contradiction, so, here is a proof.
Assume that there is no bus with more than 40 people in it. If $p_i$ denotes the number of the passengers in the $i$th bus, then $$b_i\leq40,\quad i=1,2,3,4$$ There are total $163$ people in all buses, therefore $$b_1+b_2+b_3+b_4=163\label{eq1}\tag{1}$$ But since $b_i\leq40$, then sum of $b_i$s would never exceed $160$, i.e., $$b_1+b_2+b_3+b_4\leq160$$ According to equation (\ref{eq1}) the sum can be replaced by $163$, so $$163\leq160$$ But this is a contradiction and thus the there is at least one bus with more than $40$ passengers.
Answer: Let every bus contained less than 40 peoples. Consider there are $(40-x_1)$ people in the first bus. Let there are $(40-x_2)$ people in second bus. Also there are $(40-x_3)$ in the third and $(40-x_4)$ in the fourth bus. Now from this we can easily write this     $x_1,x_2,x_3,x_4\ge 0$.
Now total number of peoples in the buses are
$(40-x_1)+(40-x_2)+(40-x_3)+(40-x_4)=160-(x_1+x_2+x_3+x_4)$. Which is equal to 163. Then,$160-(x_1+x_2+x_3+x_4)=163$
$\implies (x_1+x_2+x_3+x_4)$ is a negative number( Contradiction)
Answer: If no bus has $40$ passengers, then we can transport at most $156=4\times39$ people.

BUS (Discrete mathematics)


Kubectl command throwing error: Unable to connect to the server: getting credentials: exec: exit status 2

Question: I am doing a lab setup of EKS/Kubectl and after the completion cluster build, I run the following:
> kubectl get node

And I get the following error:
Unable to connect to the server: getting credentials: exec: exit status 2

Moreover, I am sure it is a configuration issue for,
kubectl version
usage: aws [options] <command> <subcommand> [<subcommand> ...] [parameters]
To see help text, you can run:

  aws help
  aws <command> help
  aws <command> <subcommand> help
aws: error: argument operation: Invalid choice, valid choices are:

create-cluster                           | delete-cluster
describe-cluster                         | describe-update
list-clusters                            | list-updates
update-cluster-config                    | update-cluster-version
update-kubeconfig                        | wait
help
Client Version: version.Info{Major:"1", Minor:"17", GitVersion:"v1.17.1", GitCommit:"d224476cd0730baca2b6e357d144171ed74192d6", GitTreeState:"clean", BuildDate:"2020-01-14T21:04:32Z", GoVersion:"go1.13.5", Compiler:"gc", Platform:"darwin/amd64"}
Unable to connect to the server: getting credentials: exec: exit status 2

Please advise next steps for troubleshooting.
Answer: Please delete the cache folder folder present in
~/.aws/cli/cache
Answer: For me running kubectl get nodes or kubectl cluster-info gives me the following error.
Unable to connect to the server: getting credentials: exec: executable kubelogin not found

It looks like you are trying to use a client-go credential plugin that is not installed.

To learn more about this feature, consult the documentation available at:
      https://kubernetes.io/docs/reference/access-authn-authz/authentication/#client-go-credential-plugins

I did the following to resolve this.

Deleted all of the contents inside ~/.kube/. In my case, its a windows machine, so its C:\Users\nis.kube. Here nis is the user name that I logged into.

Ran the get credentials command as follows.

    az aks get-credentials --resource-group terraform-aks-dev --name terraform-aks-dev-aks-cluster --admin

Note --admin in the end. Without it, its giving me the same error.
Now the above two commands are working.
Reference: https://blog.baeke.info/2021/06/03/a-quick-look-at-azure-kubelogin/
Comment: It's bad practice to use admin credentials and in a proper configured AKS cluster with disabled local accounts, the --admin parameter will fail.
Answer: Did you have the kubectl configuration file ready?
Normally we put it under ~/.kube/config and the file includes the cluster endpoint, ceritifcate, contexts, admin users, and so on.
Furtherly, read this document: https://docs.aws.amazon.com/eks/latest/userguide/create-kubeconfig.html
Comment: On the money!  Thank you for the assist.
Answer: In my case, as I am using azure (not aws), I had to install "kubelogin" which resolved the issue.
"kubelogin" is a client-go credential (exec) plugin implementing azure authentication. This plugin provides features that are not available in kubectl. It is supported on kubectl v1.11+
Answer: Make sure you have installed AWS CLI.
https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html
Answer: Can you check your ~/.kube/config file?
Assume if you have start local cluster using minikube for that if your config is available, you should not be getting the error for server.
Sample config file

    apiVersion: v1
    clusters:
    - cluster:
        certificate-authority: /Users/singhvi/.minikube/ca.crt
        server: https://127.0.0.1:32772
      name: minikube
    contexts:
    - context:
        cluster: minikube
        user: minikube
      name: minikube
    current-context: minikube
    kind: Config
    preferences: {}
    users:
    - name: minikube
      user:
        client-certificate: /Users/singhvi/.minikube/profiles/minikube/client.crt
        client-key: /Users/singhvi/.minikube/profiles/minikube/client.key
Answer: You need to update/recreate your local kubeconfig. In my case I deleted the whole ~/.kube/config and followed this tutorial:
https://docs.aws.amazon.com/eks/latest/userguide/create-kubeconfig.html
Answer: In EKS you can retrieve your kubectl credentials using the following command:
% aws eks update-kubeconfig --name cluster_name
Updated context arn:aws:eks:eu-west-1:xxx:cluster/cluster_name in /Users/theofpa/.kube/config

You can retrieve your cluster name using:
% aws eks list-clusters
{
    "clusters": [
        "cluster_name"
    ]
}

Answer: I had the same problem, the issue was that in my .aws/credentials file there was multiple users, and the user that had the permissions on the cluster of EKS (admin_test) wasn't the default user. So in my case, i made the "admin_test" user as my default user in the CLI using environment variables:
export $AWS_PROFILE='admin_test'

After that, i checked the default user with the command:
aws sts get-caller-identity

Finally, i was able to get the nodes with the kubectl get nodes command.
Reference: https://docs.aws.amazon.com/eks/latest/userguide/create-kubeconfig.html
Answer: I had the same error and solved it by upgrading my awscli to the latest version.
Answer: In Azure:

Delete all contents of the ~/.kube/ folder

Execute:
sudo az aks install-cli

(https://learn.microsoft.com/en-us/answers/questions/1106601/aks-access-issue)

Reconnect:
az login
az aks get-credentials -n {clustername} -g {resourcegroup}

It worked for me for Azure.
Answer: Removing and adding the ~/.aws/credentials file worked to resolve this issue for me.
rm ~/.aws/credentials
touch ~/.aws/credentials


Show/Hide div using if then statement (javascript)

Question: I have this show/hide set up here: http://jsfiddle.net/TwDSx/38/
What I would like to do is have the plus sign go away if the content is showing and vise versa if the content isn't showing hide the minus sign and show the plus.
I read articles on this using images to swap out, but nothing with just using html/css. Also, I would like to keep the javascript out of the html if this is possible, and just call for it externally.
any help is appreciated!
Answer: EDIT :
You can attach an event handler on your click to toggle the display attribute of the + or - button
$('#hide,#show').click(function(){
  $('#hide,#show').toggle();
})

Quick demo:
http://jsfiddle.net/TwDSx/39/
Comment: Questions and answers need code provided within the post. Linking to code off-site alone is not suitable.
Comment: Please try to post your code within the answer itself. There may be times when it's impractical or otherwise needs "treatment", but especially when you don't have Linus Torvald's War and Peace for an answer, put the code in the answer block. It's just lazy not to. `:)`
Comment: dude ... I didn't link to my personal blog or anything.. nor am I promoting jsfiddle..
Comment: I simply said "off-site". The point is that when that fiddle disappears (not under StackOverflow's control), this answer becomes useless.  It's fine to link to jsfiddle for code demonstration, but you need to include the code in your post, too.
Comment: What you have in that fiddle, really, is more akin to "War war, what is it good for?!?!" Make your answers self-depicting and **complete** as possible. This is brief and honestly, I have not a clue what is needed, and by whom, what or why.
Answer: I modified your Javascript a little and extended it so you can keep it in an external file, you just need to ensure you hide the #show div with CSS if you load the page with the content already showing, or vice-versa for the #hide.
The Javascript is as follows:
$('#show').click(function() {
    ShowClick();
});

$('#hide').click(function() {
    HideClick();
});

//This Javascript can be external
function ShowClick() {
    $('#content').toggle('slow');
    $('#hide, #show').toggle();
};

function HideClick() {
    $('#content').toggle('fast');
    $('#show, #hide').toggle();
};

The Js-Fiddle can be seen here: http://jsfiddle.net/mtAeg/
Comment: Is there any way to load all of the javascript externally?
Comment: Definitely, that whole script can be kept in an external file. I've just got in the habit of keeping my jQuery listeners at the bottom of my views lately, something I should probably stop doing.
Answer: I think the simplest solution is to have only one button, #toggle, and to change the content of that button like so:
$('#toggle').click(function () {
    if (this.innerHTML == '-') {
        $('#content').slideUp('fast');
        this.innerHTML = '+';
    } else {
        $('#content').slideDown('slow');
        this.innerHTML = '-';
    }
});

fiddle


how to add a user on 100 servers when there is no NIS

Question: How  to add a single users in all the 100 servers When there is no centralization for adding users.
What would be the best way to add users in all the 100 systems
Comment: Fix "there is no centralization for adding users" first.
Comment: Well, if you can't add centralized authentication (LDPA, NIS, w/e), or centralized configuration management (ansible, puppet, chef, w/e), then in order to add a user on 100 servers... you'll have to add a user on 100 servers.
Comment: Is implementing LDAP or NIS or some other centralized authentication scheme not an option?
Comment: a user should be able to login in from all the systems no centralization for adding users
Answer: (This is not meant to be a full answer)
I've been working with Ansible lately.  Love it or hate it, this is a perfect fit for exactly what you're attempting to ask.
With that assumption, these steps will work pretty darn quick.
From: http://docs.ansible.com/intro_installation.html
<code>$ git clone git://github.com/ansible/ansible.git
$ cd ./ansible
$ source ./hacking/env-setup
</code>
From: http://docs.ansible.com/intro_adhoc.html
Create an inventory file of your hosts
<code>$ ansible all -m user -a "name=foo password=<crypted password here>"
</code>


ftp/sftp spring integration - localDirectory must not be null

Question: I am trying to poll ftp server for file and process them. I want to do it without xml configuration. I am using spring boot(1.2.5) and spring integration ftp (4.1.5)
I created a bean for session factory
    @Bean
public DefaultFtpSessionFactory ftpSessionFactory() {
    DefaultFtpSessionFactory ftpSessionFactory = new DefaultFtpSessionFactory();
    ftpSessionFactory.setHost(ftpProperties.ftpHost);
    ftpSessionFactory.setPort(Integer.parseInt(ftpProperties.ftpPort));
    ftpSessionFactory.setUsername(ftpProperties.ftpUser);
    ftpSessionFactory.setPassword(ftpProperties .ftpPassword);
    return ftpSessionFactory;
}

I am trying to configure ftp server polling as follows.
    @Bean
@InboundChannelAdapter(value = "receiveChannel", poller = @Poller(fixedRate="1000"))
public MessageSource pollFtpForFiles() {
    File localDirectory = new File(sftpProperties.localDirectory);
    System.err.println("LocalDirectory::"+localDirectory.getAbsolutePath()+"::exists::"+localDirectory.isDirectory());
    FtpInboundFileSynchronizer ftpInboundFileSynchronizer = new FtpInboundFileSynchronizer(ftpSessionFactory());
    ftpInboundFileSynchronizer.setRemoteDirectory(sftpProperties.remoteDirectory);
    ftpInboundFileSynchronizer.synchronizeToLocalDirectory(localDirectory);
    return new FtpInboundFileSynchronizingMessageSource(ftpInboundFileSynchronizer);
}

But I am getting following exception when I run the app.
Not sure what I am doing wrong. Can somebody help me. (I tried with sftp also with same result)
LocalDirectory::localDirForSftpTransfer::exists::true
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sftpInboundSetup' defined in file [/Users/rsamban/Documents/workspace/Second/target/classes/com/yesVin/integration/sftp/SftpInboundSetup.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'pollFtpForFiles' defined in class path resource [com/yesVin/integration/sftp/SftpInboundSetup.class]: **Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: localDirectory must not be null**
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:547)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:957)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:946)
    at com.yesVin.integration.SecondApplication.main(SecondApplication.java:16)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'pollFtpForFiles' defined in class path resource [com/yesVin/integration/sftp/SftpInboundSetup.class]: **Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: localDirectory must not be null**
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.integration.config.annotation.AbstractMethodAnnotationPostProcessor.resolveTargetBeanFromMethodWithBeanAnnotation(AbstractMethodAnnotationPostProcessor.java:362)
    at org.springframework.integration.config.annotation.InboundChannelAdapterAnnotationPostProcessor.createMessageSource(InboundChannelAdapterAnnotationPostProcessor.java:76)
    at org.springframework.integration.config.annotation.InboundChannelAdapterAnnotationPostProcessor.postProcess(InboundChannelAdapterAnnotationPostProcessor.java:62)
    at org.springframework.integration.config.annotation.MessagingAnnotationPostProcessor$1.doWith(MessagingAnnotationPostProcessor.java:151)
    at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:495)
    at org.springframework.integration.config.annotation.MessagingAnnotationPostProcessor.postProcessAfterInitialization(MessagingAnnotationPostProcessor.java:131)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:422)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1579)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
    ... 13 more
**Caused by: java.lang.IllegalArgumentException: localDirectory must not be null**
    at org.springframework.util.Assert.notNull(Assert.java:112)
    at org.springframework.integration.file.remote.synchronizer.AbstractInboundFileSynchronizingMessageSource.afterPropertiesSet(AbstractInboundFileSynchronizingMessageSource.java:132)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1633)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1570)
    ... 28 more

thanks
-Ramesh
Answer: The operation:
ftpInboundFileSynchronizer.synchronizeToLocalDirectory(localDirectory);

isn't for your responsibility.
I'm sure you meant exactly this setter:
FtpInboundFileSynchronizingMessageSource.setLocalDirectory(localDirectory);

In other words your @InboundChannelAdapter should look like this:
@Bean
@InboundChannelAdapter(value = "receiveChannel", poller = @Poller(fixedRate="1000"))
public MessageSource pollFtpForFiles() {
    File localDirectory = new File(sftpProperties.localDirectory);
     System.err.println("LocalDirectory::"+localDirectory.getAbsolutePath()+"::exists::"+localDirectory.isDirectory());
    FtpInboundFileSynchronizer ftpInboundFileSynchronizer = new FtpInboundFileSynchronizer(ftpSessionFactory());
    ftpInboundFileSynchronizer.setRemoteDirectory(sftpProperties.remoteDirectory);
    FtpInboundFileSynchronizingMessageSource messageSource = new FtpInboundFileSynchronizingMessageSource(ftpInboundFileSynchronizer);
    messageSource.setLocalDirectory(localDirectory);
    return messageSource;
}


Using slice() in JavaScript

Question: I have difficulty understanding the use of slice() wrt to the following code, which doesn't fetch me the result I expected.
var cDate = "11-05-2016";
var m = cDate.slice(0,2);
var d = cDate.slice(3,2);
var y = cDate.slice(6);
console.log("Month is " + m);
console.log("Day is " + d);
console.log("Year is " + y);

This gives the following output:
Month is 11
Day is
Year is 2016

I tried to slice with different strings. But every time I do it, it always gives me an empty string when I slice it from the middle of the string. Why is this?
Comment: "endSlice
Optional. The zero-based index at which to end extraction. If omitted, slice() extracts to the end of the string. If negative, it is treated as sourceLength + endSlice where sourceLength is the length of the string (for example, if endSlice is -3 it is treated as sourceLength - 3)."
Comment: 2nd parameter is not the length of slice like it is in `substr`.
Comment: tangentially, I would recommend .split('-') for this sort of thing rather than slice or substr as the numbers are more readable and a little less magical.

`var parts = cDate.split('-'); var m = parts[0]; var d = parts[1]; var y = parts[2];`
Comment: I want the day printed as 05. It returns an empty string
Comment: use `slice` when you know the indices of the characters in the string, use `substr` when you know the length of the substring you want
Comment: @BlakeO'Hare Thank you! This looks more elegant!
Answer: From MDN:

The slice() method extracts a section of a string and returns a new string.

The syntax of slice is:

str.slice(beginSlice[, endSlice])

Note that the endSlice is the actual position in the string (and not how many chars to get from the beginSlice).
In your example - you can't slice a string from position 3 to position 2 (because it goes backwards), so you get an empty string.
Comment: //Note that the endSlice is the actual position in the string (and not how many chars to get from the beginning// Oh Ok. I get it now. Thanks!
Answer: You seem to be confusing slice with substr. The arguments mean different things:

slice( startIndex, endIndex )
substr( startIndex, length )

var cDate = "11-05-2016";
var m = cDate.substr(0,2); // "11"
var d = cDate.substr(3,2); // "05"
var y = cDate.substr(6); // "2016"
console.log("Month is " + m);
console.log("Day is " + d);
console.log("Year is " + y);

Using slice() in JavaScript


What's the most efficient way to add spacing with a specific width to Widgets in a Row()?

Question: I use Expanded() to tell the Widgets in my Row to use the available space. I want to have 4px space between elements in my Row. I don't want to have the same space towards elements outside of the Row. Given that Flutter doesn't support negative Padding I therefore can't add Padding in a way that gives the first item no left Padding and the last item no right Padding.
Is there pattern to easily define spacing with a specific width? I want a solution that works with an arbitrary number of Widgets. For 4 Widgets I want something that produces the equivalent of:
Row(children: [
    Padding(
        padding: const EdgeInsets.fromLTRB(0, 0, 8, 0),
        child: Expanded(Text("Alice"))),
    Padding(
        padding: const EdgeInsets.fromLTRB(8, 0, 8, 0),
        child: Expanded(Text("Alice"))),
    Padding(
        padding: const EdgeInsets.fromLTRB(8, 0, 8, 0),
        child: Expanded(Text("Alice"))),
    Padding(
        padding: const EdgeInsets.fromLTRB(8, 0, 0, 0),
        child: Expanded(Text("Alice")))
]);

Comment: Can you share a code snippet of what you are conveying..that makes it a bit clear and easy to understand..
Comment: @srikanth7785 I added code for 4 Widgets with padding.
Comment: Did you try using `SizedBox`? You can use the `width` property to give space between the elements.
Comment: @Christian:  In your case, Expanded widgets will divide widgets with equal spaces. but I think that should work for you, that row first element will start from left side and remaining widgets will fill the remaining space. but if Expanded not found enough space to render in right side, it will shrink from there
Answer: cant understand what you want to achieve exactly but try
Use SizedBox widget very easy and simple check it here
https://api.flutter.dev/flutter/widgets/SizedBox-class.html
example
  SizedBox(
  width: 200.0,
  height: 300.0,
)

Comment: That leaves open the question of how to best put the SixedBoxes in between the Widgets.
Answer: I usually use this:
Row(
  crossAxisAlignment: CrossAxisAlignment.center,
  mainAxisAlignment: MainAxisAlignment.spaceAround,
  children: [
    Widget(),
    Spacer(),
    Widget(),
    Widget(),
    ],
  ),

Spacer, a widget that takes up space proportional to it's flex
  value. Flutter Row Class
mainAxisAlignment property : How the children should be placed along
  the main axis. Flutter MainAxisAlignment enum

If you want to determine the size, you can use SizedBox(width: double) instead of Spacer ().

SizedBox: A box with a specified size. Flutter SizedBox class


Show a sequence of functions is pointwise but not uniformly convergent

Question:
Let $f:\mathbb{R}\rightarrow\mathbb{R}$ be a bounded function with the properties $f(0)=0$ $\lim_{x\to\infty} f(x)=1$. For each $n\in\mathbb{N}$ define $f_n(x)=f(x+e^n)$ with $(x\in\mathbb{R})$
Show that $(f_n)_{n\in\mathbb{N}}$ is pointwise but not uniformly convergent

So to prove pointwise, I would do the following:
$f_n(x)=f(x+e^n)$ so as $n\rightarrow\infty$ you would have $e^n \rightarrow\infty$ So I am unsure how to prove this? What would the limit function be?
Comment: Please again note it's not a function that is convergent, rather it's a sequence of functions that is.
Answer: For each $x \in \Bbb R$, $\lim_{n \to \infty} x + e^n = \infty$,
and  $\lim_{t\to\infty} f(t)=1$, therefore:
 $$
\lim_{n \to \infty} f_n(x) = \lim_{n \to \infty} f(x + e^n) = 1 \, .$$
 So $(f_n)$
converges pointwise to the function $F(x) = 1$.
To prove that the convergence is not uniform, compute
$f_n(x) - F(x)$ for $x = -e^n$.
Comment: could you explain how that tends to 1? I just cant work out how $f(\infty)$=1
Comment: @LaurenBathers: Because of your condition $\lim_{x\to\infty} f(x)=1$.
Comment: oh i literally completely disregarded that! Thank you!


What is the best approach of clustering if you know number of elements in each cluster?

Question: I want to predict sporting event with knockout system tournament. Data have some features attached to each athlete. I know that there are determined number of results such as:
W(winner) = 1
F = 1
SF = 2
QF = 4
and so on
And I want to predict result for every athlete. I think that clustering is the right way to solve such problem.
Which is the best way of such clustering in Python libraries? I know that some cluster estimators in scikit-learn have argument n_clusters (amount of clusters), but I didn't find any argument that determines number of elements in every cluster.
Edit: add dataframe example structure (including predicted results in column 'y_example'):
    pl  f1  f2      f3      f4  f5  f6  f7  f8         y_example
    0   27  587927  0.498   44  11  0   1   4727329    QF
    1   25  742400  0.588   52  30  9   17  1972378    SF
    2   30  707331  0.44    26  5   2   2   -28808492  F
    3   25  636268  0.434   9   0   0   0   -12889458  QF
    4   28  890370  0.522   34  9   6   6   -18179225  QF
    5   24  710522  0.459   19  4   1   0   -18973768  W
    6   30  817982  0.51    20  3   2   1   -20905065  SF
    7   26  692898  0.499   33  10  0   0   6786944    QF

Comment: can you post an example dataset and explain the structure? The question is not quite clear
Comment: Edited question
Comment: Im not sure if clustering is the way to go here? For doing so you would have to assume, that whith each step in the tourney there is a jump in distance - the distance within one tourney-step must be smaller then between tourney-steps to get this going. But - worst case - in a tourney player A and B could be true gods and C to Z are not skilled at all. So A and B are very similar but chances, that they wont face each other before great final are just 50%.
Comment: You seem to want to predict classes, and not use clustering at all.
Answer: I think we would need more information than what you have provided. Selecting a clustering method depends on many factors:

Size of the data (Unfortunately very large data is difficult to cluster)
Types of variables (continuous? categorical?)
Expected distribution of the clusters

For example:

Hierarchical clustering is very complex for big volumes of data
K-means works good with big volumes of data but the euclidean distance is meaningless for clustering in some cases and it doesn't scale for massive volumes of data
The BF-R algorithm can work well on massive data sets, but it makes works only under the assumption that the clusters are normally distributed across the centroid and the mean and standard deviation for a cluster may differ for different dimensions, but the dimensions must be independent

You can review this presentation to get a basic idea about clustering.
And also check this video for the BF-R algorithm for clustering massive data sets.
Comment: size of data is small - 32 rows, types of variables are all continuous and expected distribution of the clusters actually provided in question: W - 1, F - 1, SF - 2, QF - 4, R16 - 8, R32 - 16.


Integral representation of $|x-a|$

Question: Are there integral representations of the absolute value function $|x-a|$ with $x$, $a$ real numbers?
My initial thought was to write $|x-a| = \sqrt{(x-a)^2}$, and then find an integral representation for $\sqrt{f(x)}$ where $f(x) = (x-a)^2$. But I am not sure if this is the `easiest' way to do it.
Comment: You should tell us the "rules of the game". What is allowed, what is not.
Comment: Do you mean the antiderivative of the sign function ?
Comment: @YvesDaoust Yes, sorry, I posted a new question as my question here is too sloppy. Apologies!
Answer: $$\int_a^x \operatorname{sgn}(t-a)dt$$
where $\operatorname{sgn}(x)$ is the signum function.
Hope it helps:)
Answer: Since $|x - a|$ can be defined piecewise as $a - x$ for $x < a$ and $x - a$ for $x > a$, I think you should also be able to express the integral of the function as $ax - x^{2}/2$ for $x < a$ and $x^{2}/2 - ax$ for $x > a$.
Answer: You have to split it into cases.
If $x-a<0\implies x<a$, then $|x-a|=-(x-a)$:
$$\int|x-a|\,dx=-\int(x-a)\,dx=-\frac{x^2}{2}+ax+C.$$
If $x-a=0\implies x=a$, then $|x-a|=0$:
$$\int|x-a|\,dx=\int 0\,dx=K.$$
If $x-a> 0\implies x> a$, then $|x-a|=x-a$:
$$\int|x-a|\,dx=\int(x-a)\,dx=\frac{x^2}{2}-ax+M.$$
As you can see, the antiderivative is a piecewise-defined function. Moreover, the fact that at $x=a$ the antiderivative is $K$ means that the original function is differentiable there and therefore continuous at that point. This simply means that the curve should not have a gap there So, you just need to find appropriate values for $C$ and $M$ that depend on $K$ to make the curve continuous at $x=a$. You do that by solving these equations for $C$ and $M$ respectively: $-\frac{a^2}{2}+a\cdot a+C=K$ and $\frac{a^2}{2}-a\cdot a+M=K$.
Finally, this is the antiderivative:
$$
f(x)=
\begin{cases}
-\frac{x^2}{2}+ax+K-\frac{a^2}{2},\ x<a\\
K,\ x=a\\
\frac{x^2}{2}-ax+K+\frac{a^2}{2},\ x> a.
\end{cases}
$$
Answer: If $f$ is convex on $[a,b]$, then $$f(x)=\int_a^x f'_+(t)\text{ d}t.$$
The function $f(x)=|x-a|$ is convex.

Integral representation of $|x-a|$


Firefox addon toolbar button disappears after first run

Question: I have a Firefox addon made with the add-on SDK.
https://addons.mozilla.org/es/firefox/addon/board-notes/
To add a toolbar button I use a popular library for the SDK toolbarbutton.js:
https://github.com/erikvold/toolbarbutton-jplib/blob/master/lib/toolbarbutton.js
I only want to add the icon when it first installs and it works, the icon appears but after restarting the browser the icon disappears. The user has to use the right click button to open the setup browser bar and drag the icon again to the bar. Then if he restarts the icon continue correctly in its place.
I want to fix this behaviour because the most part of users probably don't know that they can recover the icon with the setup options.
I've tested some functions to detect if the icon is not in his place to move again, but by doing this if the user hides the icon, when he restarts it will appear again. And this is forbidden by Firefox policies.
I'll appreciate any help, I'm going crazy.
The code I use is this:
 button = createButton(options);

 if (options.loadReason == "install")
 {
    button.moveTo({
       toolbarID: "nav-bar",
       insertbefore: "home-button"
    });
 }

 function createButton(options) {
   return toolbarbutton.ToolbarButton({
     id: "NoteBoard",
     label: "Note Board",
     tooltiptext: "Note Board",
     image: data.url("noteboardMini.png"),
     onCommand: function() {
         openPopup();
     },
     onContext: (function () {
       var installed = false;
       return function (e, menupopup, _menuitem) {
       //Install command event listener
         if (!installed) {
            menupopup.addEventListener("command", function (e) {
               var link = e.originalTarget.value;
               if (link) open(link.replace(/\?.*/ , ""));
            });
            installed = true;
         }
         var temp = (function (arr) {
            arr.forEach(function (item, index) {
               for (var i = index + 1; i < arr.length; i++) {
                  if (arr[i] && item.label == arr[i].label) {delete arr[index]}
               }
            });

         return arr.filter(function (item){return item});
    })(loggedins);
    //remove old items
     while (menupopup.firstChild) {
      menupopup.removeChild(menupopup.firstChild)
     }
     function addChild (label, value) {
      var item = _menuitem.cloneNode(true);
      item.setAttribute("label", label);
      item.setAttribute("value", value);
      menupopup.appendChild(item);
    }
    if (temp.length) {
      temp.forEach(function (obj) {
        addChild(obj.label, obj.link);
      });
    }
    else {
      addChild(_("context"), "");
    }
  }
 })()
 });
}

Comment: I am working on it, I will probably have an answer by tomorrow.
Comment: Does your `onContext` function run? When is this `onContext` supposed to happen?

I have not yet found anything to handle it in the library you linked to.
Comment: @Stephen I don't know what is the onContext function, I copied of another extension I use like an example of the icon bar, I don't see any call.
Answer: You could use the library Toolbar Button Complete, which is my fork of toolbarbutton.js.

Using the library
You can use this library the same way as the original toolbarbutton.js, but it also has more options and features.
In your main.js file:
button = createButton(options);

// On install moves button into the toolbar
if (options.loadReason == "install") {
    button.moveTo({
        toolbarID: "nav-bar",
        insertbefore: "home-button",
        forceMove: true
    });
};

You can find a working example of the library here, but it is a bit out of date.
Installing the Library
If you are using the add-on SDK on your computer:

Download Toolbar Button Complete from github.com.
add it to your packages directory. (Either under your SDK directory or under your add-on's directory.)

If you are using the Add-on Builder to create your add-on:

Click the plus button next to your library folder:

Type in Toolbar Button Complete.
Click on the Add Library button:

Updating the Library
The library is hosted on github.com here.
If you are using the Add-on Builder for your add-on, you can simply click the little refresh button when there is an update available.
Comment: Thank you very very much @Stephen, with this toolbarbutton.js version the icon works correctly. Doesn't dessapear after first run and if the user wants to hide it he can. I've deleted the onContext function, it's not necessary, it works well without it. Now I have to wait the revision, I'm on 250 queue position! Thank you again!
Comment: @Oscardrbcn Sorry I am a bit late to tell you, but I just found out the one area I overlooked before releasing [Toolbar Button Complete](https://builder.addons.mozilla.org/package/166563/). I didn't test it using more than one Firefox window, which it was not able to handle.  I have fixed it now, and you probably want to upgrade to the latest version.
Comment: I didn't have any problem with more than one firefox window but I've upgrade to the last version and submit again. When I upload to the addon library I had a warning about compatibility in the line "const { isPrivate } = require("sdk/private-browsing");". I didn't find anything more about this private const and I've deleted this line to remove the warning. Did I do wrong? Thank you again!
Comment: No that is fine.  That was part of a work in progress anyways, I did not mean to put that in the stable channel.
Comment: @Oscardrbcn You probably want to update your addon (again) with the [latest version](https://builder.addons.mozilla.org/package/166563/). Until this update it would do two things: **1:** It would freeze firefox if you installed it with more than one Firefox window open, and **2:** It caused other addons' toolbar button to disappear. (TileTabs for example.)
Comment: @Stephen works great, thanks for putting in the work for this. Is this hosted on github or anywhere similar so I can follow the source?
Comment: @andrew It isn't currently, just an builder.addons.mozilla.org for now. But I have been planning to put it up on Github for awhile. I will let you know if/when I do!
Comment: @andrew I now have it [hosted on github](https://github.com/Geek-in-Training/Toolbar-Button-Complete-jplib/)!


How can I either through vbscript or GPO push a Windows 7 Logon Screen to all my users

Question: I know how to change the login screen, it's easy. But I would like to figure out a way to do it through GPO or login script. I have tried running the script as the computer start-up script as well as the users login script(GPO) But the users do not have admin rights and the require UAC to replace the backgroundDefault.jpg. Turning UAC off is not an option.
Any idea's
Answer: You could simply copy the file to all your machines from an administrator logon. That's more or less what I did. I just did it one at a time, but you could put that in a batch file.
Comment: This is all we did. Make a GPO to do this in the machine context, not a user's context. Job done.
Comment: RobM are talking about running a script via GPO from the Computer side versus the user side? ie the startup vs login script? Cause I tried that and it didn't work for me..
Comment: ETL - that was what I was thinking as well just using a for loop to circulate through the subnet. I just though is was little inelegant, however effective. I was hoping to just automate through GPO. But I think at this point you have a the top answer. Thanks!


What is the name of this problem? linear Matrix equation optimization?!

Question: I have almost no knowledge in linear algebra but I need to understand the process of solving a problem. In fact I'm looking for some keywords or hints to know what exactly should I be Googling! So any help is appreciated in advance.
The problem is very simple I suppose:
I have a scalar ${D}$ which is calculated by the following l2 norm matrix equation:
$D=||A_{m \times m}X_{m \times 1}+B_{m \times 1}||_2$
I want to optimize $D$ by finding the best $X$ that minimizes it.
i.e.:
$X^*=argmin_XD$
Unfortunately I don't remember the name of this problem so I am not able to find a proper lesson on the YouTube. Anyone can help me?
Comment: If $A$ is invertible then $X^\ast=A^{-1}(-B)$ is the unique minimization argument and you get $D=0$. If $A$ is not invertible then you might try to find out the null space of $A$ in order to partially invert $A$, but then you'll have a whole vector subespace of $\mathbb{R}^m$ as solutions of $X^\ast$. Hope this helps :)
Answer: If $A$ is invertible, then see the @Jonh 's comment.
If $A$ is not invertible, then $(1):$ $im(A^TA)=im(A^T)$. Let $f:x\rightarrow ||Ax+b||^2$. If $f$ admits an extremum in $x$, then its gradient in $x$ is $0$, that is $A^T(Ax+b)=0$ or $(2):$ $(A^TA)x=A^T(-b)$. According to $(1)$, such an $x$ exists; if $x_0$ is a particular solution of $(2)$, then the set of all the solutions is $x_0+y$ where $y\in\ker(A)=\ker(A^TA)$. Note that $f(x_0+y)=f(x_0)$ is a fixed real -which is the required minimum of $f$-.
Conclusion. A value of $x_0$ is $x_0=-(A^TA)^+A^Tb$ where $Z^+$ is the Moore-Penrose pseudoinverse of $Z$. cf. https://en.wikipedia.org/wiki/Moore%E2%80%93Penrose_pseudoinverse


What is the probability of no events in a Markov-modulated Poisson process?

Question: Suppose I have a two-state continuous-time Markov chain $M$ with rate matrix $Q$.
$$ Q = \begin{bmatrix} -q_{01} & q_{01} \\ q_{10} & -q_{10} \end{bmatrix} $$
Now consider a Poisson process $P$ whose rate is $\lambda_0$ when $M$ is in state 0, and $\lambda_1$ when $M$ is in state 1. Then $P$ is a Markov-modulated Poisson process. I want to calculate the probability that no events have occurred in $P$ by time $t$.
Here's my reasoning so far. Suppose that $M$ always starts in state 0. Let $P_0(t)$ and $P_1(t)$ be the probabilities that $M$ is in state 0 and 1, respectively, at time $t$. Then the expected rate of $P$ at time $t$ is
$$ \lambda_0 P_0(t) + \lambda_1 P_1(t).$$
It follows that the probability of no events occurring before time $t$ is
$$ \exp\left[ -\int_{s=0}^t (\lambda_0 P_0(s) + \lambda_1 P_1(s)) \, ds\right]. $$
However I am uncertain if it makes sense to use the expected rate this way, to get at the probability of no events occurring. I would like to know if this makes sense, and if not, where did I go wrong?
Answer: I found the result I needed in "Fischer, Wolfgang, and Kathleen Meier-Hellstern. "The Markov-modulated Poisson process (MMPP) cookbook." Performance evaluation 18.2 (1993): 149-171.".
Let $P_{ij}(n, t)$ be the probability that, at time $t$, $n$ arrivals have occurred and the chain is in state $j$, given that the chain began in state $i$ at time 0. Then the matrix $P(n, t)$ satisfies the differential equation
$$ P'(n, t) = P(n, t) (Q - \Lambda) + P(n-1, t) \Lambda, \quad P(0, 0) = I,$$
where $Q$ is the transition matrix of the Markov chain and $\Lambda = \text{diag}(\lambda_1, \ldots, \lambda_n)$ is the diagonal matrix of the arrival rates. In particular, the row sums of $P(0, t)$ are the probabilities that no arrivals have occurred by time $t$.


Spivak Calculus- Chapter 11, question 25.

Question: I'm working through the Spivak Calculus book, and am having some difficulty with the following problem. Assume that $f$ is a second differentiable function, $f(0) = 0$, $f(1) = 1$, and $f'(0) = f'(1) = 0$. Prove that $\exists c\in [0,1]$ such that $|f''(c)|\geq 4$. The hint that the text provides is prove that either $f''(x) > 4$ for some $x\in [0, \frac{1}{2}]$ or $f''(x) < -4$ for some $x\in [\frac{1}{2}, 1]$.
Using the Mean Value theorem, it's easy enough to prove that that $\exists c_1\in (0,1)$ and $f'(c_1) = \frac{f(1) - f(0)}{1-0} = 1$.
From here, you can apply MVT to $f'$ on $[0,c_1]$ and $[c_1, 1]$ giving
$\exists c_2\in (0,c_1)$ where $f''(c_2) = \frac{1}{c_1}$
and
$\exists c_3\in (c_1, 1)$ where $f''(c_3) = \frac{-1}{1-c_1}$.
From here, using the assumption that $c_1 \leq \frac{1}{4}$ yields $f''(c_2) \geq 4$ or $c_1 \geq \frac{3}{4}$ yields $f''(c_3) \leq -4$.
However, I am unsure of what to do if $\frac{1}{4} < c_1 < \frac{3}{4}$. I have been told that Cauchy's Mean Value Theorem (sometimes called the Generalized Mean Value Theorem) is the way to go concerning this problem, but I'm unable to make it work. Any thoughts would be greatly appreciated.
Comment: I edited my answer below to include a proof using CMVT.
Comment: This is appearing too frequently and there is a list of duplicates already available.
Answer: You're right, Cauchy's MVT is a nice way to go: There exists $a\in (0,1)$ such that $f(a) = 1/2.$ Apply CMVT twice to see
$$\frac{1}{2a^2}=\frac{f(a)}{a^2} = \frac{f(a)-f(0)}{a^2-0^2} = \frac{f'(c)}{2c} = \frac{f'(c)-f'(0)}{2c-2\cdot 0}=\frac{f''(d)}{2}. $$
This implies $|f''(d)| \ge 1/a^2.$ A similar argument, using $f(1) = 1, f'(1) = 0,$ gives $d'$ such that $|f''(d')| \ge 1/(1-a)^2.$
Now one of $1/a^2, 1/(1-a)^2$ has to be at least $4,$ giving the desired result.

Previous answer: There exists $a\in (0,1)$ such that $f(a) = 1/2.$ Suppose $a\in (0,1/2].$ Then by Taylor,
$$ \frac{1}{2} = f(a) = f(0)+f'(0)\cdot a + f''(c)\frac{a^2}{2}=f''(c)\frac{a^2}{2}$$
for some $c\in (0,a).$ Thus $f''(c) = 1/a^2.$ Since $a^2\le 1/4,$ we see $f''(c)\ge 4.$ A similar proof works if $a\in [1/2,1).$
Answer: Assume that $f''(x)< 4$, for all $x\le 1/2$. Then
$$
f'(x)=f'(0)+\int_0^x f''(t)\,dt< 4x,
$$
and
$$
f(x)=f(0)+\int_0^x f'(t)\,dt< 2x^2\le\frac{1}{2}
$$
which implies that
$$
f\left(\frac{1}{2}\right)<\frac{1}{2} \tag{1}
$$
If $f''(x)>-4$, for all $x\ge 1/2$, then
$$
0=f'(1)=f'(x)+\int_x^1 f''(t)\,dt> f'(x)-4(1-x),
$$
and thus
$$
-f'(x)>-4(1-x)
$$
which implies that
$$
f(x)-f(1)=-\int_x^1f'(t)\,dt>-4\int_x^1(1-t)\,dt=-2(1-x)^2,
$$
and hence
$$
f(x)>1-2(1-x)^2,
$$
which implies that
$$
f\left(\frac{1}{2}\right)>\frac{1}{2} \tag{2}
$$
Observe that $(1)$ contradicts $(2)$.
Comment: We aren't assuming $f\in C^2[0,1],$ just that $f$ is twice differentiable on $[0,1].$ So it's possible $f''$ is not Riemann integrable.
Comment: Your solution is very elegant, but I don't think that this is the solution that was envisioned as integrals do not appear in the text until 2 chapters after the problem is stated. Is there a way to do the problem using MVT or GMVT?


Disproof of an attempted disproof of the pythagorean theorem because of recursively defined path

Question: Here is a video that attempts to state that the Pythagorean theorem is wrong:
https://www.youtube.com/watch?v=-rRaAgjU5kw
I know he must be making an incorrect assumption but I have gotten a lot of contesting reasons from other forums. So could someone provide a clear answer as to what is wrong with this?
Comment: The taxicab geometry distance run in Manhattan streets never equals the direct distance as the crow flies.   https://en.wikipedia.org/wiki/Taxicab_geometry
Answer: These curves used to be called pathological curves, now they are called fractal curves.
As you go to infinity, the stairwell curve never actually becomes a straight line, that is, it never becomes smooth. Because it's not really a straight line, the pythagorean theorem does not apply. The actual definition of smooth requires calculus and is complicated. There are even different degrees of smoothness.
Fractal curves are not smooth at all. They might look smooth, but that is a problem with the way our eyes and brains work and the actual practical matters involved in the way we graph functions.
Let't take a more technical look at this stair curve approximation to the diagonal. We need to show why, even after an infinite number of iterations, the resulting curve is not a straight line.

Just to make this discussion easier, let's assume that we have put a ruler against the diagonal so that the coordinate of the first point is $0_2 = \dfrac 01$ and the coordinate of the last point is $0.1_2 = \dfrac 12$.
The image above shows the first four iterations of the stair curve. The points that make of the stair curve are counted in base two from $0.0_2$ to $0.1_2$ (the radix is not shown) in increments of $2^{-n}$.
This implies that, even when we go to infinity, the number of points of the stair curve that are actually on the diagonal will be countable. Hence, even when we go to infinity, the stair curve will be different from the diagonal.
$$ \lim_{n \to \infty} S_n \ne \overline{A_0A_{\frac 12}} $$
Comment: But the fallacy can be presented with arbitrarily smooth curves, so I don't think focusing on "fractal curves" and lack of smoothness is going to give the best insight.
Comment: I apologise for not presenting this is the correct format earlier. I was trying to disprove it on my own and ask for a critique on it. I seemed to have gotten what I was looking for, at the cost of every point that I've earned (not much), but I'm happy I have a solid reason now. Much thanks to @StevenGregory for providing such a well made answer.
Comment: Thank you. I had someone with higher credentials than I claim that it was not a fractal so I tried another approach. This was my original answer so I'm feeling a little vindicated ^___^
Comment: Of course we know the many traditional proofs are correct but I think this is interesting. A just for fun kind of thing.
Comment: @hardmath The definition of the arc length generally requires smoothness. The limit of the stairwell curve is nowhere differentiable. To tell you the truth. Insight wasn't what I was attempting to do here.
Comment: You could smooth it out, but then the method would be replaced by one that flattens the waves in between and the sequence of wavy curves would converge to a straight line and be of the same distance as the hypotenuse.
Comment: If you used waves it would be a Taylor series and the length would contract to the hypotenuse correct? The lack of smoothness is what causes the degeneracy.
Comment: Archimedes approximated the circumference of a circle with a polygon, e.g. a less smooth curve.  In any case I again point out that without the Pythagorean Theorem to build on, we get nowhere with lengths of smooth curves.
Comment: @hardmath -  On the contrary, the limit of the polygon is a smooth curve.
Comment: @hardmath Yes, a sum of the lengths of infinitesimal hypotenuses (hypotenii?) is needed to compute arc length. And that can only be done on smooth curves.
Comment: @JeffreyColeman - I first saw this when I was in high school and was terribly upset by it. This is a very big thing, if not resolved, then the (elementary calculus) definition of arc length is meaningless. It took me a lot of work to come to terms with why it doesn't work.


Is it possible to use a block tag ({% block %}) from base html template two or more times in derived html file in Django

Question: I want to be able to reuse the same block tag multiple times in derived html.
something like:
base.html

    {% block panel %}
         # some basic panel structure inside this block
    {% endblock %}

derived.html
{% extends base.html %}

--first panel

    {% block panel %}
        # override things like panel header
    {% endblock %}

--second panel

    {% block panel %}
        # again override some panel stuff from base template
    {% endblock %}

Is there anyway i can achieve this in Django?
Answer: No, it will result in template syntax error. The best you can do is to include as many block tags as you require in base and reuse them. Or you can even loop the blocks in base.
I haven't tested it out, but theoretically it should work. In your base, create a loop block, in below example it creates 6 blocks, block content1.....  content6
{% for i in '123456' %}

{% block content{{i}} %}

Foo

{% endblock content{{i}} %}
{% endfor %}

Answer: No, you can not. The best way to do it is, assign each block for each panel or if you have multipanel then run the loop for the block.
In your current case (i assuming two panel in single derived file) it would be like this-
base.html

    {% block content %}

    {% endblock %}

derived.html
{% extends "base.html" %}

{% block content %}

{% endblock %}

The block is just for reducing the redundant work which unique to each extended file. so you can only referred it to single time in any extended file.


get_called_class ou de new static?

Question: Eu não lembro qual foi a biblioteca em PHP que vi isso, mas lá existia um trecho de código onde, para se obter uma nova instância da classe atual, era usado a função get_called_class.
Porém o PHP tem a palavra chave static, que se refere ao late static binding.
Parece que o uso dos dois produz o mesmo resultado.
Veja:
class Yea
{
    public static function withStatic()
    {
        return new static;
    }

    public static function withCalledClass()
    {
        $class = get_called_class();
        return new $class;
    }
}

var_dump(Yea::withStatic());
var_dump(Yea::withCalledClass());

Já que a saída é a mesma, por que alguns preferem usar get_called_class, ao invés do static?
IDEONE
Comment: Seria pelo fato de `get_called_class` estar disponível do php5.3 para frente? testa esse código no https://3v4l.org/ ele vai rodar em várias versões do php. +1
Comment: PHP 5.3 funfou https://3v4l.org/rmmvc
Comment: E no 5.2 pra baixo? deu erro ou deu outro resultado? não tenho acesso ...
Comment: Não mostrou nenhum resultado.
Answer: A função get_called_class() retorna o nome da classe, enquanto static retorna a própria classe.
A partir do PHP 5.5, você também pode usar static::class para retornar o nome da classe.
Acredito que seja mais uma questão de estilo, mas eu recomendaria usar o static (principalmente se o seu objetivo é instanciar a classe, como no seu exemplo), por duas razões:

1)  É mais Curto, seu código fica mais limpo;
2)  Performance. Apesar de quase imperceptível, qualquer chamada de função tem custos.

Você pode fazer uma comparação simples, assim:
class Foo {
    public static function bar()
    {
        echo "\n get_called_class: ";
        $time = microtime(true);
        echo get_called_class(). ' ';
        printf('%f', microtime(true) - $time);

        echo "\n static: ";
        $time = microtime(true);
        echo static::class . ' ';
        printf('%f', microtime(true) - $time);
    }
}

echo "
";
Foo::bar();

Resultado:

get_called_class: Bar 0.000006
static: Bar 0.000001

Esses tempos podem variar um pouco em cada page load.
Comment: Gostei da sua resposta. Mas sabe se a questão da versão pode influenciar na hora de um framework utilizar `get_called_class` ou `static`?
Comment: Os frameworks costumam definir uma versão mínima. Geralmente essa informação fica logo na primeira página da documentação, ou na seção "Instalação". Resumindo, a versão influencia sim. Se você estiver desenvolvendo um Framework seu, então tem que escolher se quer dar suporte apenas às versões mais modernas, ou manter compatibilidade com as versões anteriores.
Comment: Sempre determino PHP 5.4 ++
Comment: Provavelmente, essa lib que vc viu queria pegar o nome da classe em versões anteriores à 5.5. Existem outras opções para fazer isso também, como a variável `__CLASS__` ou `get_class($this)` (se o método não for estático)
Answer: Vale ressaltar que a função get_called_class veio a existir a partir da versão 5.3 do PHP.
Além da diferença de performances como citadas pelo Rafael

class Foo {
    public static function bar()
    {
        echo "\n get_called_class: ";
        $time = microtime(true);
        echo get_called_class(). ' ';
        printf('%f', microtime(true) - $time);

        echo "\n static: ";
        $time = microtime(true);
        echo static::class . ' ';
        printf('%f', microtime(true) - $time);
    }
}

echo "
";
Foo::bar();

Resultado:
get_called_class: Bar 0.000006

static: Bar 0.000001

Existe uma outra questão que deve ser levantada.
O get_called_class é usado em parceria com o late static binding em frameworks.
Por exemplo, quando um framework busca utilizar um sistema de service locator/IoC, costumam utilizar o get_called_class, pois como essa função retorna o nome da classe e isso pode ser utilizado para verificar se já existem instâncias juntos com a utilização do FactoryPattern
Exemplo
class Factory
{
    private static $_instances = array();

    public static function getInstance()
    {
        $class = get_called_class();
        if (!isset(self::$_instances[$class])) {
            self::$_instances[$class] = new $class();
        }
        return self::$_instances[$class];
    }
}

class ClassExtendFactory extends Factory {}

$class = ClassExtendFactory::getInstance();
$otherClass = ClassExtendFactory::getInstance();
var_dump($class === $otherClass);
// result true { ou seja, representam o mesmo objeto, duas variáveis apontando para o mesmo endereço de alocamento da memória }

Quando não utilizam a factory, somente usam o late static binding
abstract class AbstractExample {
    public static function getInstance() {
        return new static();
    }
}

class Example extends AbstractExample {

}

$ex1 = Example::getInstance();
$ex2 = Example::getInstance();
var_dump($ex1 === $ex2);
// return false { ou seja, agora são 2 instâncias diferentes da mesma class, duas variáveis apontando para espaços diferentes de alocamento na memória }

É isso, espero que tenha ajudado a entender um pouco melhor.

get_called_class ou de new static?


How do I start a new line in

Question: Here is my code:
<textarea name='awesome'><?php
                                    if(session::exists('home')) {
                                        echo Session::flash('home') . '       ';
                                    }
                                    if($user->hasPermission('admin')) {
                                        echo 'You are an administrator!';
                                    }
                                    if(isset($_SESSION['bodycontentmessage'])){
                                        echo $_SESSION['bodycontentmessage'];
                                    }
                                    $_SESSION['bodycontentmessage'] = "";
                                  ?></textarea>

How do I make it so that each if statement variable produces a new line within this textarea?
For example if I ran it like it is now, it would output inside the textarea:
You are an administrator!Successfully logged in!
However I want it to say:
You are an administrator!
Successfully logged in!
Any idea how?
Answer:

$('textarea').html('Hello'+"\r\n"+'There');
textarea{width:100%;height:100px;}

<textarea></textarea>

In your PHP, do the same thing:

echo 'You are ' ."\r\n". 'an administrator!';

Note that if you later post the data into a back-end database, you might need to programmatically search/replace the \r\n with
 before inserting into the DB, so that future rendering will render correctly.
Also note the use of double-quotes around the \r\n. Sometimes this matters.
Comment: how would I implement this into my code? p.s ive never used javascript before
Comment: where do I insert this: $('textarea').html('Hello'+"\r\n"+'There');
textarea{width:100%;height:100px;}
Comment: You don't -- that was to demonstrate how it works. Not possible to demo PHP in an SO demo. However, I re-code it below with PHP -- just do the PHP part.  `echo "Hello" ."\r\n". " there"`
Answer: In html, use
\n
or \r\n.
For example,
<textarea>Hello,\r\nWorld!</textarea>

In some frameworks like php or jsp,
you can replace \r\n with your own markup
and replace it with \r\n again using script.
Usually I use @br@ in jsp,
replace it with \r\n again in html.
So it flows like below
textarea:Hello,\r\nWorld! -> request to server
-> jsp:"Hello,\r\nWorld!".replaceAll( "\\r", "" ).replaceAll( "\\n", "@br@" );
-> do something

jsp:"Hello,@br@World!" -> response to client
-> js:"Hello,@br@World!".replace( /@br@/g, "\r\n" );
-> textarea:Hello,\r\nWorld!

Try it.
If it doesn't work,
let me know.

Edit
I don't know your whole html code but it may seem like below

        <textarea name="awesome">Hello,\r\nWorld!</textarea>

With that script part, text in textarea will be chaned as you want.
Without it, it just Hello,\r\nWorld!.
Comment: then it just says "Hello,\r\nWorld!" in the textarea?
Comment: It is Just an example.  You should use script to replace it.
Comment: where do I copy this into? ive never used javascript before
Answer: Ensure that your textarea has the right CSS.
textarea {
    white-space:pre;
}

Then split your php into multiple lines with a newline character between after each if statement.
<textarea name='awesome'><?php
    if(session::exists('home')) {
        echo Session::flash('home')."\n";
    }
    if($user->hasPermission('admin')) {
        echo "You are an administrator!\n";
    }
    if(isset($_SESSION['bodycontentmessage'])){
        echo $_SESSION['bodycontentmessage']."\n";
    }
    $_SESSION['bodycontentmessage'] = "";
?></textarea>

Comment: doesnt work, just shows: You are an administrator!\n\n
Comment: Looks like it might be a PHP quirk, try changing the single quotes to double quotes: http://php.net/manual/en/language.types.string.php#language.types.string.syntax.double
Answer: Like this:
<textarea name='awesome'>
<?php
    if(session::exists('home')) {
        echo Session::flash('home') . '       ';
    }
    if($user->hasPermission('admin')) {
        echo 'You are an administrator!' ."\r\n";
    }
    if(isset($_SESSION['bodycontentmessage'])){
        echo $_SESSION['bodycontentmessage'] ."\r\n";
    }
    $_SESSION['bodycontentmessage'] = "" ."\r\n";
?>
</textarea>

How do I start a new line in