Qual a diferença entre usar FileInputStream e FileOutputStream ou Scanner e PrintStream?

Question: Há alguma grande diferença entre usar essas classes?
Answer: Entrada e Saída em Java
Para entender melhor como funcionam essas classes você deve entender um pouco sobre a API de E/S do Java do pacote java.io.
Streams
O básico da API inclui as classes abstratas InputStream e OutputStream que definem a forma como, respectivamente, você lê e grava sequências bytes sem se importar com a fonte ou destino dos dados.
Note que essas classes estabelecem um acesso relativamente de baixo nível, pois trabalham apenas bom bytes.
File Streams
Estendendo as classes básicas, existem diferentes implementações mais específicas, sendo FileInputStream e FileOuputStream exemplos que trabalham especificamente com streams de bytes em arquivos.
Buffered streams
Ler ou gravar byte a byte não é eficiente, afinal a maioria dos discos e memórias são otimizados para trabalhar com blocos de dados.
Para isso, existem classes como BufferedInputStream e BufferedOutputStream que utilizam o padrão de projetos decorator para "decorar" um stream e automaticamente gerenciar a leitura e escrita em blocos através de um buffer interno.
Isso significa que, numa leitura, a classe vai ler n bytes de uma só vez para o buffer (sendo n o tamanho do buffer) mesmo que você efetivamente leia um a um na sua classe. Quando o buffer for lido completamente, a classe dispara a leitura do próximo bloco de n bytes.
O mesmo vale para gravação. Mesmo que você grave um byte por vez, a implementação bufferizada só vai disparar a gravação no disco depois que tiver uma quantidade suficiente de caracteres para encher o buffer.
PrintStream
A classe PrintStream também é uma subclasse de OutputStream, assim como FileOutputStream.
Ela também permite você decorar qualquer OutputStream e lhe dá acesso a vários métodos de mais alto nível. Esse padrão é muito importante para entender essa API.
Então, se você tiver um OuputStream qualquer, tal como um FileOutputStream, você pode passar esse objeto no construtor do PrintStream. Quando você chamar um método de PrintStream, por exemplo algum que escreve uma linha formatada de texto, você estará indiretamente gravando bytes no seu OutputStream original, mas de forma mais simplificada.
O que confunde um pouco é que PrintStream também aceita um arquivo File em seu construtor. Porém, note que isso é apenas um facilitador. Se olhar a implementação, vai ver que ele apenas cria um FileOutputStream.
Scanner
Já a classe Scanner é um animal diferente. Ela não faz parte do pacote java.io.
Scanner é uma classe utilitária para interpretar dados simples (primitivos) e delimitados em uma sequência de caracteres. Esses caracteres podem ser lidos de várias fontes, sendo uma delas sequências de bytes, mas pode ser uma simples String.
Não pare por aqui
Existem muitas outras classes na API de Entrada e Saída do Java. Cada uma delas tem um propósito e é importante conhecer algumas delas para tirar o proveito máximo da linguagem.
Além disso, para implementações ainda mais consistentes em com desempenho melhor, considere a API NIO (New Input/Output), que é a forma mais nova e recomendada de acesso a arquivos no Java. Veja a documentação oficial aqui.
Answer: Sim,

FileInputStream e FileOutputStream: como os nomes sugerem, são para tratar de arquivos, o primeiro possui métodos para ler um arquivo e o segundo possui métodos para escrever.
Scanner e PrintStream: são mais genéricos, podem ser usados em outros streams(não apenas arquivos), o Scanner normalmente é usado para facilitar a entrada de dados do console/terminal:

Scanner input = new Scanner(System.in);
input.nextLine();


Como chamar um Interstitial clicando em um item da lista que passa por um Adapter?

Question: Preciso chamar um Interstitial nesta Activity clicando em um item da lista que vem do meu Adapter:
public class ListOfTemplates extends AppCompatActivity {
    private Template template;
    private ViewHolder view;

    private InterstitialAd mInterstitialAd;

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

        final RecyclerView rclTemplates = findViewById(R.id.rclTemplates);
        final TextView txtNome = findViewById(R.id.txtNome);
        final Button btn = findViewById(R.id.btnAdmod);

        MobileAds.initialize(this, "ca-app-pub-3940256099942544~3347511713");

        //Toast.makeText(getApplicationContext(), "Desliguei", Toast.LENGTH_LONG).show();
        mInterstitialAd = new InterstitialAd(this);
        mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
        LoadInterstitial();

        mInterstitialAd.setAdListener(new AdListener() {
            @Override
            public void onAdClosed() {
                LoadInterstitial();
            }
        });

        rclTemplates.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mInterstitialAd.isLoaded()) {
                    mInterstitialAd.show();
                } else {
                    Log.d("TAG", "The interstitial wasn't loaded yet.");
                }
                //mInterstitialAd.show();
            }
        });

        if (ListaTemplates.getTamanhoListaTemplates() > 0){
            ListaTemplates.getListaTemplates().clear();
        }

        TemplateDAO dao = new TemplateDAO(getApplicationContext());
        dao.selectTemplates();

        ListaTemplates.carregarTemplates();

        Adapter tempAdapter = new Adapter(ListaTemplates.getListaTemplates(), getApplicationContext());

        rclTemplates.setAdapter(tempAdapter);

        RecyclerView.LayoutManager meuLayout = new LinearLayoutManager(
                getApplicationContext(),
                LinearLayoutManager.VERTICAL,
                false
        );

        rclTemplates.setLayoutManager(meuLayout);

    }

    private void LoadInterstitial(){
        //mInterstitialAd.loadAd(new AdRequest.Builder().build());
        AdRequest interAdRequest = new AdRequest.Builder().build();
        mInterstitialAd.loadAd(interAdRequest);
        Toast.makeText(getApplicationContext(), "Estou aqui", Toast.LENGTH_LONG).show();
    }

}

Meu Adapter:
public class Adapter extends RecyclerView.Adapter {

    private ArrayList<Template> listaTemplates;
    private Context context;

    public Adapter(ArrayList<Template> listaTemplates, Context context) {
        this.listaTemplates = listaTemplates;
        this.context = context;
    }
    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(context).inflate(R.layout.minha_celula, parent, false);

        //
        RecyclerView.ViewHolder holder = new ViewHolder(view);
        return  holder;
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, final int position) {

        final ViewHolder holderArm = (ViewHolder)holder;

        holderArm.txtNome.setText(listaTemplates.get(position).getNome());

        if (ListaTemplates.getTemplate(position).getPhoto().equals("classic")){
            holderArm.imgCelula.setImageResource(R.drawable.on);
        }else if (ListaTemplates.getTemplate(position).getPhoto().equals("spark"){
            holderArm.imgCelula.setImageResource(R.drawable.power_on2);
        }
        final String nome = holderArm.txtNome.getText().toString();
        holderArm.txtNome.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(context, MainActivity.class);
                intent.putExtra("index", position);
                intent.putExtra("nome", nome);

                Bundle bundle = new Bundle();
                intent.putExtra("keyNome", nome);
                intent.putExtra("keyNome", nome);

                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);

            }
        });

    }

    @Override
    public int getItemCount() {
        return listaTemplates.size();
    }
}

Answer: Eu fiquei dias tentando implementar este Interstitial (pode parecer simples, mas sou iniciante em Desenvolvimento Android), então resolvi pedir ajuda aqui, mas é incrível, só foi eu postar a dúvida, minutos depois eu consegui a solução esperada. Vou deixar a resolução aqui caso alguém tenha essa dúvida um dia.
public class Adapter extends RecyclerView.Adapter {

    private ArrayList<Template> listaTemplates;
    private Context context;
    private InterstitialAd mInterstitialAd;

    public Adapter(ArrayList<Template> listaTemplates, Context context) {
        this.listaTemplates = listaTemplates;
        this.context = context;
    }
    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(context).inflate(R.layout.minha_celula, parent, false);

        RecyclerView.ViewHolder holder = new ViewHolder(view);
        return  holder;
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, final int position) {

        final ViewHolder holderArm = (ViewHolder)holder;

        holderArm.txtNome.setText(listaTemplates.get(position).getNome());

        if (ListaTemplates.getTemplate(position).getPhoto().equals("classic")){
            holderArm.imgCelula.setImageResource(R.drawable.on);
        }else if (ListaTemplates.getTemplate(position).getPhoto().equals("spark")){
            holderArm.imgCelula.setImageResource(R.drawable.power_on2);
        }
        //holderArm.txtNome.setText("Ver Detalhes");
        final String nome = holderArm.txtNome.getText().toString();
        holderArm.txtNome.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Posição na lisa e não no Banco de Dados
                Intent intent = new Intent(context, MainActivity.class);
                intent.putExtra("index", position);
                intent.putExtra("nome", nome);

                //Toast.makeText(context, "Nome printado: " + nome, Toast.LENGTH_SHORT).show();

                Bundle bundle = new Bundle();
                intent.putExtra("keyNome", nome);
                //bundle.putString("keyNome", nome);
                intent.putExtra("keyNome", nome);

                //intent.putExtra("nome", holderArm.txtNome);
                //holderArm.txtNome.toString();

                /** Código da resolução
                    Toda vez que selecionar um item da lista que passar pelo Adapter será chamado um Interstitial
                **/
                AdRequest adRequest = new AdRequest.Builder().build();
                mInterstitialAd = new InterstitialAd(context);
                mInterstitialAd.setAdUnitId("ca-app-pub-1714562797049244/5381799713");
                mInterstitialAd.loadAd(adRequest);
                mInterstitialAd.setAdListener(new AdListener() {
                    @Override
                    public void onAdLoaded() {
                        displayInterstirial();
                    }
                });

                //Resolvendo o problema de "Calling startActivity() from outside of an Activity"
                //intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);

            }
        });
    }

    private void displayInterstirial(){
        if (mInterstitialAd.isLoaded()){
            mInterstitialAd.show();
        }
    }

    @Override
    public int getItemCount() {
        return listaTemplates.size();
    }
}


animação sai do lugar quando eu diminuo o zoom

Question: bom dia, sou um programador iniciante, estava fazendo uma animação em css do sistema solar com divs, o problema é que nem todos os elementos cabem no mesmo espaço quando o zoom está normal então quando eu diminuo o zoom, eles sai do lugar (menos o sol que nao é animado). Tentei usar o display flex, mas quando faço isso a animação para
vou postar o código css do mercúrio e do sol, porque os outros são bem parecidos com ele
#mercurio {
width: 10px;
height: 10px;
border-radius: 50%;
background-color:white;
position:absolute;
left: 660px;
top: 300px;

animation-name: mercurio;
animation-duration: 1s;
animation-timing-function: linear;
animation-iteration-count: infinite;

}
 #sol{
  background-color: yellow;
  width: 100px;
  height: 100px;
  border-radius: 50%;
  position:relative;
  margin-left: auto;
  margin-right: auto;
  top:250px;
  text-decoration-color: white;

agora o html
<!DOCTYPE html>

    Sistema Solar

Comment: Cara coloca o html, de forma que pelo menos de para simular o seu problema ;)
Comment: perdao hugo, sou novo no site assim como programador não sei muito bem como usar, agora está dando para executar o código?
Answer: No HTML:

No CSS:
#mercurio {
    position:absolute;
    top: 50px;
    width: 10px;
    height: 10px;
    border-radius: 50%;

    background-color:rgb(190, 39, 39);

    animation-name: mercurio;
    animation-duration: 1s;
    animation-timing-function: linear;
    animation-iteration-count: infinite;
}

#sol{
    position: relative;
    top:250px;
    background-color: yellow;
    width: 100px;
    height: 100px;
    border-radius: 50%;
    margin-left: auto;
    margin-right: auto;
    text-decoration-color: white;
}
@keyframes mercurio{
    from{
        left:0px;
    }
    to{
        left: 100px;
    }
}

Vou explicar como funciona o position: absolute.
O position: absolute, faz com que a tag com esse atributo fique "presa" dentro da primeira tag positon: relative que ela esteja dentro.
Então do seu jeito ele fez o seguinte: a tag mercurio é filha mais proxima de qual tag com position Relative? o body? então ele verifica e vê que não, o body é position: static,então ele ve a tag HTML, e vê se é position relative então ele vê que tambem não, então já que não tem nenhuma tag acima, ele fica "preso" dentro do começo do site, se você desse top:0px ele iria para o topo do site.
Então quando diminuir ou aumentar o zoom, modificar o tamanho de tudo, tambem dos pixels, então do jeito que ele tava, o sol aumentava o tamanho/diminuia, e os pixels dele tambem, e a diferença entre o topo da pagina e o sol tambem mudava, fazendo que a tag do mercurio se movesse.
Na minha edição eu botei a div do mercurio (e dos outros planetas) dentro da div "Sol", assim ao colocar top:0px ele vai no começo da div sol.
então quando dar zoom, ele vai continuar X pixel da div SOL e não X pixels do top da pagina.
É meio complicado de explicar, mas espero que tenha entendido :)


Understanding chain probability notation?

Question: I'm going over markov models and I'm tying to understand the following notation for chain probability:
$$p(a_1, a_2, a_3, a_4) = p(a_1)p(a_2\mid a_1)p(a_3\mid a_1,a_2)p(a_4\mid a_1,a_2,a_3)$$

"The Chain Rule is one simple consequence of the definition of conditional probability: the joint probability of some set of events $a_1, a_2, a_3, a_4$ can also be expressed as a 'chain' of conditional probabilities"

Can someone explain?
Comment: Unrelated to the Markov property, always true, simply iterates Bayes formula $$p(a,b)=p(a)p(b\mid a)$$ for various $a$ and $b$.
Answer: By definition of conditional probability, we have $P(A,B) = P(A\mid B)P(B)$, where $P(A,B)$ means $P(A\cap B)$.
Now taking $A=a_4$ and $B = (a_1,a_2,a_3)$, we get:
$$P(a_4,a_3,a_2,a_1) = P(a_4\mid a_1, a_2, a_3)P(a_1,a_2,a_3)$$
Now with $A = a_3$ and $B=(a_1,a_2)$ the last factor can be written
$$P(a_1,a_2,a_3) = P(a_3\mid a_1,a_2)P(a_1,a_2)$$
Once again, $P(a_1,a_2)$ is $P(a2\mid a_1)P(a_1)$ and you get your formula.


what is wrong to display if condition correctly?

Question:

var arr = [{
  name: "John Doe"
}, {
  name: "jamal"
}, {
  name: "Badr"
}, {
  name: "mohsen"
}]

arr.forEach((val) => {
  firstLetter = val.name.split(" ")[0].split("")[0];
});

for (var i = 0; i < arr.length; i++) {
  if (firstLetter == "J" || firstLetter == "j") {
    console.log("Goodbye " + arr[i].name);
  } else {
    console.log("Hello " + arr[i].name);
  };
};
Comment: I think you did not post all of the code, and I dont understand your question so could you try to explain your problem
Comment: `firstLetter = val.name.split(" ")[0].split("")[0];` is going to replace the variable on every iteration. It does not magically remember each first letter. You should be read the first letter inside of your for loop.
Comment: i want dispaly if the first name's first letter is J or j console could display goodbye name whose first name is J or j but any letter else it could display hello + name
Comment: After the `forEach` loop, `firstletter` is the result for the last element of the array.
Answer: In your code, the firstLetter has only the last value in it m as you're overwriting its value.
Change the code to:

var arr = [{
  name: "John Doe"
}, {
  name: "jamal"
}, {
  name: "Badr"
}, {
  name: "mohsen"
}]

const firstLetter = [];
arr.forEach((val) => {
  firstLetter.push(val.name.split(" ")[0].split("")[0]);
});

for (var i = 0; i < arr.length; i++) {
  if (firstLetter[i] === "J" || firstLetter[i] === "j") {
    console.log("Goodbye " + arr[i].name);
  } else {
    console.log("Hello " + arr[i].name);
  };
};
Answer: If I understand correctly, you want to say "Goodbye " + val.name for names which start with J or j (and "Hello " + val.name for others). There's no need to do two loops for this (do the forEach or the for loop).
In any case, you can address the first character in the name as .name[0] and use comparison operators or String methods to determine if the name starts with a J or a j.
See the following code snippet for an example of this.

var arr = [{
  name: "John Doe"
}, {
  name: "jamal"
}, {
  name: "Badr"
}, {
  name: "mohsen"
}];

arr.forEach((val) => {
  if (val.name[0] === "J" || val.name[0] === "j") {
    console.log("Goodbye " + val.name);
  } else {
    console.log("Hello " + val.name);
  }
});
Answer: You do not need an other loop after forEach, what you need is to check if the specific name starts with J/j
var arr = [{
            name: "John Doe"
        }, {
            name: "jamal"
        }, {
            name: "Badr"
        }, {
            name: "mohsen"
        }]

        arr.forEach((val) => {
            firstLetter = val.name.split(" ")[0].split("")[0];

            if (firstLetter == "J" || firstLetter == "j") {
                console.log("Goodbye " + val.name);
            } else {
                console.log("Hello " + val.name);
            };

        });


How to use a varImp function to select features from training set?

Question: Till now I have used a following flow for training a random forest model.
create 10 folds of data.
for each fold i:
    - use ith fold as validation data
    - use remaining 9 folds as training data
    - apply normalization on training and validation data
    - # apply feature selection on training data
    - # select same features from validation data
    - train random forest on training data
    - predict values for validation data
combine all predictions.

Now I want to do feature selection using varImp() function. I am confused as it is said that varImp itself trains a model on training data to find out best set of features.
How should I use varImp to get important features (say using partial least squares) and then again apply training model on training data?
Comment: There's no need to use feature scaling with Random Forest. https://stats.stackexchange.com/questions/255765/does-random-forest-need-input-variables-to-be-scaled-or-centered If you're using random forest, you might as well apply a random forest-based feature selection method such as the Boruta algorithm. https://stats.stackexchange.com/questions/2350/why-does-the-random-forest-oob-estimate-of-error-improve-when-the-number-of-feat/2359#2359
Comment: Inside your loop, step/line 4 says "apply feature selection", how did you select these features?
Answer: This sounds a lot like recursive feature elimination. See the caret help page for feature selection.
Answer: I'd suggest removing the least important/lowest varImp features using this criterion, then re-runing test and validation sets. In some cases, but not always, this would increase your success. Note that normalization is generally not recommended for this approach and may in fact result in a loss of valuable signals.


Access child element value of Div

Question: I have following code:

  Text:
       <input type="text" aria-controls="searchResult">

I want to get the input field values if anything is entered.
I only have mentioned code and i can't change it like putting id or adding any event. So then how to do it.
Even if i'm able to detect changes in div that will also helpful.
I have tried like:
$("#searchResult_filter").change(function() {
  alert("ketyup");
});

Comment: Attach a `keyup` or `keypress` event handler to the `input`
Comment: check this : http://stackoverflow.com/questions/8769158/get-value-of-child-div-of-a-parent-div
Comment: How to attatch keyup  for input.
Answer: I have found the solution: By adding keyup eventListener
document.getElementById("searchResult_filter").addEventListener("keyup",disableConsultarOpcionesdeFinanciacion);

It call the below function on input box keyup:
function disableConsultarOpcionesdeFinanciacion()
{
 //Code to do somthing
}

Answer: Use .keyup()

Description: Bind an event handler to the "keyup" JavaScript event, or trigger that event on an element.

$("input[type=text]").keyup(function (e) {

        alert($(this).val());

    });

Comment: I don't have any id for input field.
Comment: @Abhay Ok select using above changed method
Comment: I have multiple input fields in my html.
Comment: Then either select using id , or their index values . Actually above code will  work for all input type text .. and it will give you the value of input being changed real time. @Abhay
Comment: I only have mentioned code and i can't change it like putting id or something. So then how to do it.
Comment: @Abhay : use above code it will work for multiple text input too
Comment: In that case if i enter in other input then function will execute.
Comment: if you change any text input ,, this function will run and give the value of that particular text input
Answer: Try this..

 Text:
    <input type="text" aria-controls="searchResult"   onchange="GetInputVal(value)">

 function GetInputVal(val) {
 //your logic to handle the value
 }

Comment: I have not access to add onchange method can it be possible to add it via js/jquery?
Comment: pls try $( "input[aria-controls="searchResult").change(function() { // your logic here}
Answer: jQuery selector also work like the css selector. So you can use the following code.
$("#searchResult_filter input[type=text]").keyup(function (e) {
        console.log($(this).val());
});

Or
$("input[aria-controls=searchResult]").keyup(function (e) {
            console.log($(this).val());
    });

Comment: I have posted the solution.

Access child element value of Div


If 6 high school teams play each other once in a division, what is the probability that one team has a perfect 5-0 season?

Question: I tried to use inclusion exclusion, and got something close, but not quite right. I am also assuming each team is as likely to lose as to win.
For the event $A_i$ being the event that team $i$ has a perfect season, with each event having $P(A_i)=(1/2)^5=\frac{1}{32}$, by inclusion exclusion
$$
P(\cup_{1}^6 A_i)=6\frac{1}{32}-{6\choose 2}\frac{1}{32^2}+{6\choose 3}\frac{1}{32^3}-{6\choose 4}\frac{1}{32^4}+6\frac{1}{32^5}-\frac{1}{32^6}
$$
The correct answer in the book is 5/32. By messing around on wolfram alpha, it seems that if I cut off the final term, which represents the impossible event that all 6 teams have perfect seasons, I get to within .01 of the answer. But why cut off this term? It also isn't possible to have 5 teams have perfect seasons? Also, how in the world did they get such a nice simple fraction?
Thanks!
Comment: Odd, the answer should be $\frac{6}{32}$...
Comment: There cannot be more than one
Comment: Remember that $P(A_1\cap A_2)= P(A_1)\cdot P(A_2)$ is true **only** when the events are independent.  In general $P(A_1\cap A_2)=P(A_1)\cdot P(A_2\mid A_1)$, but as mentioned it cannot be the case that multiple teams have a perfect season simultaneously.  (Suppose two teams both have a perfect season, then in the single game they played against eachother they both were the winner: contradiction)
Comment: @JoeyZou the back of the back claims 5/32.
Comment: @JMoravitz I noticed this, but I guess I don't really understand inclusion exclusion very well. Or at least got confused between when you are allowed to overcount and correct
Answer: There are, in the tournament, $2^{15}$ possible combinations of game outcomes, each of which is equally likely.
Of these $2^{15}$ tournament results, how many have one team at five wins?
You can choose the team ($6$ ways) and having done that, five results are forced, and the remaining ten results can be any combinations, you don't care about them.
So the answer is
$$
\frac{6\cdot 2^{10}}{2^{15}} = \frac{6}{32}
$$
The correct answer in the book is using a definition of "correct" with which I was previously unfamiliar.
Comment: it's defined as "I trust the book more than myself"
Comment: I really like this answer, combinatorics makes it way more intuitive. Thank you!
Comment: Upvoting your answer. Nice approach.
Answer: Outline
The key to this problem is first realizing that if one team has a perfect $5-0$ season, then no other team has a perfect $5-0$ season..  The probability of a particular team having a perfect season is winning all the $5$ matches, i.e. $\frac{1}{32}$. This can be any one of the teams, so the required probability is $\color{blue}{\frac{6}{32}}$
Comment: But there are six teams, not five, so shouldn't it be $6/32$?
Comment: oy ok. So with inclusion exclusion, you "expand" until you reach an impossible event?
Comment: Yes, You could do it carefully, but it does get complicated, because of handling the impossibilities.
Comment: the book is wrong! thank you
Answer: The implicit assumption seems to be that all teams are equally good so that each outcome of a game is equally likely. If the sport is soccer and one team is the Brazilian National team while the other 5 teams are local high schools, the record 5-0 is all but certain.
The "correct" answer therefore will depend on the ex ante distribution of ability within the division. (Though I doubt the textbook was expecting to proceed that way.)


Creating a loading timeout page in React

Question: I am trying to make a timeout page when loading certain data from the backend takes too long, but i am failing at something very easy (i think), my code currently
const Layout = ({ lang: { language, loadingLang }, getLang }) => {
  const time = useRef(0);
  const timer = useRef(false);
  useEffect(() => {
    // Get the language
    if (!language && !loadingLang) {
      getLang();
      //Start the timer
      timer.current = setInterval(function() {
        ++time.current;
        console.log(time.current);
      }, 1000);
      return () => {
        clearInterval(timer.current);
      };
    }

    // Prevent any useless errors with net line:
    // eslint-disable-next-line
  }, []);

  if (language && !loadingLang) {
    // stop the timer if whe have the data
    clearInterval(timer.current);
  }

  if (!language && time.current > 10) {
    return <LoadingTimeoutPage />;
  }

  // If the language data does not exist or is loading show the preloader
  if (!language && time.current < 10) {
    return <Preloader />;
  }

  return (
    <Router>
      <NavBar />
      <Switch>
        <Route exact path="/" component={Home} />
        <Route exact path="/hire" component={Hire} />
        <Route exact path="/swimschool" component={SwimSchool} />
        <Route exact path="/login" component={Login} />
        <PrivateRoute path="/dashboard" component={DashBoard} roles={['any']} />
        <Route exact path="*" component={PDNE} />
      </Switch>
    </Router>
  );
};

It should be very simple i think but i just can't get it to work how it is supposed to, right now it will just show the preloader even after the 10 seconds have passed, am i doing something wrong that i am just overlooking?
Comment: You should show what function is consuming time. Is it getLang()? Does it return promise?
Comment: I don't think so, its a redux function. But yes getLang is consuming time thats why i start a timer when i run getLang
Comment: You are starting a timer but you never actually trigger a re-render when the timer value exceeds the limit. A changing ref does not tigger a re-render.
Comment: How come a function like `getLang` is time consuming?!
Comment: Ah that would explain it, what is a better way to do this then?
Comment: @bravemaster getLang gets the language info from the backend, if for whatever reason this takes to long i want to show a different page
Answer: You need to periodically check the timer value and trigger a re-render when it exceeded the limit:
const Layout = ({/* ... */}) => {
  const [limitExceeded, setLimitExceeded] = useState(false);
  const time = useRef(0);
  const timer = useRef(false);

  useEffect(() => {
    if (!language && !loadingLang) {
      getLang();

      timer.current = setInterval(function() {
        if(time.current > 10) {
          // trigger a re-render by setting limitExceeded to true
          setLimitExceeded(true);
          clearInterval(timer.current);
        } else {
          ++time.current;
        }
      }, 1000);

      return () => clearInterval(timer.current);
    }
  }, []);

  useEffect(() => {
    if (language && !loadingLang) clearInterval(timer.current);
  }, [language, loadingLang]);

  // ...

  if (!language && limitExceeded) {
    return <LoadingTimeoutPage />;
  }

  // ...
}


What is parametrics and Parametrization of equations?

Question: I always read about parametric equations and parametrization of equations, but what is that anyway? how can I tell the difference between a Parametric equation and a 'normal' one?
Answer: A parametric equation basically is where variables are defined using a common parameter. For example the standard equation of a parabola can be parameterized like this:
$$y^2=4ax$$ $$y=2at$$ $$x=at^2$$ where $t$ is the common parameter. Each value of $t$ corresponds to a unique point on this parabola. For instance $t=2$ will give $(4a,4a)$.
You can then derive the equations of a tangent, or a normal to this parabola in terms of this parameter. You can also derive various relations of two points in terms of this parameter(for example, when the chord through two points passes through the focus, $t_1t_2=-1$).


Applying time series forecasting model in categorised data

Question: My dataset looks like this
+-------+--------+----------+
|     ID|     Val|      Date|
+-------+--------+----------+
|Ax3838J|81119.73|2021-07-01|
|Ax3838J|81289.62|2021-07-02|
|Ax3838J|81385.62|2021-07-03|
|Ax3838J|81385.62|2021-07-04|
|Ax3838J|81385.62|2021-07-05|
|Bz3838J|81249.76|2021-07-02|
|Bz3838J|81324.28|2021-07-03|
|Bz3838J|81329.28|2021-07-04|
|Bz3838J|81329.28|2021-07-05|
|Bz3838J|81329.28|2021-07-06|
+-------+--------+----------+

In real, there are 2.7 million IDs and total 56 million rows.
I am using Azure Databricks (PySpark) and trying to apply fbprophet on a sampled dataset of 10000 rows and it's already taking 5+ hours.
I am considering applying NeuralProphet and StatsForecast but not sure how can I apply the forecast model for each individual ID to do the forecasting on ID basis.
Any suggestions?
NB: while applying fbprophet, val becomes 'y' and Date becomes ds in the respective order.
Here is what I have tried so far:
def forecast_balance(history_pd: pd.DataFrame) -> pd.DataFrame:

    anonym_cis = history_pd.at[0,'ID']

    # instantiate the model, configure the parameters
    model = Prophet(
        interval_width=0.95,
        growth='linear',
        daily_seasonality=True,
        weekly_seasonality=True,
        yearly_seasonality=False,
        seasonality_mode='multiplicative'
    )

    # fit the model
    model.fit(history_pd)

    # configure predictions
    future_pd = model.make_future_dataframe(
        periods=30,
        freq='d',
        include_history=False
    )

    # make predictions
    results_pd = model.predict(future_pd)
    results_pd.loc[:, 'ID'] = anonym_cis

    # . . .

    # return predictions
    return results_pd[['ds', 'ID', 'yhat', 'yhat_upper', 'yhat_lower']]

result_schema =StructType([
  StructField('ds',DateType()),
  StructField('CIS_ANONYM',IntegerType()),
  StructField('yhat',FloatType()),
  StructField('yhat_upper',FloatType()),
  StructField('yhat_lower',FloatType())
  ])

historic_data = df.filter(F.col('ds') < '2022-02-20')

group_results = (
    historic_data
    .groupBy('ID')
    .applyInPandas(forecast_balance, schema=result_schema)
    )

Comment: What "ID" is? If it is something like user ID, using it as a feature would mean that you cannot make predictions for any new user not available in the training dataset...
Comment: `ID` are fixed. I am trying to forecast `val` for each `ID` and that's where facing the problem.
Comment: Simple solution would be to have a separate time-series model per each ID, why this would not work for you?
Comment: Can you please suggest how? Especially how to I scale the model for each ID? [note: I have added the code that I used]
Comment: Create a separate dataset per each ID and train a standard time-series model for it. Would this be a bad idea?
Comment: for 2.7 million unique ID?
Comment: Why not? I don't know what your data it, so cannot tell.
Comment: can you share any reference doc or article to understand a bit more clearly how can I do so?
Comment: Maybe tell us more what your data is? What are the IDs? Why are they important? Is there any variability between IDs?
Answer: You can use StatsForecast to perform your task. The library parallelizes the training for each time series (ID). StatsForecast receives a pandas dataframe with tree columns: unique_id, ds, y. So you have to rename your columns:
from statsforecast.core import StatsForecast
from statsforecast.models import auto_arima

df = df.rename(columns={'ID': 'unique_id', 'Val': 'y', 'Date': 'ds'})
df = df.set_index('unique_id')

fcst = StatsForecast(df, models=[auto_arima], freq='D')
forecasts = fcst.forecast(h=30)

You can use StatsForecast with spark trough fugue. Here's and example.
If you use Ray, you can also scale your task.
Regarding using prophet, I recommend using other models such as the AutoARIMA from StatsForecast. With this experiment we have seen that it is a lot faster and more accurate than prophet.


Calculating and interpreting effect sizes for interaction terms

Question: Can an effect size be calculated for an interaction effect in general and more specifically using the F-statistic and its associated degrees of freedom?  If yes, should this be done and what is the appropriate interpretation of the effect size given the nature of interaction effects?  Initially, I assumed the answer is "no." However, a quick Google search turned up statements about computing effect sizes for interaction terms.  Any assistance in clarifying this issue will be greatly appreciated!
Answer: Yes, an effect size for an interaction can be computed, though I don't think I know any measures of effect size that you can compute simply from the F and df values; usually you need various sums-of-squares values to do the computations. If you have the raw data, the "ezANOVA" function in the "ez" package for R will give you generalized eta square, a measure of effect size that, unlike partial-eta square, generalizes across design types (eg. within-Ss designs vs between-Ss designs).
Answer: Looking into classic old texts (like Geoffrey Keppel's Design and Analysis:  A Researcher's Handbook and Fredric Wolf's Meta-Analysis: Quantitative Methods for Research Synthesis), I've seen several options, including omega, phi, and the square of each.  But most widely interpretable and simplest to obtain from most software packages' output is the incremental contribution that the interaction makes to r-squared.  Partial eta squared (explained variance not shared with any other predictor in the model) is another option, and in fact for an interaction tested in a sequential model, it should be the same as the increment in r-squared.  I realize I'm not answering your question about specifically using F and df; if that is that essential to you maybe others can address it.  Wolf shows how to convert F to r for the 2-group case only, and I'm not the strongest when it comes to formulas.


IRunningObjectTable.Register always sets pdwRegister to 65536, an invalid value

Question: I'm using IRunningObjectTable.Register and IRunningObjectTable.Revoke as shown in this tutorial.  My VBScript client initially calls methods no problem, but when the C# COM server disposes, I always receive a "Value does not fall within the expected range" exception.  This is due to the commented line below:
private const int ACTIVEOBJECT_STRONG = 0x0;

[DllImport("ole32.dll")]
private static extern int CreateBindCtx(int reserved,
    out IBindCtx bindCtx);

[DllImport("oleaut32.dll")]
private static extern int RegisterActiveObject
    ([MarshalAs(UnmanagedType.IUnknown)] object punk,
    ref Guid rclsid,
    uint dwFlags,
    out int pdwRegister);

// register instance so it appears in ROT
private static int Register<T>(T classToRegister)
{
    int pdwRegister;
    Guid guid = Marshal.GenerateGuidForType(typeof(T));

    RegisterActiveObject(classToRegister,
        ref guid,
        ACTIVEOBJECT_STRONG,
        out pdwRegister);

    return pdwRegister;
}

// do stuff in VBScript before disposal calls Revoke with the stored
// pdwRegister value from the method above

// revoke instance so it's removed from ROT
private static void Revoke(int pdwRegister)
{
    IBindCtx bc;
    CreateBindCtx(0, out bc);

    IRunningObjectTable rot;
    bc.GetRunningObjectTable(out rot);
    // EXCEPTION: pdwRegister is *always* 65536, an invalid value!
    rot.Revoke(pdwRegister);
}

If I terminate the program and ignore the exception, the instance usually removes itself from the ROT.  However, after some time, I've noticed multiple instances of my app's GUID in the ROT and my VBScript client starts failing on GetObject(, "my.id").  Any thoughts?
Comment: The code snippet is hopeless, no sign of the Register call.  Post code that can reproduce the problem.
Comment: Fixed - more details can be found in the linked article
Comment: Well, debug this.  What is the value of pdwRegister right after the RegisterActiveObject call?  Does the value get stored in a VBScript variable?  Does it get destroyed doing so?  Not checking the return value of RegisterActiveObject is unwise btw.
Comment: Everytime I've debugged the program, pdwRegister has had the value 65536.  The return value of RegisterActiveObject is always 0, another invalid pdwRegister value.  VBScript is completely separate from this code - it only interacts with it through COM interfaces
Answer: The first one registered is always 65536, and that is correct.
Use
[DllImport("oleaut32.dll", PreserveSig = false)]
        public static extern void RevokeActiveObject(
            uint handle,
            IntPtr reserved);

And Not:
IBindCtx bc;
    CreateBindCtx(0, out bc);

IRunningObjectTable rot;
bc.GetRunningObjectTable(out rot);
// EXCEPTION: pdwRegister is *always* 65536, an invalid value!
rot.Revoke(pdwRegister);

And RevokeActiveObject needs to be called from the same thread and proc as it was registered in.
Comment: You must be correct about the first object always being 65536 because that's always the value I see.  Do you know what the difference between these two methods are?  Why did you suggest the pinvoke method?
Answer: I suspect that you are not maintaining the lifetime of the object correctly.  I've done the same thing you have, but used two separate types, placing each of them in the Running Object Table.
Like you, the first object I placed in the table, I received a handle value of 65536.  However, for the second item, I received a different handle.
However, when calling RevokeActiveObject, both calls returned an HRESULT of S_OK.
Something tells me that your object is being disposed of before the calls to revoke them are made.
Either that, or something is not incrementing/decrementing the reference count of the item on the ROT.
Comment: Unfortunately, I don't have the troubled code anymore and a simple test doesn't throw an exception.  Perhaps it did have something to do with object lifetimes...


Is here any trick for multiplication Sn permutations in this example

Question: I've got problem with permutation group multiplication.
Here is an example:
Determine the permutation $\alpha = S_9 $ is that $ \alpha*\omega * \alpha^{-1} = \gamma$ . How much of those permutations we have?
$ \omega= (13624)(587)(9) $ and $\gamma = (15862)(394)(7)$
$ \alpha*\omega * \alpha^{-1} = \gamma$
Is here any trick to do this? I will be very thankful for every help.
Answer: Yes, there is a trick, or more specifically a theorem. It says that for $(i_1,...,i_k) \in S_n$, $$\alpha\cdot (i_1,...,i_k) \cdot \alpha^{-1}=(\alpha(i_1),...,\alpha(i_k)).$$ In particular, $$\alpha \omega \alpha^{-1}=\alpha (13624)\alpha^{-1}\alpha (587)\alpha^{-1}\alpha (9)\alpha^{-1}=(15862)(394)(7).$$ So you're looking for $\alpha \in S_n$ such that $\alpha(1)=1,\alpha(3)=5,\alpha(6)=8$, etc...


A unique decomposition of an element to irreducible elements, not all of them primes

Question: Let $D$ be a Noetherian integral domain which is not a UFD. Being Noetherian guarantees that every non-zero non-invertible element $d \in D$ can be written as a product of irreducible elements of $D$, see this question; of course, such a product is not necessarily unique (for example,
$(1+\sqrt{3}i)(1-\sqrt{3}i)=4=2 \cdot 2$).
It is not difficult to show that if some element $d \in D$ can be written as a product of prime elements of $D$, then this product is unique (if
$d=p_1 \cdots p_m= u_1 \cdots u_n$,
where the $p_i$'s are primes and the $u_i$'s are irreducibles, then use the primality of each $p_j$ and the fact that $D$ is an integral domain).
I wish to find a Noetherian integral domain $D$ and an element $d \in D$
such that $d= v_1 \cdots v_l$ is unique,
$v_1 \ldots, v_l$ are irreducibles, with at least one of the $v_j$'s non-prime.
(Hence the converse of the above fact is not true).
Am I missing an easy example? (probably). What if we remove the assumption that $D$ is Noetherian?
(Remark: If some of the $v_j$'s are primes, then they must appear in every decomposition of $d$, but here this fact is not relevant, since I have already assumed that $d$ has a unique decomposition).
Comment: What if you take $d$ to be an irreducible non-prime? Am I missing something here?
Comment: Thanks, you have not missed a thing, it is just that I have not written all the details, namely, I meant $l \geq 2$. Your comment is a good answer for $l=1$.
Answer: I think you can use the example you consider in your post, namely $D = \mathbb{Z}[i \sqrt{3}]$. Consider the factorization
$$w = 2 \cdot (1 + i\sqrt{3}).$$
The generic element of our domain is $z=a + i \sqrt{3} b$ where $a,b \in \mathbb{Z}$ and this has absolute value squared $|z|^2 = a^2 + 3b^2$. Only certain positive integers take this form, and we can, with a bit of work, write down all the $z$ with a given absolute value squared.
Suppose we factor $w$ into irreducibles $w = z_1 \cdots z_n$. Then we must have $|z_1|^2 \cdots |z_n|^2 = 16$. This constraint leaves only finitely many possiblities for $z_1,\ldots,z_n$ (Note in particular that any $z_i$ with $|z_i|^2 = 1$ is one of the two units $\pm 1$). Some casework should allow you conclude that the above factorization of $w$ into irreducibles is unique, up to units.
However, neither $2$ nor $1+i\sqrt{3}$ is prime, as can be seen from your post.
Comment: Nice answer, thanks!


What are the digits of a complex number?

Question: The digits of a natural number like $5782$ can be written as a sequence of natural numbers
$$(5,7,8,2)$$
Similarly, the digits of a real number can be written in the same way, e.g. the digits of $\pi$ are
$$(3,1,4,1,5,9,2,...)$$
Is there an analogous notion for complex numbers? Writing them in a single sequence of natural numbers doesn't really make much sense to me. I could imagine either a vector of sequences, like the number $\pi + i \mathbb{e}$ being written as
$$\begin{pmatrix}(3,1,4,1,5,9,2,...)\\(2,7,1,8,2,8,1,...)\end{pmatrix}$$
or as a sequence of vectors
$$ \left( \begin{pmatrix}3\\2\end{pmatrix}, \begin{pmatrix}1\\7\end{pmatrix},  \begin{pmatrix}4\\1\end{pmatrix}, \begin{pmatrix}1\\8\end{pmatrix}, \begin{pmatrix}5\\2\end{pmatrix}, \begin{pmatrix}9\\8\end{pmatrix}, \begin{pmatrix}2\\1\end{pmatrix},...\right) $$
or maybe as a sequence of complex numbers with real/imaginary parts in $\{0,1,...,8,9\}$
$$\left( 3+2i, 1+7i, 4+1i, 1+8i, 5+2i, 9+8i, 2+1i,...\right)$$
The first version seems very wrong, because (to me) the digits of a number can be enumerated one after the other and in that case, there is only one single thing: a vector of two sequences.
The latter versions seem similar to each other in the same way that $\mathbb{R}^2$ and $\mathbb{C}$ are similar.
All of my ideas seem pretty clunky and I wasn't able to find anything online. Is there even such a thing as the digits of a complex number, that people generally agree on? Does this question even make sense?
Comment: Look up "base $1+i$".
Comment: (In fact, "base $-2$" lets you write any positive _or_ negative number without using a minus sign!)
Comment: But as a rule, we don't talk about "the digits of a complex number." We can talk about the digits of the real part and the digits of the imaginary part.
Comment: @AkivaWeinberger Thank you for the search-term. I've read a little on it now, but I don't really understand it fully yet. Talking about different base-systems seems to make sense, as opposed to "digit systems", like I was talking about.
Answer: Some different point of views:
$\bullet$ Suppose they are comparable. Complex numbers form a super set of real numbers i.e., a real number $a$ is also a complex number and can be written in the general form of $a+0.i$. With this assumption, we proceed to compare $i$ and $0=0+0.i$. Cleaely, $i\ne0$. Hence, $i>0$ or $i<0$.
Case 1. $i>0\Rightarrow i.i>0.i\Rightarrow-1>(0\times0)+(0\times1)i=0~\rightarrow\leftarrow$
Case 2. $i<0\Rightarrow i.i>0.i\Rightarrow-1>(0\times0)+(0\times1)i=0~\rightarrow\leftarrow$
$\bullet$ The set of complex numbers are unlike, the set of real numbers or its subsets, "unordered". So, the concepts of comparibility do not apply at all i.e., it is not possible to enumerate them.
$\bullet$ Geometrically, the complex numbers are viewed on a plane, NOT a straight line which is why, your second way of writing them is correct: a set of 2 dimensional vectors. All the numbers lying on either axes are real numbers, a subset of complex numbers. By similar, if you mean you can write a bijective function $f:\mathbb{R}^2\rightarrow\mathbb{C}$ then, yes. This is correct.
Now, if you want to talk about digits, it can only be done separately for the real parts and the imaginary parts. So, your first visualization is OK in such a case. Although usually, the preferred representation for a single number is using one vector to represent it. In case of a real number it is 1 dimensional; for an imaginary number it is a 2-dimensional representation.


Inserting html into php using echo

Question: I'm currently developing web leaderboards for a Minecraft server and I've run into an issue.
Here's my code that works:
<?php
      while( $row = mysql_fetch_assoc( $result ) ){
        echo
        "

          $row[UUID]
          {$row["KILLS"]}
          {$row["DEATHS"]}

\n";
      }
    ?>

So I'm trying to make it instead of a clickable UUID make it the actual image. In order to do that it needs to be: (http://cravatar.eu/avatar/uuid/64.png) I've tried to use the img tag but I get an issue. I'm extremely new to php so if you can "dumb" down your answer that'd be great.
EDIT: I got it semi working! I used ($uuid = $row['UUID'];) then added the variable in the link. Thank you to everyone who suggested stuff!
Comment: I tried doing () but towards the end it starts a informative tag. @Nordenheim
Comment: Use the `{$row['UUID']}` syntax in the first `` like you do in the last two.
Comment: @iVersion, do you have a closing tag on the img?  That's not valid HTML as it's written in the comment.
Comment: You need to make sure that contents of `$row["UUID"]` is vaild for an url. But it looks as if it is simply a nickname of an avatar so probably ok. Secondly, you must use the correct syntax for printing a variable within a string, as Kenney has pointed out. Last but not least, make sure your use of quote and doublequote doesnt get mixed up.. For instance, use single-quote for array-'names' and double quotes to encapsulate the string youre printing out
Comment: @Devon When testing that method I did add a closing img tag.
The $row["UUID"] should print out the UUID of the player which is fine for the website I'm using. Can you explain using the correct syntax for print a variable more?
Answer: After correcting some mistakes, I have two ways that i would suggest for you to try
1st way is
<?php

      while( $row = mysql_fetch_assoc( $result ) ){
        echo
        '

          '.$row["KILLS"].'
          '.$row["DEATHS"].'

\n;';
      }
?>

And the 2nd way is
<?php do { ?>

  <?php //echo $row['UUID']; ?>
              <?php echo $row["KILLS"]; ?>
              <?php echo $row["DEATHS"]; ?>

<?php  } while( $row = mysql_fetch_assoc( $result ) ) ?>

Hope this helps
Comment: Not really an answer to the problem, just a different way of doing both the loop and the output.  Probably just going to confuse them, plus you have an error.
Comment: I have edited the answer and now it will display the image instead of the link @Devon
Comment: 1st method works just I need the avatar to update based on their stats.
2nd method also works but it duplicates the table (https://gyazo.com/f2f7d95bd5259c844fb0981a5a0fd242)
@OmariOmosa
Comment: is `` code representing their stats?
Comment: The **second way** is the most sure way. It means you have two results. The **first way**, i have tried it in some scenario and in most of the scenario it displays one less. e.g. instead of displaying 5 it displays 4. instead of displaying 2 i displays 1,.   Lets try to do this @iVersion .Take this code `` as is to the **second code** that you say it is duplicating the table and try to fix it on the image whereby it keeps changing and see if it works
Comment: You use while, or do when you want to repeat a region .If you don't want to repeat a region you remove it and query the specific row that you want.

Inserting html into php using echo


How to access shared files in two different domains

Question: There are two internal domains, domainA and domainB at my workplace. I could remote into machines from either domains by using respective credentials.
My doubt is if I create a shared folder on domainA with read access to everyone for e.g., \\server1.domainA.net\sharedfolder. Will I be able to access this folder by just entering the path likewise from any machine in domainB without entering credentials.
Comment: On second thought, I'm not sure I want to get in to this.
Comment: So, was the answer a guess or there is a slight ambiguity so that I can provide more information.
Comment: It was the 'Everyone' bit that I'd have to test before I could provide a positive answer. When DomainA trusts DomainB, DomainA trusts the authentication mechanisms of DomainB. There, SSO works. But anonymous files shares are sort of a complicated thing which is what made me less confident in my answer.
Comment: Yes, idea is not to have the credentials window to popup since it has permissions set to everyone. Our development servers are in same env. but this situation arise in UAT which is under release team control. So, it is becoming difficult to test.
Answer: You'll need to edit local security policy on server1 to allow anonymous users to be a part of the "Everyone" group.  (Computer Configuration -> Windows settings -> Security settings -> local policies -> Security Options -> Network access: Let Everyone permissions apply to anonymous users)
http://technet.microsoft.com/en-us/library/cc772211.aspx
Answer: You'll need to use Anonymous Users in the NTFS permissions instead of Everyone.  This is because starting with Win 2k3 the Everyone group no longer includes Anonymous Users.
See Anonymous Users and Traverse Checking
You could Let Everyone permissions apply to anonymous users by enabled the Group Policy Setting @ Computer Configuration\Windows Settings\Security Settings\Local Policies\Security Options, but that may be more than you want to open up for this.


How to change text in textbox

Question: Ok this is wheat I have so far. IF someone could help me out. I had to change the color of the background when you click on a button. And I also have to Use document.getElementById('yourelementid') to both find the value of the textarea and to change the basic text created in the div. But I don't know how to do that i have been researching online. I think i am getting a little confused about where to put things at in here thanks.
Here is what I have so far....
      <!DOCTYPE html PUBLIC "-//W3C//DTD Xhtml 1.0 Strict//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

     <title>DOM</title>
     <meta http-equiv="content-type" content="text/html;charset=iso-8859-1" />

DOM Assignment Examples

    <form>

Change background color to:

     <input type="radio" value="White" onclick="newbg('white');">white

     <input type="radio" value="Blue" onclick="newbg('blue');">Blue

     <input type="radio" value="Beige" onclick="newbg('Beige');">Beige

     <input type="radio" value="Yellow" onclick="newbg('yellow');">Yellow

    </form>

add text to this box change the text below:

    <TEXTAREA NAME="" ROWS="10" COLS="40" onBlur="blurHandlerRouting">
    You will change this text
  </TEXTAREA>

  <INPUT TYPE="button" NAME="button" Value="Click" onClick="testResults(this.form)">

Comment: I don't understand... when the user clicks on the button, what happens? The contents of the `` are transferred to... what?
Comment: I am suppose to Create a div with some basic text to start out.  Create a form that has a textarea.  Use document.getElementById('yourelementid') to both find the value of the textarea and to change the basic text created in the div. (Hint: user innerHTML)
Answer: The contents of a <textarea> can be manipulated using .html() in jQuery or .innerHTML in vanilla JavaScript.
Your HTML should contain the id="" attribute:
<textarea id="mytextarea">Text to be changed</textarea>

And the JavaScript:
document.getElementById('mytextarea').innerHTML = "New Text";

Comment: Yeah he said i had to use .innerHTML I am just still a little confused about that part.
Comment: .value is more reliable than .innerHTML.
Answer: To change the background and the textarea you would try this:
function = testResults(){
    document.getElementById("yourTextBoxId").style="background:red;"; //Change the background color to red.
    document.getElementById("yourTextAreaId").value="your another text for the textarea"
}

Comment: .value is more reliable than .innerHTML.

How to change text in textbox


How to 2d array initial to 0

Question: int array2d[3][5]{};

for (auto& iter1 : array2d)
{
    cout << "iter1 in 2d array - " << iter1 << endl;
    for (auto& iter2 : iter1)
    {
        cout << "iter2 in 2d array - " << iter2 << endl;
    }
}

Result

iter1 in 2d array - 00CFFCB4
    iter2 in 2d array - 0
    iter2 in 2d array - 0
    iter2 in 2d array - 0
    iter2 in 2d array - 0
    iter2 in 2d array - 0
    iter1 in 2d array - 00CFFCC8
    iter2 in 2d array - 0
    iter2 in 2d array - 0
    iter2 in 2d array - 0
    iter2 in 2d array - 0
    iter2 in 2d array - 0
    iter1 in 2d array - 00CFFCDC
    iter2 in 2d array - 0
    iter2 in 2d array - 0
    iter2 in 2d array - 0
    iter2 in 2d array - 0
    iter2 in 2d array - 0

How to 2d array initial to 0??
Comment: it's already all zeros. those other values are addresses for each row (`iter1` is a reference to a 1-D array)
Answer: Your 2d array does have all elements initialized to zero! This is shown by the fact that there are fifteen lines in your output of the form iter2 in 2d array - 0.
The non-zero outputs for iter1 are actually addresses: the type of iter1 is int (&iter1)[5] - which is, for each outer loop, the address of each of the three 'rows' of the 2d array.
Answer: for m rows and n columns,
vector<vector<int> > array2d( m , vector<int> (n));

Comment: this is both not an array and doesn't even guarantee zero initialization (since C++14)
Comment: I think the "2nd array" thing was a confusion with what `iter1` is vs `iter2` in the question's code block
Comment: @CruzJean I got confused with the term "2nd array" with "2d array",
by the way, what is second array?
Comment: @CruzJean, what do you mean by "doesn't even guarantee zero initialization"? `std::vector(n)` is a vector of `n` zero `int`s.
Comment: @Evg that constructor (since C++14) default constructs the elements. `int` default constructor does nothing, so not guaranteed to be zero. it's like if you just declared a variable `int val;` without giving it a value (uninitialized). If you want zeros, use e.g. `vector(n, 0)`
Comment: @CruzJean Unfortunately, this is wrong. In C++11/14/17 you're guaranteed to get zeros. Since C++14 elements are ["default inserted"](https://en.cppreference.com/w/cpp/named_req/DefaultInsertable) instances of `T`. With a default allocator, elements will be [value-initialized](https://en.cppreference.com/w/cpp/named_req/DefaultInsertable#Notes) as by `T()`. That is, `int()` for `int`.
Comment: @Evg Ah, I stand corrected. I was under the impression `int()` was uninitialized and `int{}` was zero initialized. Still, I'd recommend being explicit with the `vector(n, 0)` constructor

How to 2d array initial to 0


Atualizando valores em uma ListView

Question: Eu adiciono os valores que estão dentro de 3 arrays no hashMap para inserir na listview:
 ArrayList<HashMap<String, String>> lista = new ArrayList<HashMap<String,String>>();

    for(int i=0; i<tema.length; i++ ) {
        HashMap<String,String> item = new HashMap<String,String>();
        item.put("tema", tema[i]+": "+tempo[i]);
        item.put("palavras", palavras[i]);
        lista.add(item);
    }

O que eu quero fazer é que quando o usuário clicar no botão SUBIR, por exemplo. O item que ta na posição 2 (se for o que ele tiver clicado) suba para a posição 1, e o que estava na posição 1 ocupe a posição 2.
Substituindo:
 up.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        if(posicao!=0 && tema.length>1) {

              auxtema = tema[posicao-1];
              auxpalavras = palavras[posicao-1];
              auxtempo = tempo[posicao-1];

              tema[posicao-1] = tema[posicao];
              palavras[posicao-1] = palavras[posicao];
              tempo[posicao-1] = tempo[posicao];

              tema[posicao] = auxtema;
              palavras[posicao] = auxpalavras;
              tempo[posicao] = auxtempo;

        }

Dentro do array eu consegui fazer. Eu substitui, mas como faço para atualizar isso dentro da listView, e atualiza-la?
Answer: Não sei se entendi bem sua duvida, mas caso seu listview tenha um Adapter você pode implementar uma método que atualiza o ArrayList dentro do Adapter e chama o método notifyDataSetChanged
Ex.:
public void atualizarLista(ArrayList<HashMap<String, String>> lista) {
    this.lista = lista;
    notifyDataSetChanged();
}

Answer: Como o seu código não está mostrando como você instanciou a ListView não dá para ter certeza se você está utilizando um adapter padrão ou seu próprio adapter.
Assumindo que você implementou seu próprio ListAdapter (herdando direta ou indiretamente de BaseAdapter) ou usou algum adapter capaz de lidar com atualizações dinâmicas (e.g., ArrayAdapter), a solução é chamar o método notifyDataSetChanged após ter atualizado o modelo:
Para fazer isso (assumindo que listView é sua ListView)
((BaseAdapter) listView.getAdapter()).notifyDataSetChanged();

Atualização: Pela estrutura do seu código você deve estar utilizando um SimpleAdapter.
Se minha resposta e a do @R3oLoN não fizeram sentido eu recomendo fortemente dar uma lida no tutorial do Lars Vogel: Using lists in Android (em inglês).
Comment: Eu não tenho dados suficientes sobre seu código / adapter para te dar uma solução específica, mas [remover](http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#remove(int)) o item da `ArrayList` e chamar `notifyDataSetChanged` deveria funcionar. De uma olhada [nessa resposta do SOE](http://stackoverflow.com/questions/5497580/how-to-dynamically-remove-items-from-listview-on-a-button-click).

Atualizando valores em uma ListView


Android studio - Faild to resolve: com.android.support:design:26.0.1 error

Question: I have an error called:
 "Failed to resolve: com.android.support:design:26.0.1".

My android studio version is 3.0 beta 1.
My gradle file is as below:
apply plugin: 'com.android.application'

android {
compileSdkVersion 26
buildToolsVersion "26.0.1"
defaultConfig {
    applicationId "hojune.example"
    minSdkVersion 17
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:26.+'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
testCompile 'junit:junit:4.12'
compile 'com.android.support:design:26.0.1'
}

I want to put "design" to my project, but I can't do it. How can I do it?
Comment: Does your project-level `build.gradle` file have both `jcenter()` and `maven { url 'https://maven.google.com' }` in its `allprojects` `dependencies` closure?
Comment: Yes, I changed app-level build.gradle file's com.android.support.design:26.0.1 to com.android.support.design:26.0.0-alpha1. And I solved my problem well.
Comment: August already google release 26.0.1 version, Problem might be you didn't sync properly. may be you could disable **offline mode** and try to sync again. V2.6.0 is [July release check here the latest one](https://developer.android.com/topic/libraries/support-library/revisions.html)
Comment: Follow instructions from here - https://developer.android.com/about/versions/oreo/android-8.0-migration.html
Answer: Add this to your project level build.gradle file:
repositories {
    maven {
        url "https://maven.google.com"
    }
}

Just to clarify, this should be in the "allprojects" section of the gradle file (Thanks to @tys)
Comment: Except where it does not work.  I have Android Studio 2.3.3, am using com.android.tools.build:gradle-experimental:0.9.3, and have the Google repository in my maven repositories list as per above -- and still it cannot find the 26.0.1 support libraries.
Comment: Just to clarify, this should be in the "allprojects" section of the gradle file
Comment: Wow! This worked. @JessHolle you need to change the gradle build version. Make it 2.3.3
Comment: As I noted on another question and then forgot to note here, the issue was that @Tys noted, I had this in my buildscript rather than allprojects section -- a subtle but critical difference.
Answer: Try to Change
buildToolsVersion "26.0.0"

and
com.android.support:design:26.0.0

Or not change into bulidToolsVersion Change dependencies
compile 'com.android.support:design:26.0.0-alpha1'

Comment: Please explain, in detail, how this would address the problem. Also, do not use `+` for library version numbers, as then you have no idea exactly what version you are getting, when you need to build this code again in the future (e.g., fixing a bug on a historical branch from version control).
Comment: It is not the solution. Why should you use an alpha version while there is a stable version ??
Comment: But I get "Faild to resolve: com.android:support:design-v7:26.+".
Answer: I had the same problem i solved it by using
compile 'com.android.support:design:26.0.0-alpha1'

Answer: According to the comment of @Muthukrishnan Rajendran is right google already release 26.0.1 version so a problem in your way of building.
If you using android studio 3.0 then you need to read this documentation please refer this link https://androidstudio.googleblog.com/2017/05/android-studio-30-canary-1-sdk-updates.html here specified maven.google.com are now available so you need to added below line of code
allprojects {
    repositories {
        jcenter()
        maven { url 'https://maven.google.com' }
    }
}

for the above gradle change you need to refer this document https://developer.android.com/topic/libraries/architecture/adding-components.html
also required to change if your project is old
dependencies {
   classpath 'com.android.tools.build:gradle:3.0.0-alpha1'
}

Answer: I solved it by replacing
compile 'com.android.support:design:26.0.1'

with
compile 'com.android.support:design:26.0.0-alpha1'

Comment: **Avoid doing this!** Degrading from a stable version to an alpha version is a very bad idea when there is a stable version.


Implementing PPPoE half-bridge/ip-passthrough to suit IPSec VPN firewall appliance with Linux

Question: (I'm editing my own question and posting an answer for anyone else who finds themselves in a similar position.)
I would like a firewall appliance that requires a public static IP on its external interface to be used with an ISP-approved ADSL modem.  (This setup isn't recommended as the ADSL service and modem are consumer-grade, but we need to save money.)
The modem can act as a router, which means it will NAT all traffic and use the service's 1 public static IP on its external interface.  We can't use a public subnet behind this NAT as this isn't supported by this ADSL service.
The other option is that this modem can act as a full bridge, but the firewall appliance is not capable of terminating a PPP link.
There is one modem (DrayTek Vigor 120) that I could acquire that is capable of half-bridge mode (DrayTek calls this "True-DMZ"), where one device behind the modem is assigned the ADSL link's one public static IP address.  This worked, but unfortunately we had unrelated problems with the ADSL line and were not able to receive any support from our ISP while using this modem.
How do I configure a Linux PC so that it terminates the PPP link in half-bridge mode?
Answer: I used Debian on a PC with three NICs (1 for management, 1 to connect to the modem, 1 to connect to the firewall).  I ended up with eth0=management, eth1=modem, eth2=firewall, ppp0=ADSL service and lo.

Prepare PC with ppp (and pppoeconf if desired) [note: this PC will lose its connection to the internet when this is all set up]
Put modem into full-bridge mode
Configure ppp and connect, test connection, etc.
Configure eth1 and eth2 as "auto ethx" and "iface ethx" in /etc/network/interfaces
Add the following to /etc/ppp/ip-up (just before the "run-parts" line):
ifconfig ppp0 an IP in a subnet you'll never use/that subnet's CIDR
ifconfig eth2 up
ifconfig eth2 your public IP/your public subnet
ip route delete default
ip route add default dev ppp0
ip route flush cache

You should end up with a route table that looks like this:

0.0.0.0/0 ppp0
your public IP's network/your public IP's subnet eth2
network you don't care about/subnet ppp0

The way this works:

eth1 doesn't need an IP address, as PPPoE is a frame protocol
eth2 gets another IP in the same subnet as your public IP
ppp0 gets an IP you don't care about (but doesn't clash with anything you do care about)
when a packet arrives from ADSL, its source will be some other public IP and its destination will be your public IP: it will egress eth2 (due to route #2)
when a packet arrives from the firewall, its source will be your public IP and its destination will be some other public IP: it will egress ppp0 (due to default route)

Example:
Say your public IP is 188.8.131.52/24 and your gateway is 18.104.22.168 (our ISP assigned us something like this; the way I understand it, you would normally get 220.127.116.11/32 with no gateway).  Say also that 172.16.1.0/24 is a network you'll never use anywhere.  So:
<code>ifconfig ppp0 172.16.1.1/24

ifconfig eth2 up

ifconfig eth2 22.214.171.124/24

ip route delete default

ip route add default dev ppp0

ip route flush cache
</code>
Your route table:

0.0.0.0/0 ppp0
220.127.116.11/24 eth2
172.16.1.0/24 ppp0

Note that you are assigning eth2 18.104.22.168 and not 220.127.116.11.  Eth2 needs to be on the same subnet as your public IP, but not the public IP itself.
Caveat:
You'll need to use either the real subnet used by your ISP (e.g., 220.127.116.11/24) or make up a pretend one (and use /30 to keep it as small as possible).  Other IPs (typically other customers of your ISP) in this subnet on the internet will become unreachable to you.
Comment: You're welcome. It's a pleasant surprise this has helped someone
Comment: Yes. This kind of stuff isn't everybody's cup of tea. But so are my mostly answers here :)
Comment: Thank you. You set my direction: https://android.stackexchange.com/a/218562/218526


My view's 'more' link needs to go to a page with exposed filters already selected

Question: I have a view that is a list of a certain content. The more link for the view needs to link to a page I have set up that has exposed filters for sorting the content.
So let's say the view I have is of baseball-related content. The more link will go to another page that contains all sports, but in this case it will link there but already have the baseball filter selected. Confused?
What I had been trying was to use the Custom URL field in the view, but no tokens can be used. Maybe this isn't even the right way to go about it. I'd love to know what is.
Any ideas?
Answer: I believe you want to use Contextual Filters (or, the functionality formerly known as Arguments").
Expand the "advanced" fieldset on the right side of your View's admin panel.
If, for example, I select "Content:Type" as a contextual filter, and my main page output of the view has a path of "/testview" then I can go to "/testview/Page" and see all content of type "Page". Same with my other content types, which happen to be "Story", "Product", and "Slide". You can do this with features besides content type. It sounds like using taxonomy terms would meet your needs.
Comment: This may have worked, but I never got around to trying it. You'll see the more complex solution a coworker came up with. Thanks though!
Answer: My coworker came up with this. Works flawless. It was put in the file views_and_panels.module file created by one of our features.
<code> /**
 * Implement hook_panels_pane_content_alter().
 *
 * Add more links to the appropriate panels.
 */
function module-name_views_and_panels_panels_pane_content_alter($content, $pane, $args, $context) {
  if($pane->subtype == 'node:field_related_products') {
    if($context['argument_entity_id:node_1']->data) {
      $values = field_get_items('node', $context['argument_entity_id:node_1']->data, 'field_catalog');
      $tids = array();
      if($values) {
        foreach($values as $value) {
          $tids[]  = $value['tid'];
        }
      }
      $content->more = array(
        'href' => 'catalog/all_products-tax-term',
        'title' => 'See All',
        'query' => array(
          'field_catalog_tid' => $tids,
        )
      );
    }

  }

  if ($pane->subtype == 'view-name_featured_resources_and') {
    if ($content->delta == 'view-name_featured_resources_and-block_2') {
      if ($context['argument_term_1']->data) {
        $tids = array();
        $tids[] = $context['argument_term_1']->data->tid;
        $content->more = array(
          'href' => 'catalog/all_products-tax-term',
          'title' => 'See All',
          'query' => array(
            'field_catalog_tid' => $tids,
          )
        );
      }
    }
  }
</code>


Geofield (geocode from another field) - database entry not created

Question: On a Drupal 7.63 site, I have a content type with a "Postal Address" field (address module, v7.x-1.3) (mandatory) and a "Geofield" field (geofield module, v7.x-2.4). The geofield field has no input interface: it uses the "Geocode from another field" widget and is configured to use the Postal Address field as a source. Its information is then used to render a small map using Google Map ("Geofield map").
My issue is that when creating new nodes, the geofield field remains empty and no map is rendered. And when updating the address on existing nodes, the map isn't updated (it still shows the old point).
I checked directly in the database (table field_data_field_geofield), and can confirm that the rows corresponding to the new nodes are not there. So it seems the data is never created in the table, but I don't know why.
I see no error message on the edit page of the nodes or in the recent log page (admin/reports/dblog).
The addresses used for those nodes are correctly formed and stored (I checked the field_data_field_adresse table); they are rather simple and can easily be found on Google Maps. (Example: Grand-Rue 5, 2900, Porrentruy, Switzerland)
I tried applying the patch provided in this issue, but it didn't solve my problem, even when creating new content (I have since rolled back this change). Maybe it's not the same problem.
Update: after more research, this issue seems to describe my problem. However:

applying patch #29 doesn't solve the problem
applying patch #41 doesn't solve the problem
downgrading geocoder to v.1.3 doesn't solve the problem either.

Any suggestion on what is wrong would be greatly appreciated. What else should I check for?
(It's on a website that has used this system for several years and it's the first time I see this problem.)
(I created a request support ticket on the geofield page last week, but so far I haven't received any feedback.)
Answer: So in the end the problem actually had two causes, which made it more difficult to solve than it should have been:

a bug in the geocoder codebase (solution: apply this patch)
the Google Maps API key used in the geocoder configuration was actually invalid for this type of operation, and so I had to generate another key specifically for geocoding operations. (I noticed the problem via a geocoder error saved in the recent log entries pages.)


Validar campos com OnClientClick

Question: Estou tentando chamar uma função JavaScript através do OnClientClick.
O problema é que ao rodar no navegador ele não valida os campos, é como se a função simplesmente não fosse chamada.
JavaScript:
function VerificaCampos() {
   //verifica processo
   var ddlprocesso = document.getElementById("<%=ddlProcesso.ClientID%>")
   if (ddlempresa.options[ddlprocesso.selectedIndex].value == ""){
      alert("Favor preencher processo!");
      ddlprocesso.focus();
      return false;

Botão:
<asp:Button ID="btnBuscar" runat="server" CssClass="botao"
  Text="Gerar" OnClientClick="if(VerificaCampos()) return false;"
  OnClick="btnBuscar_Click"/>

Comment: Você chegou a colocar um alert dentro da função para ver se ela é chamada?
Comment: Se a sua função estiver num arquivo `.js` não irá funcionar a parte do `asp.net`: `<%=ddlProcesso.ClientID%>`. Pode confirmar se está num arquivo ou na mesma página `.aspx`? Segundo, como o @CaiqueRomero comentou, validou se está entrando na function, usando um `alert` ou `console.log`?
Comment: @RobervalVenicio Conseguiu?
Answer: Um dos problemas é que em seu javascript você está instanciando o ddlProcesso e depois e depois tetando verificar outro objeto que não foi declarado o ddlEmpresa
function VerificaCampos() {
   //verifica processo
   var ddlprocesso = document.getElementById("<%=ddlProcesso.ClientID%>")
   //if (ddlempresa.options[ddlprocesso.selectedIndex].value == ""){
   if (ddlprocesso.options[ddlprocesso.selectedIndex].value == ""){
      alert("Favor preencher processo!");
      ddlprocesso.focus();
      return false;
    }
}

Depois como o colega comentou, se o seu javascript estiver em arquivo js separado do aspx, o Response.Write() não irá funcionar, mas você pode contornar isso de maneira simples. Basta colocar em seu dropdown o atributo ClientIDMode="Static" assim seu id no DOM será "ddlProcesso" também
<asp:DropDownList ID="ddlProcesso" runat="server" ClientIDMode="Static"></asp:DropDownList>

E no javascript você poderá selecioná-lo sem precisar da ajuda do ASP.Net
var ddlprocesso = document.getElementById("ddlProcesso");

E por último, mude o evento do seu botão, para OnClientClick="return VerificaCampos();"
<asp:Button ID="btnBuscar" runat="server" CssClass="botao"
  Text="Gerar" OnClientClick="return VerificaCampos();" OnClick="btnBuscar_Click"/>

Validar campos com OnClientClick


MLE of a function of a parameter

Question: I am working on a problem where we are interested in finding the MLE for a function of two parameters.
I am having problems with going about finding this. Intuitively, the idea makes sense. I am just wondering about the definition of the MLE of a function of two parameters (Google isn't turning up much). The question is as follows:
Question: Suppose that $X_1,\ldots,\,X_n$ are iid $N(\mu, \sigma^2)$ with unknown $\mu,\sigma^2$. Find the MLE for $\frac{\mu}{\sigma}$.
Note that this is not just a homework problem, but part of a take home final. I really am not looking for much of an answer, but more or less the idea for such problems.
Edit
Apparently MLE's are invariant under function. TY
Comment: Assuming you have found the MLE of $\mu$ and $\theta$ you just need to use this [theorem](http://www.stats.ox.ac.uk/~dlunn/b8_02/b8pdf_6.pdf).
Comment: @caburke link is forbidden now
Answer: The question was answered with a link in a comment, so let me just give here the argument from the link, for future completeness.
We assume a statistical model for data $X$ is parameterized by a parameter $\theta$ (which can be scalar or vector, or even more general).  Let the likelihood function be $L(\theta)$ and the value of $\theta$ maximizing that be the maximum likelihood estimator $\hat{\theta}$ (mle). We do assume that estimator exists and is unique. Wanted is the mle of $g(\theta)$, a function of $\theta$. First we assume that $g$ is one-to-one. Then we can write
$$
    L(\theta) = L(g^{-1}(g(\theta))
$$
and both functions are clearly maximized by $\hat{\theta}$, so
$$
   \hat{\theta} = g^{-1}(\hat{g(\theta)})
$$  or
$$
  g(\hat{\theta}) = \hat{g(\theta)}
$$
If $g$ is many-to-one, then $\hat{\theta}$ which maximizes $L(\theta)$ still corresponds to $g(\hat{\theta})$, so $g(\hat{\theta})$ still corresponds to the maximum of $L(\theta)$. (Argument paraphrased from the link in the comment above).
Answer: I just came up with a solution that I personally like more (for wide range of reasonable estimators):
Assume that $f$ is convex (likelihood function, the solution is unique) and $A$ is monotonous (function of parameter, $\exists A^{-1}$), then $f(A(x))$ is also convex.
What we want to prove is that
$$ \arg\max_{x\in X} f(A(x)) = A^{-1}(\arg\max_{z \in A(X)} f(z))$$
Now assume that there exists such a pair $(\tilde x, \tilde z)$ s.t. they are optimal for corresponding problems but $A(\tilde x) \neq \tilde z$.
From optimality:
$f(\tilde z) > f(z') \quad \forall z'$ and $f(A(\tilde x)) > f(A(x')) \quad \forall x'$
including $z' = A(\tilde x)$ and $x' = A^{-1}(\tilde z)$, then
$$ f(\tilde z) > f(A(\tilde x)) > f(A(A^{-1}(\tilde z)) = f(\tilde z)$$
- contradiction!
Comment: more specifically, if you want to get some $\hat g = g(\theta)$ consider a function $A = g^{-1}$ and $f$ is the likelihood $f(\theta)$.

MLE of a function of a parameter


Customized Jquery UI spinner

Question: Iv been stuck on this one for over a month now, really really need help on this one,
I want to use Jquery ui spinner with following customizations :

The increment up and down button should be defined by me, my images should be used
The increment step size should be variable

Another other approach , than using jquery ui would be welcomed but need help to achieve this , basic functionality im looking for is : till mousedown on image keep incrementing textbox value, thats it
Answer: you can try with:
<code>       https://github.com/btburnett3/jquery.ui.spinner
</code>
Is easy to use and you only need 2 files (ui.spinner.min.js or ui.spinner.js and ui.spinner.css)
Answering to your questions:

You can override any of the css classes listed below to put your desired image, and play with some values in the browser development tool to see your changes.
<code>    classes: ui-spinner-up ui-spinner-button ui-state-default ui-corner-tr
</code>
The increment size could be set in the 'step' property.

Example:
<code>$('#someId').spinner({
                        min: 0,
                        max: 100,
                        increment:'fast',
                        step:5  // this will increment or decrement by 5
                    });
</code>
Remember that the HTML component with id="someId" should be an input with type="text" or "number" but if you choose the last one and your browser support HTML5 it will render the up/down arrow inside the input and below the buttons added by this extension. My suggestion is to use type="text".
Cheers.
Comment: naah i dont want to do all this , i just need the simple spinner describe in the question
Comment: I reply again with another approach, I hope that helps. Regards.
Comment: @NishantJani Reads very much like "No, I don't want to learn how the technology works, just give me a working solution."
Comment: ".ui-widget" is also important.
Answer: If you look at the latest version in github for spinner, https://github.com/jquery/jquery-ui/tree/master/ui
They have added code in the last commit for spinner to have option to change images. As far as increment step size is concerned you can add the step value in options. Hope this helps.
Answer: I forgot mention that you can use jQuery UI 1.9, in the milestone 6 they were featuring many updates for the Spinner widget.
Please visit this site for further details:
JQuery UI 1.9 milestone 6
Remember that this feature is 'in development', the visual design looks good but the working spinner looks like this example
For your purposes:

The images could be changed by CSS.
The option 'step' should provide the increment step size.
Till mousedown on image keep incrementing textbox is working as you expect.

Note: Remember that you can download the first release candidate of JQuery UI 1.9 RC,  to test that.
I hope this helps.

Customized Jquery UI spinner


Android create directory

Question: I'm trying to create a folder in the Downloads directory on the SDcard of an Android device. I have declared <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> in the manifest.
Here's my code:
String state = Environment.getExternalStorageState();
    if (!Environment.MEDIA_MOUNTED.equals(state)) {
        Log.e("file writer", "Directory not writeable");
        Toast.makeText(this, "Not writeable.",
                Toast.LENGTH_SHORT).show();
    }

    File dir = new File(Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_DOWNLOADS), "myfolder");
    dir.mkdirs();
    if (!dir.mkdirs()) { Log.e("file writer", "Directory not created"); }

I get the "directory not created" error and there's obviously no folder where I intend there to be one.
Comment: You have to request run time permissions also if you are running app on android 6.0 and above
Answer: Have you tried this?
String state = Environment.getExternalStorageState();
if (!Environment.MEDIA_MOUNTED.equals(state)) {
    Log.e("file writer", "Directory not writeable");
    Toast.makeText(this, "Not writeable.",
            Toast.LENGTH_SHORT).show();
}else{

File dir = new File(Environment.getExternalStoragePublicDirectory(
        Environment.DIRECTORY_DOWNLOADS), "myfolder");
dir.mkdirs();
if (!dir.mkdirs()) { Log.e("file writer", "Directory not created"); } }

Answer: for getting permission in Android 6+ you should ask user, try this
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)) {
            // Show an expanation to the user *asynchronously* -- don't block this thread waiting for the user's response! After the user sees the explanation, try again to request the permission.
        } else {
            // No explanation needed, we can request the permission.
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_WRITE_STORAGE);
            // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an app-defined int constant. The callback method gets the result of the request.
        }
    }

Comment: run time permissions are applied to android 6+, not 7+
Comment: I think you must be right. The exact same code worked on my Android 5.1 test device but not on the one running 6.0.1
Answer: Try this code
 File rootPath = new File(Environment.getExternalStorageDirectory(), "Download/myfolder");
 if (!rootPath.exists())
        rootPath.mkdirs();

Hope it work

Android create directory


When voiceOver is on, how to dismiss UIPresentController when tap on dimmed view

Question: When voiceOver is on, how can I dismiss UIPresentViewController?
Answer: You will need to add custom view to presenting view and add tap gesture recogniser to it.  Look into Adding Custom Views to a Presentation at Apple Doc
Also, added snippet of some of the functionality.
<code>private lazy var backgroundView: UIView = UIView(frame: CGRect.zero)
private lazy var tapGestureRecognizer: UITapGestureRecognizer = UITapGestureRecognizer()

override init(presentedViewController: UIViewController,
              presenting presentingViewController: UIViewController?) {

    super.init(presentedViewController: presentedViewController, presenting: presentingViewController)
    self.tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.dismiss))
    self.backgroundView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    self.backgroundView.isUserInteractionEnabled = true
    self.backgroundView.addGestureRecognizer(tapGestureRecognizer)
}

override func containerViewDidLayoutSubviews() {
    super.containerViewDidLayoutSubviews()
    self.presentedView?.frame = self.frameOfPresentedViewInContainerView
    if let container = self.containerView {
        // Set frame for background view
        self.backgroundView.frame = container.bounds
    }
}

override func presentationTransitionDidEnd(_ completed: Bool) {
    if !completed {
        self.backgroundView.removeFromSuperview()
    }
    // Additional TearDown
}

override func presentationTransitionWillBegin() {
    self.containerView?.addSubview(self.backgroundView)
    // Additional SetUp
}

// Tap gesture handler
@objc
func dismiss() {
    self.presentedViewController.dismiss(animated: true, completion: nil)
}
</code>


Continuous random variable and median problem

Question: The definition of median, $m$, for a continuous random variable $X$ is
$$P(X\leq m)=P(X\geq m)=\int_{-\infty}^m f(x)\text{d}x=\int_{m}^{\infty}f(x)\text{d}x=\frac{1}{2}$$
where $f(x)$ is the pdf of $X$.
Now the problem goes as follows:

Show that if $X$ is a continuous random variable, then
$$min_{a} (E|X-a|)=E|X-m|$$

The work I have done for this problem:

WORK
Have that
$$E|X-a|=\int_{\mathbb{R}} |x-a|f(x)\text{d}x=\int_{a}^{\infty}(x-a)f(x)\text{d}x-\int_{-\infty}^a (x-a)f(x)\text{d}x$$
Differentiation with respect to $x$ gives us
$$\frac{d}{dx}E|X-a|=\int_{a}^{\infty} f(x)\text{d}x-\int_{-\infty}^a f(x)\text{d}x$$
Setting this equal to 0, we find that
$$\int_{a}^{\infty} f(x)\text{d}x= \int_{-\infty}^a f(x)\text{d}x$$
We know that
$$\int_{\mathbb{R}}f(x)\text{d}x=1$$
$$\implies \int_{a}^{\infty} f(x)\text{d}x= \int_{-\infty}^a f(x)\text{d}x=\frac{1}{2}$$
Hence, $a$ must be our median, by definition.

What I am confused on is showing the minimal property. I looked up what I could, and it appears that using the second derivative to show that we produce a positive value for f(a) present us with minimality, but I don't really understand why. Potentially a very naïve question, but why does f(a)>0 for second-derivative have significance? Is it because of the absolute-value property on $X-a$?
Comment: The variable of interest is $a.$ So the derivative should be taken with respect to $a.$
Comment: self-study flag missing?
Comment: The derivative is not quite right: its sign is in error.  Based on that, you should conclude that the median *maximizes* $E|X-a|$.
Answer: Based on your work,
$$ I(a) = \frac{d}{da} E|X-a| = \int_a^{\infty} f(x) ~ dx - \int_{-\infty}^a f(x) ~ dx $$
If $a=m$, then $I(m) = 0$.
Think of $I(a)$ geometrically. You have a probability mass functions $f(x)$. Geometrically $I(a)$ is the area of the right-half of the curve minus the left-half of the curve at the point $a$. Therefore, if $I(m) = 0$ and $a>m$ then, as you are weighing the curve now more to the left, $I(a) < 0$. By a similar argument, $I(a) > 0$ if $a<m$.
Ignore the second-derivative test. Use the first-derivative instead here. As $I(a) = 0$ at $a=m$, $I > 0$ for $a>m$, and $I<0$ for $a<m$, it follows that at $a=m$ we have a minimum point.
Comment: Your argument would be correct if you used the correct derivative.  With your expression for $I(a)$, it approaches $-1$ as $a\to\infty$ and $1$ as $a\to -\infty$, proving that $m$ is a *maximum* of $I$, not a minimum.
Comment: Once I get more reputation, I shall give you an upvote. Thank you very much, my friend. This was incredibly helpful :D


Creation order of static/global objects

Question: In my application, there are 2 global objects. One object's constructor it accesses the other one assuming it is already created. Fortunately my application was running correctly for some time. But due to the recent changes in cpp files and compilation order, I figured out that the global object creation order has been changed from what my application was expected.
So, My question is,
Is there a way to control the creation order of global objects. I think the same issue should be there for static objects as well. According to my tryouts I identified that the linking order or "o" files changes this. But is it correct? Isn't there a proper way of doing this?
Answer: Ignoring the fact that global variables are not a very good idea, you can wrap the objects inside of functions. This way, they get created when they are first accessed, giving you control over creation order:
Foo& get_foo()
{
  static Foo f;
  return f;
};

Bar& get_bar()
{
  static Bar b(get_foo());
  return b;
}

Example of use:
int main() {
    Bar& b = get_bar();
    return 0;
}

Comment: @SujithGunawardhane - the can be accessed by calling the above functions.
Comment: Lower-overhead solution: Just define all run-time initialized interdependent objects in the same compilation unit in dependency order. Bonus: You get the proper destruction order for free (compared to slight overhead with wrapping in functions).
Comment: But then, can these objects accessed by some other places as usual static / global objects?
Comment: @Deduplicator, I doubt there's any overhead, any decent compiler will optimize the function call out since it never changes.
Comment: @Blindy: How? The purpose of wrapping the global as a static in an accessor function was delaying initialization until first use and thus avoiding the static initialization order fiasco.
Comment: @Deduplicator, turns out we were both right, VC++ 2012 optimizes the function call out, but adds a boolean test (`jne`) before using the value that calls or skips the `static` initialization. So yeah, there is a bit of overhead.
Answer: A nice maintainable way would be to create global pointers to these objects and assign them in a single function (such as main() or elsewhere) in the desired order. If you were instead to do "lazy-evaluation" and simply let the objects be created upon access, then it will be much less obvious what order they are in, and thus less maintainable.
This does of course mean that you will have null pointers if they are not initialized.
if A's ctor must use object B, then A should assert that B is not null.
(edit: That is not say that lazy-evalutaion doesn't have its place, but for this situation I'd personally go with pointers)
Answer: Check out the Singleton pattern (as copied from yolinux). There's a few variations out there, but the idea is to have creation specified at the first usage of the class as accessed via Instance(), which is then used to access the only instance of the class anywhere else in code.
class Singleton{
public:
  static Logger* Instance(){
    if(!m_pInstance) return new Singleton;
    return m_pInstance;
  }

private:
  Singleton(){};  // Private so that it can  not be called
  Singleton(Singleton const&){};             // copy constructor is private
  Singleton& operator=(Singleton const&){};  // assignment operator is private
  static Singleton* m_pInstance;
};

This part should go outside the header (best if in body file):
Singleton::Singleton* m_pInstance = NULL;

Comment: Bad singleton pattern :-(. It's not thread safe, etc.

Creation order of static/global objects


Storing text in database with tags

Question: Can anyone please help me with this? I want to know how to store text in database with the tags. For example, if the text is bold, italics, underlined, justification, paragraphs, space etc., then even that must be retrieved and displayed in the textarea of the jsp page. Please help me out!
Answer: use function getTag("id_of_tag") to get tag.
attached its value and save it to database.Later retrieve it and show in view.
Answer:
Create a field in database with datatype Text
Use some javascript text-area such as tinymce so that user can enter the text bold, italic etc.
Save the field with proper sql injectioning after form submission.

Storing text in database with tags


Do all sample statistics behave normally?

Question: A version of the central limit theorem tells us that the sample means will be distributed roughly like a normal distribution around the population mean.
Are there cases of a sample statistics that don't behave normally? How do they behave? Are all of their distributions independent from the population distribution?
It feels like I'm barely scratching the surface of the definition of CLT. A similar question was asked here.
Answer: The answer to the title question is no.
As an example, suitably standardized sample maxima and minima have limiting distributions that are not Gaussian (see the Fisher-Tippett-Gnedenko theorem).
For another example, see the Pickands-Balkema-de Haan theorem, which is about limiting distributions of values above a threshold.
There are many examples on site of statistics that (when standardized) are not asymptotically normal.
For example, many questions on site discuss the smallest or largest observation from a sample from a uniform population (which statistics have beta distributions). An appropriately 'standardized' smallest observation from a uniform distribution on $(0,k)$ will be asymptotically exponential.
An easier example: $n$ times the smallest observation from sample of size $n$ from a standard exponential is standard exponential, so the limit in this case is trivial (being attained at every sample size).
(These two are both special cases of the Fisher-Tippett-Gnedenko theorem)
Another interesting example is the Kolmogorov-Smirnov statistic $D_n=\sup_{x}|F_n(x)-F(x)|$ (under the null hypothesis); suitably 'standardized' ($K_n=\sqrt{n}D_n$) it approaches the Kolmogorov distribution in the limit.
You might also like to consider the distribution of the sample median in a discrete distribution. For simplicity, consider the case where the population median is at a specific point rather than an interval (skirting, for example, the additional detail required for dealing with a $\text{Poisson}(n)$ for integer $n$). In the limit, the sample median will have all its probability at a single point (the population median).