Problema para a exibição dos valores de um Array no front-end

Question: Galera, boa noite. To com dificuldade para exibir os valores de um array no front-end. No backend ele aparece mas no front não.
Minha classe de tarefa service onde está a função que retorna o array:
 public function procurar(){

       global $procura;

       $comando = $this->conexao->prepare("select tarefa, id_status from tb_tarefas where tarefa like :nome");
       $comando->bindValue(':nome', "%{$procura}%");
       $comando->execute();

       $inf = $comando->fetchAll(PDO::FETCH_OBJ);

       print_r($inf);

   }

Aqui está a parte do código responsável por dar o comando no banco na classe tarefaController :
elseif($acao == 'procurar'){

        $tarefa = new Tarefa();

        $conexao = new Conexao();

        $procura = isset($_POST['procura']) ? $_POST['procura'] : "";

        $tarefaService = new TarefaService($conexao, $tarefa);
        $retorno = $tarefaService->procurar();

        header('location: buscar_tarefas.php?resultado=1');
    }

E então lá no front-end eu abri o bloco de php e mandei escrever a variável $retorno. Dei também um require once para chamar a classe tarefaController:
<?php
 global $retorno;

print_r($retorno);
?>

Me ajudem por favor, galera
Answer: O que acontece é que você não está retornando nenhum valor na função procurar, então o valor de $retorno está como nulo.
Para resolver isso, você deve trocar print_r($inf); por return $inf;
Confira a documentação!
Comment: Fiz o que você falou mas ainda assim não foi. Poderia dar uma olhada no projeto ? Caso isso não seja muito incômodo pra ti, segue o link no github. O projeto está em dois repositórios. github.com/gabrieltec97/Projeto-Help-Desk.git github.com/gabrieltec97/app_lista_tarefas.git
Comment: No seu código ainda está print_r($inf);, mude para return $inf e tente novamente. Faça o commit também.
Comment: E no seu Github também não achei onde você quer exibir o resultado
Comment: Tá comitado lá, irmão. Quero exibir lá no arquivo buscar_tarefas onde deixei um comentário lá. To tentando implementar uma busca naquele sistema, agora só falta exibir em tela. Dá uma olhada lá por favor
Comment: Remova o `header('location: buscar_tarefas.php?resultado=1');` de tarefaController.php:141
Comment: entao brother, se eu remover, ele não irá exibir naquela página. Quero que o conteúdo seja exibido nesta página chamada buscar_tarefas, pois essa página que faz a consulta no banco
Comment: Amigo, não é assim que se passa dados através de páginas em php.
O header apenas redireciona, e pelo que eu vi você não precisa dele pois o buscar_tarefas.php tem um require do mesmo.
Remova e faça a "consulta" através da pagina buscar_tarefas.php, ficaria assim:
buscar_tarefas.php?acao=procurar
Comment: Po nao to entendendo a forma que você ta falando mano, Pode alterar o código lá no github e salvar, se não der, pode me passar o código por aqui?
Comment: Já falei, só remover o header(); e fazer a requisição pela url buscar_tarefas ao invés de fazer em tarefaController
Comment: Funcionou, irmão. Muito obrigado pela ajuda e pela paciência em me ajudar. Valeu mesmo! tmj
Answer: Se o processo das informações não forem feitas na mesma página em que você quer imprimir o resultado, você precisa transferir o retorno de uma pagina para outra.
Assim como o @PauloVictor falou, você precisa de um return na função primeiro.
public function procurar(){

    global $procura;

    $comando = $this->conexao->prepare("select tarefa, id_status from tb_tarefas where tarefa like :nome");
    $comando->bindValue(':nome', "%{$procura}%");
    $comando->execute();

    $inf = $comando->fetchAll(PDO::FETCH_OBJ);

    return $inf;

}

Depois de ter esse retorno, e caso os dados sejam processados na mesma página que será exibido o front, basta dar um print_r()que será imprimido, caso contrario, usar session, por exemplo, para passar as informações para outra página.
Comment: Fiz o que vocês comentaram, mas ainda assim não foi. Poderia dar uma olhada no projeto ? Caso isso não seja muito incômodo pra ti, segue o link no github. O projeto está em dois repositórios.  https://github.com/gabrieltec97/Projeto-Help-Desk.git https://github.com/gabrieltec97/app_lista_tarefas.git


Complete sufficient statistic

Question: I've recently started studying statistical inference. I've been working through various problems and this one has me completely stumped.
Let $X_1,\dots,X_n$ be a random sample from a discrete distribution which assigns with probability $\frac{1}{3}$ the values $\theta-1,\space\theta,\space\text{or}\space\theta+1$, where $\theta$ is an integer. Show that there does not exist a complete sufficient statistic.
Any ideas?
Comment: What do you have so far?
Comment: What do you know about completeness?
Comment: A statistic, $T$, is complete if it satisfies the condition that, for some function $g(T)$, if $E[g(T)]=0$, then $g(T)=0$ $a.e.$
Comment: So you need to find a counter-example ... what clearly ancillary statistic can you find from the sample minimum & maximum?
Comment: I can write the likelihood as: $(\frac{1}{3})^n$ times the product of the indicator functions that each observation is equal to either $\theta-1,\space\theta,\space\text{or}\space\theta+1$. From this it looks like the sufficient statistic is the order statistics. I've been thinking about this for days, it's like nothing I've seen before.
Answer: (1) Show that for a sample size $n$, $T=\left(X_{(1)}, X_{(n)}\right)$, where $X_{(1)}$ is the sample minimum & $X_{(n)}$ the sample maximum, is minimal sufficient.
(2) Find the sampling distribution of the range $R=X_{(n)}-X_{(1)}$ & hence its expectation $\newcommand{\E}{\operatorname{E}}\E R$. It will be a function of $n$ only, not of $\theta$ (which is the important thing, & which you can perhaps show without specifying it exactly).
(3) Then simply let $g(T)=R-\E R$. It's not a function of $\theta$, & its expectation is zero; yet it's not certainly equal to zero: therefore $T$ is not complete. As $T$ is minimal sufficent, it follows from Bahadur's theorem that no sufficient statistic is complete.
Comment: Thinking about it, it would've been simpler just to say that $T$, being minimal sufficient, is some function $f(\cdot)$ of any sufficient statistic $S$, & therefore $g(T)=g(f(S))$ also goes to show the incompleteness of $S$.
Comment: @StubbornAtom: Bahadur's theorem states that if a statistic's complete it's minimal sufficient (providing a minimal sufficient statistic exists at all). So once you show that a minimal sufficient statistic exists & is incomplete, you don't need to worry about the possibility of complete non-minimal sufficient statistics. (Or of course about the possibility of other complete minimal sufficient statistics - they're all one-to-one functions of each other.)
Comment: Could you give a reference for Bahadur' theorem where it states that if a minimal sufficient statistic is not complete, then a complete sufficient statistic does not exist? I was searching for this result, but could not find it anywhere.

Complete sufficient statistic


Approximating a function

Question: I'm sorry if this question in not well formed...
I would like to perform a computation of the following function:
<code>f() = -2*X1 -1*X2 +0*X3 + 1*X4 +2*X5
</code>
(The function can be of more variables, but is always finite and the coefficients are always of this form: -n..-3,-2,-1,0,1,2,3,..n ). Each Xi is also a sum other xi's, that is:
Xi = (xi1 +xi2 + ... xim).
I need some kind of approximation or something like that so I will be able to compute this efficiently, with limit set of operations, because n and m can be large numbers and I need to run this in MATLAB many times.
I can compute sums of the xi's and the Xi's very efficiently, (in O(1)), and I would like if possible to use this.
Suggestions for additional information and examples will be welcomed.
Thanks.
Comment: Your question seems to be ineteresting and I work with such sums lot; but your description is realy foggy to th reader. Can you take some time and describe the problem you have very diligently and in a dedicated way in details so that I get what you really have and what and for which purpose of *efficiency* you want to use it.
Comment: Hi, thank you for your comment, I edited my question, I hope it is better now... let me know.
Answer: Your question can be resumed to the following form:
$$f(x_{i,j})=\sum^n_{i=1} a_{i} X_{i}=\sum^n_{i=1} a_{i} \sum^m_{j=1} x_{i,j}$$
with $a_i \in \Bbb Z$. For the largest coefficient $a_{i}^{max}$ you could define:
$$g(x_{i,j})=a_{i}^{max} \sum^n_{i=1} \sum^m_{j=1} x_{i,j}$$
$f$ would not exceed $g$. It should be to good extent efficient to calcualte $f\approx g$. I hope I understood your question correct.

possible optimization
$$g(x_{i,j})=g^{(p)}-|g^{(n)}|=p_{i}^{max} \sum^k_{i=1} \sum^l_{j=1} x_{i,j}-|n_{i}^{max}| \sum^k_{i=1} \sum^l_{j=1} y_{i,j}$$
while $p$ is for positive and $n$ for negative integers.
Then approximate separately:
$$f^{(p)}\approx g^{(p)}$$
$$f^{(n)}\approx |g^{(n)}|$$
So you may split your approximation to avoid cancellation in the series' approximation.
Comment: Hi, My problem is not the programming language, rather than the method I use, mathematically. I want some kind of approximation because I want the computation be independent of the size of the variables. The code is very straight forward of course. I'm looking  to avoid the multiplications or minimize them as possible, or something similar.
Comment: I'm not sure I understand... the series is finite, should that matter?
Comment: Got your point, see suggestion above.
Comment: Hi, thank you for your edit, I just find it hard to understand how g approximates f, the expression ∑i=1n∑j=1mxi,j equals to X1 + X2 +...Xn? could you please give a more detailed explanation ? thanks!
Comment: ok, say the case is: a = {-1,0,1}, X = {2,3,5}, where X1 = (1+1), X2= (1+2) , X3=(3+2):  then f is: -1*2 + 0*3 + 1*5 = 3. g is: 1*(2+3+5) ? or some kind of optimization is still required here?
Comment: yes. This would be indeed a result of a such a big $\mathcal O$ approximation as you asked for. Such approximation must wrap the whole possibilities of variations, and the bandwidth of your variations due number of parameter is such high. I have not tried it, but, what if you separate the negative and positive series and have this big $\mathcal O(N)$ applied to each of them and then subtract?
Comment: see above extension.

Approximating a function


Firebase list child in listview

Question: I'm new to Firebase, and I need to show a child info on a listview. It adds the data, but it does not show on listview and the app crashes. No error is shown on log, but on firebase crash I have this error:
Exception com.google.firebase.database.DatabaseException: Failed to convert value of type java.util.HashMap to String
com.google.android.gms.internal.zzamy.zzcg ()
com.google.android.gms.internal.zzamy.zzb ()
com.google.android.gms.internal.zzamy.zza ()
com.google.firebase.database.DataSnapshot.getValue ()
br.com.imobapp.CorretorFragment$1.onChildAdded (CorretorFragment.java:58)
com.google.android.gms.internal.zzaip.zza ()
com.google.android.gms.internal.zzakp.zzcxi ()
com.google.android.gms.internal.zzaks$1.run ()
android.os.Handler.handleCallback (Handler.java:739)
android.os.Handler.dispatchMessage (Handler.java:95)
android.os.Looper.loop (Looper.java:145)
android.app.ActivityThread.main (ActivityThread.java:5832)

My data is like this (Sorry, can't post pics since my account is new, only the link):
https://i.stack.imgur.com/lZHFC.jpg
My model is:
import com.google.firebase.database.IgnoreExtraProperties;

@IgnoreExtraProperties
public class ModelCorretor {
    private String CorNome;
    private String CorCreci;

    public ModelCorretor(){

    };

    public ModelCorretor(String CorNome, String CorCreci){

        this.CorNome = CorNome;
        this.CorCreci = CorCreci;

    };

    public String getCorNome() {
        return CorNome;
    }

    public void setCorNome(String corNome) {
        CorNome = corNome;
    }

    public String getCorCreci() {
        return CorCreci;
    }

    public void setCorCreci(String corCreci) {
        CorCreci = corCreci;
    }
}

And my fragment for showing it on listview:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;

import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import java.util.ArrayList;

import static android.content.ContentValues.TAG;

public class CorretorFragment extends Fragment implements View.OnClickListener {

    public CorretorFragment() {
        // Required empty public constructor
    }

    ImageButton btAddCor, btSearchCor;
    ListView lvCorretor;
    DatabaseReference dref;
    ArrayList<String> list = new ArrayList<>();
    ArrayAdapter<String> adapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_corretor, container, false);
        btAddCor =(ImageButton)view.findViewById(R.id.btAddCor);
        btAddCor.setOnClickListener(this);
        btSearchCor =(ImageButton)view.findViewById(R.id.btSearchCor);
        btSearchCor.setOnClickListener(this);
        lvCorretor = (ListView)view.findViewById(R.id.lvCorretor);
        adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_dropdown_item_1line, list);
        lvCorretor.setAdapter(adapter);

        dref = FirebaseDatabase.getInstance().getReference().child("Corretores");
        dref.addChildEventListener(new ChildEventListener() {
            @Override
            // Read from the database
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                String value = dataSnapshot.getValue(String.class);
                list.add(value);
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {
                // This method is called once with the initial value and again
                // whenever data at this location is updated.
            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {
                String value = dataSnapshot.getValue(String.class);
                list.remove(value);
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onCancelled(DatabaseError  error) {
                // Failed to read value
                Log.w(TAG, "Failed to read value.", error.toException());
            }
        });

        return view;
    }

        @Override
        public void onClick(View view){
        MainActivity activity = (MainActivity)getActivity();
            switch(view.getId()){

                case R.id.btAddCor:
                    activity.chamaAddCor();
                    break;
                case R.id.btSearchCor:
                    activity.chamaSearchCor();
                    break;
                default: throw new RuntimeException("unreachable");

            }
        }
}

If any more code is needed or if I did something wrong in the question, please let me know.
I have an idea that I have to set a child for it to show, like I did in FirebaseDatabase.getInstance().getReference().child("Corretores"); but I tried a lot and have no clue how to do it on the onChildAdded.
Answer: The issue is here:
 String value = dataSnapshot.getValue(String.class);

You shouldn't be getting a String object, you should be getting the model for the object you want. You have a model for your Corretor, so you do:
 ModelCorretor value = dataSnapshot.getValue(ModelCorretor.class);

getValue returns a hashmap and you are assigning it to a string, which is why you are getting that error. Firebase is great in that it will build that object for you by just inserting the ModelCorretor as a parameter in the getValue method.
Comment: Thank you, it works. But now it gives another error. In the list.add(value) it says add (java.lang.String) in Array List cannot be applied to br.com.imobapp.ModelCorretor. How do I modify it to an object?
Comment: I've fixed it, I forgot to declare  ArrayList list = new ArrayList<>();
    ArrayAdapter adapter;

Firebase list child in listview


Get the Date into parameters as integers

Question: How can I get the day_of_month, month and the year into parameters as integers?
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Calendar start_date = Calendar.getInstance();
System.out.println(dateFormat.format(start_date.getTime()));

int day = start_date.get(Calendar.DAY_OF_MONTH);
int month = start_date.get(Calendar.MONTH);
int year = start_date.get(Calendar.YEAR);

String result = day + "/" + month + "/" + year;

but, the date today is: 01/12/12, while the result is: 01/11/12.
Comment: MONTH is 0-11, see the javadoc of `Date`
Comment: The Java tag already says that the question belongs to Java language.
Answer: This is expected behaviour. Month goes from 0 to 11. You can check this by issuing:
System.out.println(Calendar.JANUARY);

Calendar
Calendar.MONTH in particular

By the way, to convert dates to Strings, you should really use SimpleDateFormat
new SimpleDateFormat("dd/MM/yyyy").format(start_date.getTime());

(sidenote, but important: SimpleDateFormat is not thread safe very much not thread safe, so don't try to optimize by using them as static instances in a multithreaded environment! This is also stated in the API doc: Date formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally.)
Comment: At least set a link to the official `Calendar` documentation.
Answer: month index starts from 0, thats why gives 11

0- january
  .
  .
  .
  11-december
Answer: In Calendar class Month starts with 0 which is January and ends with 11 which is December.
Open JDk 6-
public final static int JANUARY = 0;
...
public final static int DECEMBER = 11;

Answer: From the documentation of MONTH (the emphasis is mine):

MONTH: Field number for get and set indicating the month. This is a calendar-specific value. The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0; the last depends on the number of months in a year.

Human calendars start January at one, not at zero. That is why December ends up at eleven instead of twelve.
Answer: Just don't use java.util.Date and other bad parts of java
From Java 8 joda time will be in standard library so I do not see point in using bad code.
http://joda-time.sourceforge.net/
You will not have issues with this one, trust me.
Comment: It won't be Joda Time - it'll be JSR-310, which is somewhat different. There are still issues in terms of the Joda Time API too, but I agree it's *much* better than Calendar/Date.
Comment: License will be different, thats for sure but point is to switch now if you can.
Comment: I wasn't talking about the license - I was talking about the API. It's *not* just moving Joda Time to a different package.
Comment: Your right, thanks for update. Still I guess its fair to say that we both agree that Alon Shmiel should use better library
Comment: Its not an argument to switch to another lib , only because somebody uses the existing lib in a wrong way. Better not trust you.
Answer: According to the documentation, the result of start_date.get(Calendar.MONTH) is a int ranging from 0 to 11, where 0 is January and 11 is December.
Calendar.MONTH


Why doesn't MS-DOS initialize the DS and ES registers?

Question: Why does the initialization of the DS and ES registers has to be done manually by the programmer?
For example:
MOV AX, DTSEG
MOV DS, AX

On the other hand, the CS and SS registers are initialized by the operating system (in MS-DOS). Why is this so?
Comment: Wow. Next, I want to see someone ask a question about punch cards :-)
Comment: @John: Did you just ask what hardware MS-DOS runs on?
Comment: Yeah.I had a lot of them,solved few weeks ago !
Comment: @Dave, it's a perfectly valid question for Windows as well
Comment: Which version of MS-DOS? On which hardware?
Comment: dos runs on a wide variety of x86 processors, ES and DS usage is affected by which family you are using.  it is a valid question.
Comment: in fact all MS-DOS versions ,even some of the windows ( till windows 1.3 )
Comment: I once had an MS-DOS device driver that failed only on Leading Edge computers - they initialized the interrupt vectors differently.
Comment: Also, remember that MS-DOS was an OS that could be modified by the OEM to an extent. This question may have different answers depending on the hardware.
Answer: Because CS and SS registers are essential for program execution in contrast to DS and ES registers which point to user-defined data segments. By default no data is present in the executing program this nothing to initialize the DS and ES with. As a program writer you can specify where your data is by setting the data segments registers.
Edit: as was correctly noted by @FrankKotler, in .com file (the entire program size doesn't exceed single segment), DS and ES are initialized and equal to CS. For other execution models, DS and ES are initialized by pointer to PSP (which isn't the pointer to real user data).
Comment: Strictly speaking, ds and es ARE initialized - to point to the PSP, not your data segment (which dos doesn't know - you could have more than one, or have data in your code segment). In a .com file, everything's in the same (PSP) segment, so ds and es are initialized correctly.
Answer: The correct answer to your question (which i believe master V.Aghazarian has asked you in college) is not because CS ans SS are essential for program execution.
The problem in MS-DOS was with Program Segment Prefix
From wikipedia:

The segment address of the PSP is passed in the DS register when the program is executed. It can also be determined later by using Int 21h function 51h or Int 21h function 62h. Either function will return the PSP address in register BX.1


Finding $a_n$ for $a_{n+1}=\frac{1}{2}\left(a_n+\frac{1}{a_n}\right)(n=1,2,3,\cdots),~a_1=2$

Question: I would appreciate if somebody could help me with the following problem:
Q: find $a_n=?$
$$a_{n+1}=\frac{1}{2}\left(a_n+\frac{1}{a_n}\right)(n=1,2,3,\cdots),~a_1=2$$
There are quite a few posts on the main site concerning convergence of this sequence, for example, Calculating square roots using the recurrence $x_{n+1} = \frac12 \left(x_n + \frac2{x_n}\right)$ and more generally Calculating square roots using the recurrence $x_{n+1} = \frac12 \left(x_n + \frac2{x_n}\right)$. So from those posts we know that it converges to $\sqrt2$. But finding the $n$-th term is a slightly different task from finding the limit.
Comment: Are you sure it has a closed-form answer?
Comment: yes exist closed formular
Answer: Rewrite $a_n$ as $\frac{p_n}{q_n}$ for two sequences $p_n, q_n$ that need to be determined.
We have:
$$a_{n+1} = \frac12 ( a_n + \frac{1}{a_n} ) \iff \frac{p_{n+1}}{q_{n+1}} = \frac{p_n^2+q_n^2}{2p_nq_n}$$
We can choose $p_{n+1} = p_n^2 + q_n^2$ and $q_{n+1} = 2p_nq_n$ and get:
$$ p_{n+1} \pm q_{n+1} = ( p_n \pm q_n )^2 \implies p_{n} \pm q_{n} = (p_1 \pm q_1)^{2^{n-1}}$$
Since $a_1 = 2$, we take $p_1 = 2, q_1 = 1$ to get:
$$ p_{n} + q_{n} = 3^{2^{n-1}} \text{ and } p_{n} - q_{n} = 1$$
This leads to
$$ a_{n} = \frac{p_n}{q_n} = \frac{3^{2^{n-1}}+1}{3^{2^{n-1}}-1}$$
Answer: This is the sequence generated by using Newton's method to find square roots, i.e.,
$$\lim_{n \rightarrow \infty} a_n = \sqrt{1} = 1$$
Anyway, consider the following identity:
$$\coth{2 t} = \frac{1}{2}\left ( \coth{t} + \frac{1}{\coth{t}}\right)$$
Then let $a_n = \coth{t_n}$.  The recurrence becomes
$$t_{n+1} = 2 t_n$$
$$t_1 = \text{arccoth}(2)$$
Then the solution to the recurrence is
$$a_n = \coth{\left ( 2^{n-1} \text{arccoth}(2)\right )} $$
where
$$\exp{[\text{arccoth}(2)]} = \sqrt{3}$$
so that
$$a_n = \frac{3^{2^{n-1}}+1}{3^{2^{n-1}}-1}$$


Redirect URL within Apache VirtualHost?

Question: I have a dedicated server with Apache, on which I've set up some VirtualHosts. I've set up one to handle the www domain as well as the non-www domain.
My VH .conf file for the www:
<VirtualHost *>
  DocumentRoot /var/www/site
  ServerName www.example.com
  <Directory "/var/www/site">
    allow from all
  </Directory>
</VirtualHost>

With this .htaccess:
RewriteEngine on
RewriteBase /
RewriteCond %{HTTP_HOST} ^www.example.com [NC]
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]

Is there a simple way to redirect the www to the non-www version? Currently I'm sending both versions to the same DocumentRoot and using .htaccess but I'm sure I must be able to do it in the VirtualHost file.
Comment: http://stackoverflow.com/questions/42500012/apache-rewritecond-not-working-if-then/42512986#42512986
Answer: Turns out mod_rewrite rules are fine in the VirtualHosts file, apart from the RewriteBase rule. I ended up with this:
<VirtualHost *>
  ServerName www.example.com
  RewriteEngine on
  RewriteCond %{HTTP_HOST} ^www.example.com
  RewriteRule ^/(.*)$ http://example.com/$1 [L,R=301]
</VirtualHost>

EDIT: on the advice of joschi in the comments, I'm now using this simplified version using the Redirect directive from mod_alias:
<VirtualHost *>
  ServerName www.example.com
  Redirect 301 / http://example.com/
</VirtualHost>

Comment: You don't need the full-blown rewrite engine with all its checks and possibilities to just redirect the client. It would be (marginally) faster since mod_alias is not near as complex as mod_rewrite and you'd only need one directive (RedirectPermanent) instead of two with mod_rewrite. And last but not least IMHO it's easier to understand what happens in the configuration when someone looks at it the first time.
Comment: You do not need mod_rewrite for this. Use mod_alias and its RedirectPermanent directive instead.
Comment: For some strange reason Redirect 301 .. did not work for us. We had to use the RewriteRule option.
Comment: @joschi: What would be the advantage of that? Is it faster?
Comment: works fine (the second one) but it doesn't change url. still shows www in the url ?
Comment: NOTE: Using PHP 5.3.0 on WAMPSERVER 2.0 on Windows Server 2008 R2 Enterprise, not including `:80` after `VirtualHost *` causes *everything* to return "Forbidden"!
Comment: It is safer to omit the '301' unless you **really** want a **permanent** redirect. The default is 302 Found, which would work better for a lot of people. See http://jacquesmattheij.com/301-redirects-a-dangerous-one-way-street
Comment: I attempted to use the Redirect solution to force an HTTPS connection when the user tries to connect with HTTP.  However the HTTP connection still generated the default 400 error, and an HTTPS connection failed with the browser error "too many redirects."
Answer: Be very careful with 301 redirects because, by default, a browser that receives the 301 redirect will store it permanently - meaning you will give up control what that browser will see when it tries to access the domain www.example.com.
See for example this discussion http://getluky.net/2010/12/14/301-redirects-cannot-be-undon/
So either make sure it does not get cached, or use mod_proxy (I recommend the mod_proxy).
If you are fine with letting the user see the URL change on the browser address bar, use mod_rewrite:
<VirtualHost *>
 ServerName www.example.com
 RewriteEngine on
 RewriteCond %{HTTP_HOST} ^www.example.com
 RewriteRule ^/(.*)$ http://example.com/$1 [L,R=301,E=nocache:1]
## Set the response header if the "nocache" environment variable is set
## in the RewriteRule above.
 Header always set Cache-Control "no-store, no-cache, must-revalidate" env=nocache
## Set Expires too ...
 Header always set Expires "Thu, 01 Jan 1970 00:00:00 GMT" env=nocache
</VirtualHost>

If you want the "redirect" to be invisible to the user, use mod_proxy:
<VirtualHost *>
 ServerName www.example.com
 ProxyRequests Off
 <Proxy *>
 Order Deny,Allow
 Deny from all
 Allow from 203.0.113.67
 </Proxy>
 ProxyPass / http://example.com/
 ProxyPassReverse / http://example.com/
</VirtualHost>

It should be noted that mod_proxy, when badly configured, can harm your network.
Comment: The point of a 301 is that it's a *permanent* redirect; if you want a non-permanent redirect, you should use 302 or 307 instead.
Answer: You can add ServerAlias example.com to the VirtualHost but the performance will differ from a redirect.
Edit
Since you want to redirect and you don't need advanced functionality, it seems like using Redirect should suffice for you.  You would put the Redirect under a VirtualHost directive.
A client side solution would be to use a meta refresh tag.

mod_alias documentation
meta refresh
Comment: Can you explain a bit further? How would I redirect `www.example.com` to `example.com` using this method?
Comment: In your primary vhost, you have entries for both `ServerName` and `ServerAlias`.  One has example.com and the other www.example.com.

Then, both dns entries will access the documents specified in the same vhost.
Comment: I want to do a *redirect* though, not just an alias.
Comment: Then joshchi's recommendation may be a good approach for you.  Seems like hairs are being split at this point.
Answer: well, you could create one virtual host for the SERVERNAME www.example.com and have it redirect to another virtual host with the servername example.com

Redirect URL within Apache VirtualHost?


Efficient method parameters in Java

Question: I am still a beginner to java and I have a question on an efficient way to pass in parameters. When passing in objects in a method is it more efficient to pass in portions of an object or does it not matter at all? for example, lets say I have a Person object which has several attributes (name, height, gender, location, hairColor etc.) and I have a method which needs to work on two of these attributes. When I pass the info into the method, does it save me memory, process time etc to only pass in the needed info (like name and location) or is it the same as just passing in the whole person object?
is:
public void getNamePlace(String name, String location){
\\\\work here
}

any different efficiency-wise than:
public void getNamePlace(Person person){
\\\\work here and get the name location in the method
}

Thanks a lot for the help. I'm sorry if it is a dumb question but I'm trying to figure out the best mentality to approach this. Thank you.
p.s. I am thinking more on the method call itself. How does it work. In isolation, is:
public void getNamePlace(String name, String Location) --> More bits passed around and memory used than --> public void getNamePlace(Person person)
Comment: This is worrying about the wrong thing at the wrong time. They are both just "as efficient" and there is **no** performance issue/concern here. Period. Instead, write the code that makes more sense .. (even if  it took another kilobyte to invoke the method, but in reality it is < 8 bytes per argument, *it just wouldn't matter*.)
Comment: If you do go the composite route (ie one object), I highly recommend you make that object immutable for thread safety: http://docs.oracle.com/javase/tutorial/essential/concurrency/imstrat.html . Immutable objects are also less overhead to create (no setters).
Comment: @AdamGent I prefer immutable objects, but not necessarily for "thread safety" (most of my code does not involve threads or has strict contracts defined) nor "less overhead" (in source code it's just a template/good IDE, the Class definition is slightly bigger sure, but instantiation is the same) .. immutable objects simply make a program easier [for me] to reason about. And I am lazy.
Comment: @pst I actually didn't mean to bother you. I meant add the comment for the OP as he might not know about it. I also make immutable objects all the time for reasons other than thread-safety. And your right about the creation. I was thinking of another language (vtable-like creation in languages like Python).
Comment: @AdamGent I was just pointing out that there is a more fundamental reason to use immutable types -- not that the reasons listed aren't benefits, but there is a more immediate result: easier to think/reason about code :)
Comment: @AdamGent Tyvm. Ill look at it. Also thanks for giving me the correct term "Composite". Now I at least know what to search for.
Comment: @M1Garand I actually have no idea if "*composite*" is the official term. I have heard some say *container*. Java has lots jargon overlap. Immutable object might be a better term.
Answer: You're passing reference values. The more values you pass, the more work is being done.
Is it a measurable difference? Technically, yes–but miniscule in the extreme (e.g., another parameter is another bytecode, and that's all. Vanishingly small difference in performance and class size.)
Is it an appreciable difference? No.
The mentality here is that premature optimization, particularly at this level, isn't something to deal with.
Others have pointed out there are readability and data issues that are more important.
Comment: For a *very* small value of "measurable" that is quickly saturated into nothingness ..
Comment: Thank you all for the help. It is much appreciated. :)
Comment: Also relevant is: http://stackoverflow.com/questions/1109995/do-getters-and-setters-impact-performance-in-c-d-java
Comment: partly untrue, if the method is not inlined and having enough (depends on the CPU arch) parameters they are to be passed by the stack not CPU registers.
Answer: It "doesn't matter at all". In Java you only pass the reference of the object (as a value) to the function. It's a very small data type and it tells the VM where the object is located in memory.
Take a look at Is Java "pass-by-reference" or "pass-by-value"? for a very good answer ;)
Answer: When you use this:
public void getNamePlace(Person person){
   \\\\work here and get the name location in the method
}

nothing actually gets passed to the method except a reference (a "pointer" in a loose sense) to the actual object of type Person. No copying of members takes place, as you are instead instructing the method "you can find all you need at this memory location".
So technically passing a limited number of fields from person is actually worse than passing "the entire person" (although the difference is not noticeable anyway). :)
Answer: Objects in java are passed by reference.  The short answer is to just pass your objects.
The long answer is that object references are either 32 or 64 bits, depending on your java installation.  A 64 bit quantity is twice as large as the JVM's typical padding size (which is often 32 bits even on 64 bit systems under some circumstances).  There is a small amount of overhead associated with dereferencing the reference, but the JIT compiler will usually optimize it to a constant amount rather than a repeated hit.  Furthermore, you will always have to dereference it sometime, either inside the function or outside.  You might as well just save on the stack space and pass the object by reference.
Comment: Unfortunately "objects .. are passed by reference" (which means, based on the explicit noun of "objects" and the "ed" modifier, the reference [values] are passed) is very similar to "pass by reference" or "call by reference" which means something else .. for this reason I try to avoid the phase, except when I am talking about "call by reference" semantics.
Comment: @pst: Great distinction, I'll delete my comment.
Answer: You're passing around an extra address using getNamePlace(String,String) instead of getNamePlace(Person).
Java will not make a copy of the Person object when passing it; it passes the reference.
Similarly, Java will not make a copy of the Strings when passing them; it passes the references.
Will you notice a significant performance difference? No.
Answer: It doesn't matter at all considering time and efficiency.
But it does matter if you want to write readable code. - It's always nice to group logically connected items, as object that they represent
for example:
writeLetterTo(person);

is much better than that:
writeLetterTo(name, surname, address, city, country);

if only all those parameters can be taken somehow from person object.
Another example:
addTwoPionts(x1, x2, y1, y2); // ugly
addTwoPoints(point1, point2); // far better

Comment: It goes beyond just readable code.  If you wanted to enforce certain constraints on those values from within the Person class, you could no longer do that because you have just given away your data.  Also, primitives aren't passed by reference, so if those parameters were modified in the function and should be reflected in the Person instance, that can no longer happen.  There is a much bigger difference between passing in an Object which has data members, and just directly passing in the data members themselves.
Comment: @kurtzbot you're definitely right, so thanks for metioning it. Anyway side effects in methods should be avoided.
Comment: @kurtzbot Consider making your comment an answer. I'll proudly upvote it :)
Answer: Apart from the method parameters, there are a couple of things you should tweak:
public void getNamePlace(Person person){
    \\\\work here and get the name location in the method
}

to get the habits right

getNamePlace method name when it returns nothing is not convention compliant. getXXXX should return the value.
Since getNamePlace will operate on Person so it should be defined in the class itself and then you need not to pass any parameters.
Finally to answer your question, you shouldn't bother too much about such micro-optimization so initially in language learning graph... It hardly makes any difference.
Comment: Ok, thanks for the help. was just trying to get it down. Really didn't expect much traffic on this one. Thank you I will remember that. Though it is apparent the efficient difference is very small I asked more as a "how does java actually work?" I am trying to learn more about the guts of Java and not just save a nanosecond.
Comment: @M1Garand, those advices are beyond Java as single language. They are common to all (I hope!) programming languages, so remember them well :).
Comment: Good to know. I will heed the advice. Thank you both.
Answer: I personally wouldn't be too concerned with this. If you are really concerned with performance that much you probably should look at using a lower level language. As others have said, there isn't really any performance difference between the two especially when it comes to just passing variables.
If you are truly having performance issues I would suspect there are many other places in your code that are slowing you down instead of parameter passing.

Efficient method parameters in Java


Windows 10 stalling print queue on Server 2012

Question: When our Windows 10 devices print from Microsoft Edge the print hits the Window Server 2012 print queue, and just hangs at printing/spooling. This goes on until I manually clear the queue, and restart the print-spooler. As far as I have seen, the only program with printing issues is Edge.
Is this a driver issue? Where does one start fixing this?
Answer: As I suspected the driver was the culprit.
I updated the driver and waited for a good time to test. After swapping the driver on the print server there were no more problems and the queue has not stopped since!


Can two or more classes send data to the same IntentService?

Question: I'm a beginner in Android programming, and I was reading about handling time consuming operations via IntentServices. However, I have this doubt -
Can I have two classes (say A and B) issuing a call to the same class (C) extending the IntentService? Is this possible and/or safe?
If so, how do I help the IntentService differentiate between the two calling classes?
I was thinking of this way:
public class DoSomething extends IntentService{
    @Override
        public void onHandleIntent(Intent intent){
            Bundle data = intent.getExtras();
            String type = data.getString("TagForClass");
            if(type.equals("TagForClassA")){
                //Do operations for Class A
            }
            else if(type.equals("TagForClassB")){
                //Do operations for Class B
            }
        }
}

Will this method work?
Answer: Yes, multiple classes can send intents to the same IntentService. Internally, the different calls are queued and processed one by one by the service.
There is something alarming about your use - case. If you need to completely switch the service logic based on the calling class, it would be better to have two distinct services, each one completing a single, well - defined task.


Is there any way to Support UDP Stream in ROKU?

Question: My video file Format is MPEG. I play HTTP(https://l1uqyex-i.akamaihd.net/hls/live/856741/livestreamC/video1.m3u8) File It's Working Fine. But I Store in Locally(pkg://images/Video1.ts) and use UDP(udp://email@example.com:8510) Stream But It's Not Working. Is There Any way to Support UPD Stream on Roku.
Answer: Roku supports HTTP streams only. It doesn't support UDP or any other protocols for streaming video content. Check the sdk documentation for streaming specifications, somewhere you will find it for sure.
Comment: I read all the documentation. probably, not possible, but I think I try with roStreamSocket and see if I can assemble the incoming data into something playback. It would still need to be h.264.
Comment: roStreamSocket is to connect to TCP streams not UDP.  If you want to try, try it with roDataGramSocket.
Comment: Is there any way to supply decryption key to player.
Comment: Hi Nikunj, there is no build-in component in roku to handle epg. Actually epg is custom component. If you want to use it in your channel, you will have to take prior permission from roku team.  They will review you request and inform you accordingly whether you can use it in you channel. Although you can build custom component to handle epg, but it will not be an easy task. Organizations spends months to develop this type of components. Recently roku added some custom components(SGDEX). Although I didn't tried it yet, but I think its possible to implement epg grid using TimeGridView.
Comment: Yes this is also same thing, but its custom build component. They are not using roku's epg component.


How to handle simultaneous transactions in mysql with Java?

Question: Have an API that responsible for top-up mobile numbers. To use the top-up API firstly user should register and that stage allocate some credit(BALANCE) to the user.
When make a call to the API with mobile number and top-up amount that amount will subtract from the particular users account balance (Update the balance).
Problem is when a user top-up X mobile and again in the same time Y mobile number.
What are best ways to handle these kind of transaction with JAVA and MySQL(Database).
Answer: You have different ways to achieve this.

The easiest one in my opinion is to use optimistic looking: https://www.baeldung.com/jpa-optimistic-locking
Other more complex way is to use Actors. It probably involve a change in the architecture of your app and new frameworks to use but it definitely payoff. An actor receive events (for example, BalanceUpdate) and ensures that all messages are processed in order, you can have an Actor per user and the trick is made rooting all the messages related to an user to his actor. Check frameworks like Akka or Vert.X
Comment: Thanx pall very helpful information. Hope to try Pessimistic Locking and Optimistic Locking with my scenario angin thanx.


Appropriate regression-like model where the response is on half-integers

Question:
What is an appropriate model for the above scatter plot? I am not fully satisfied with a simple linear regression model. Any suggestions? Y in this problem is discrete in nature. It only increments by 0.5.
Comment: It is *very* curious that the vast majority of responses are actually whole numbers and not half-integers.  This suggests that the responses are favoring whole numbers.  Could you say more about what these responses are and help us understand this very strange behavior? Also, are the values of the independent variable set by the experimenter or are they also observations (and therefore perhaps need to be modeled as random variables, too)?
Comment: deb, that useful information would be best mentioned in your question as well; people shouldn't need to read comments to know that.
Comment: My depend variable is change in price. Here prices are recorded up to 0.5 cents. Hence the behavior.
Comment: Related question: http://stats.stackexchange.com/questions/21058/how-to-fit-a-regression-like-y-lfloor-axb-rfloor-in-r/
Answer: You could modify your linear function with applying floor/ceiling on your dependent variable (see Wikipedia).
This way you would get a discrete step function that mimics your data (see image below).

Given your regression function $y = 0.009x - 0.002$, you have to transform it in the following way: $y = ⌊0.009(x+offset) - 0.002⌋$ and select the $offset$ in a way that maximizes your fit, probably somewhere around $50$.
A more general (and complicated) solution would be to define constant linear functions for every possible Y-value. Then, you have to select intervals on the X-scale to specify where you use each of your constant functions in order to maximize your fit. Obviously, not all constant functions will be used.
Given your plot, I would select something like this (as a rule of thumb):
$$
f(x) = \left\{
  \begin{array}{l l}
    -2 & \quad \text{x < -150} \\
    -1 & \quad \text{-150 <= x < -25} \\
     0 & \quad \text{-25 <= x < 50} \\
     1 & \quad \text{50 <= x < 125} \\
     2 & \quad \text{x >= 125} \\
  \end{array} \right.
$$
Comment: How exactly would you fit data to this model and why would it work at all well?  What assumptions would you make about the residuals?
Comment: I am also not sure how the model you described would work. Can you please explain in little more details?
Comment: OK, I have updated my answer with two possible procedures.


Note placement for beat/rhythm clarity

Question: I have been transcribing a piece in 4/4 time for the piano. I am not fully certain as to how I should format the notes on the upper staff – as they split every beat.
I have provided 3 options below for how I think this could be formatted, but am unsure which is best (or if there is an even better way to do so that I am not aware of).

More generally, is it necessary for the notes on both staffs to clearly show every beat?
Comment: At the risk of making this seem opinion based, I think the first one is most readable. It clearly shows the syncopation also. I would have no problem sight reading that rhythm. The third one is a firm no. Having read the comment about staccato I wonder why not just make all the upper notes eighth notes?
Comment: It is a bit weird to have staccato on a tied note, but in this case, since the surrounding notes will be quarter notes, your meaning will be perfectly clear and shouldn't give cause for objection. (And for anyone who complains, just tell them that Chopin sometimes puts staccatos on half-notes.)
Comment: All three measures shown should be written rhythmically as measure 2 is. The half-measure should always be clear, but it's not necessary (in this example, at least) to show every single beat.
Comment: Let's look at intent here: basically you want to have 2 sets of 4th notes, with the upper ones following an 8th later, and playing staccato? If you want to spell them out as 4th notes, you need to be consistent and replace the 8th rests with tied notes too and use staccato on the tied half notes (as Aaron wrote) - or you could go the more pragmatic road and replace the upper 4th notes with 8ths and get rid of all the ties (as Todd wrote) Personally I'd go for the 8ths, since this is piano.
Comment: @Tim This is standard for chromatically rising/falling lines: sharps when ascending chromatically; flats when descending chromatically.
Comment: Which notation program is this? To me the eigth rest & the flat in the right hand are too close together.
Comment: @Aaron Thank you so much! I also need to put staccato on all notes in the upper staff. Would this still be okay to do so if it is written rhythmically with a tie? I have seen quite a bit of resistance to the notation of a tie and staccato together.
Comment: Interesting that you use flats for r.h. and sharps for l.h. Why? And Todd's suggestion of short notes rather than staccato (effectively the same) is going to make it more easily read.
Comment: @Aaron - yeah, just remembered, it eliminates (to a degree) using the cancelling natural signs. Doh!
Comment: @VictorEijkhout I'm using Musescore (Version 3.6.2 as of now). I find the exact same thing. It oddly compressed some aspects of each measure here making it look kind of congested in the right hand.
Comment: I'll have to see what Lilypond does. I usually find its output quite a bit prettier than MuseScore. It has other disadvantages though.
Comment: Is this just for yourself?  For a friend?  For a teacher to evaluate you?  Things are notated more sloppily for a pit orchestra than for a symphony orchestra.
Answer: Of the options you have provided, the first is the best as the syncopation is clearest.  But you'd probably want make the final note in the upper staff tied across the bar line (so that it gets played with the same length as all the other notes).
It is not explained why you have two staves in bass clef, or why this passage of notes is represented jumping between staves.  There could be a good reason for this, but perhaps there isn't — as one hand can play this passage alone.

Changing all of the crotchets (quarter notes) to quavers (eighth notes) will makes a difference to how it sounds, (which might not be what you want to hear), but it certainly clarifies the rhythm.
Here are four more options using only quavers, all of which I would suggest are much more clear than the options you have provided:

The second option (my preference) is nice as it gets rid of all the visually noisy rests, and keeps the ascending and descending chromatic voices (hands) separated.
The third option (my other preference) is perhaps the easiest to read, but doesn't separate the voices in any way — this leaves the choice whether to use one or two hands up to the performer (which could be a good thing).
Comment: I'd go for option 2 for the reasons you give and also because the flats are in one hand and the sharps in the other. And it'll still be clear when OP has marked the RH notes as staccato.
Comment: If I saw option 3, I would wonder why there's no whole rest for the right hand. Option 4 to me is archaic. I greatly prefer two staves in bass clef when both hands are playing low. The only time moving the right hand down (or left hand up) and preserving the clefs is justified is when there is a run or phrase that quickly goes low to high or high to low, since it makes the "shape" of the music more readable. This isn't only my opinion, it's supported both by publisher styles and scholarly recommendations (e.g., Elaine Gould).
Comment: Regarding option 3, I would interpret it to mean the composer wants me to play the whole figure with my left hand, *especially* if there's a whole rest in the upper staff. I would wonder *why*, and I might take artistic liberty and play it with both hands. But that's what 3 looks like to me: left hand only. 4 says use both hands down low but again I'm only used to seeing that in old editions and/or ones that are trying to adhere closely to the manuscript. And composers are not necessarily great engravers.
Comment: @ToddWilcox you're right, options 3's upper staff does deserve a whole bar rest.
Answer: Versions 1 and 2 are both acceptable: version 1 is readable because the syncopation is simple, version 2 clearly shows the middle of the bar. There is no other good option.
Note the stem on the E-flat should be down in each case.
Also, since this is easily playable with one hand, it might be a good idea to notate it as such (on one staff).

Note placement for beat/rhythm clarity


Setting ALLUSERS in WiX for per-user or per-machine installation context

Question: I use WiX 3.5. My installer should enable both per-user and per-machine installation. I would like to achieve that by using radio buttons ("Everyone" and "Just me").
I found a couple of references on the Internet:

Selecting current-user or all-users install: Adding a user interface, part of Yet Another WiX Tutorial - Part 2 - Adding the UI.
Set the ALLUSERS property to an empty string: Using WiX 3.0 to create a per-user MSI that does not prompt for elevation on Windows Vista

If I understand that correctly my installer should set ALLUSERS property to 1 for per-machine installation and to "" (empty string) for per-user installation.
My problem is no matter what I try ALLUSERS is always set to 1. Even when I don't set it at all!
Here is a couple of things I tried:
<Control Id="UserSelection"
         Type="RadioButtonGroup"
         X="26"
         Y="115"
         Width="305"
         Height="45"
         Property="ASSISTANCE_USERS"
         Text="ASSISTANCE_USERS">
    <RadioButtonGroup Property="ASSISTANCE_USERS">
        <RadioButton Value="cur"
                     X="0"
                     Y="0"
                     Width="295"
                     Height="16"
                     Text="Just me" />
        <RadioButton Value="all"
                     X="0"
                     Y="20"
                     Width="295"
                     Height="16"
                     Text="Everyone" />
    </RadioButtonGroup>
</Control>

and then setting the ALLUSERS based on ASSISTANCE_USERS:
  <Publish Property="ALLUSERS"
           Value="{}">ASSISTANCE_USERS = "cur"</Publish>
  <Publish Property="ALLUSERS"
           Value="1">ASSISTANCE_USERS = "all"</Publish>

However, ALLUSERS is always 1.
I also tried just setting ALLUSERS to an empty string:
<Property Id="ALLUSERS" Secure="yes"/>

This should set ALLUSERS to "", yet it stays "1"
Once I'm able to set ALLUSERS, I should be able to use HKMU for per-user and per-machine installtion.
Answer: Check a verbose log (using /l*vx): MSI logs every property change so you can see when ALLUSERS is being set.
Comment: Nothing else in WiX sets ALLUSERS. If you're using any third party libraries or merge modules, they're a likely source.
Comment: Then ALLUSERS is set in your .msi's Property table. Are you using Package/@InstallScope?
Comment: Thanks @Bob! Yes, I use merge module to include VC Redistributables.       ``. This merge module sets ALLUSERS to 1. I also succeeded to change ALLUSERS to "" by using the approach from [http://www.merlinia.com/mdt/WiXTutorial2.msl]
Comment: Hi Bob, that's exactly what I did. There is only one line in the log: Property(C): ALLUSERS = 1
Comment: I just check out you [blog](http://www.joyofsetup.com/2008/04/01/new-wix-feature-setting-package-installation-scope/). I didn't use Package/@InstallScope. When I try InstallScope="perUser" I still get ALLUSER=1. Documentation says that setting InstallScope="perMachine" sets ALLUSER to 1. Should InstallScope="perUser" set ALLUSER to ""? What else could set ALLUSERS to 1?


Corrupted State Exception types other than AccessViolationException

Question: What Corrupted State Exception types, other than AccessViolationException are possible?
In particular, is it safe to assume that none of OutOfMemoryException, ThreadAbortedException, SEHException, RuntimeWrappedException, etc. require the use of HandleProcessCorruptedStateExceptionsAttribute to be caught, say, by a catch (Exception) clause?
I'm interested even in examples, guesses, approximations, of what exception types are sometimes or always treated by the CLR as a CSE.  Existing web resources give the appearance that CSE is a near-synonym for AccessViolationException, but I suspect that this might be too inaccurate even for my modest needs.
I need to know, whenever I notice a catch (OutOfMemoryException) (or another construct explicitly dealing with other low level exceptions) in ancient code I'm peripherally responsible for, whether the exception handling code could have been made unreachable, or is at risk of becoming unreachable, by migration to .NET 4.
So far my best bet was to scan Microsoft documentation of the exception type for a mention of HandleProcessCorruptedStateExceptionsAttribute, but I wonder whether this detail of behavior is even supposed to be fully compatible across all .NET 4 versions, and/or thoroughly documented for every managed exception type affected by the CLR change.
Answer: I'm not sure if there even is a finite set of exceptions (regardless of CLR versions, but in general).
At least native code (or the CLR itself) could raise any exception, designating it as corrupting state, if you look at this CLR function.
   // Signature simplified for purposes of that answer, check link above for actual signature.
   void RealCOMPlusThrow(OBJECTREF throwable, CorruptionSeverity severity = NotCorrupting);

That function (i.e. the macro COMPlusThrow that wraps it) is called in multiple places in the (Core) CLR.
The function IsProcessCorruptedStateException function seems to be ultimately used to determine if an exception is considered state corrupting. This function has two "overloads".
One is rather helpful, because it lists the following exception codes:
    STATUS_ACCESS_VIOLATION
    STATUS_STACK_OVERFLOW
    EXCEPTION_ILLEGAL_INSTRUCTION
    EXCEPTION_IN_PAGE_ERROR
    EXCEPTION_INVALID_DISPOSITION
    EXCEPTION_NONCONTINUABLE_EXCEPTION
    EXCEPTION_PRIV_INSTRUCTION
    STATUS_UNWIND_CONSOLIDATE

At least paritially they map to .NET exception objects.
However, the other one "simply" checks if the exception object (native, not managed) has been marked was state corrupting.
Now, I'm far far far away from being an expert with the CLR's code, so YMMV.
One can surely spend hours in the CLR code to figure out how corrupted state handling works and what consequences that has for handling those in C# code.
But depending on what you are really trying to achieve by your question that
might lead to some serious yack shaving. ;-)
Comment: This was extremely helpful.  I learned from you that "corrupted process state" was a pre-existing concept orthogonal to the SEH (or managed) exception type.  I received a much better approximation of the type of conditions when it hits, and (from noticing CorruptionSeverity.ReuseForReraise in the CLR code), that its travel within the process across Reflection and AD boundaries is also optional, with TargetInvocationException another example of a potential CSE, and I'll post a particularly valuable lesson about OutOfMemoryException as a separate Q+A pair.
Comment: Separate Q+A pair [created](https://stackoverflow.com/questions/55652300/is-handleprocesscorruptedstateexceptionsattribute-needed-for-catching-outofmemor) as promised.


Is there a better way to show another form?

Question: Whenever I need to show another Form, I always instantiate a new Form Object to show another Form (then hiding the current form).
/*Code in Form1*/

private void button1_Click(object sender, EventArgs e)
{
    Form2 frm2 = new Form2();
    frm2.Show();

    this.Hide();
}

After I instantiated and showed the second Form, I want to dispose the previous form (to free up some memory usage) but it is not working on the main context form.

However, the Dispose() method is working on other WinForms which is
  not the main context form.

/*Code in Form2*/

private void button1_Click(object sender, EventArgs e)
{
    Form1 frm1 = new Form1();
    frm1.Show();

    this.Dispose();
}

Is it possible to instantiate a Form Object once only, then eventually to call/show it whenever I need it?
Answer: You can start your own ApplicationContext, and pass that to every form you want to make the MainForm. You shouldn't keep forms in memory and open and close them at will in my opinion. This could lead to potential memory leaks.
ApplicationContext ac = new ApplicationContext();
ac.MainForm = new Form1(ac);
Application.Run(ac);

(You will put this in the place of Application.Run(new Form1());)
In Form1, when you want to make Form2 the main form:
ac.MainForm = new Form2(ac);
this.Close();

This way, the form can be disposed (since you called Close() and used Show it will automatically dispose) and memory can be cleared. The instance of Form2 will be the new main form.
Answer: /*Code in Form1*/
Form2 frm2;   // --> Inside the class
private void button1_Click(object sender, EventArgs e)
{
    if (frm2 == null)frm2 = new Form2();
    frm2.Show();
    this.Hide();
}

.
/*Code in Form2*/
Form1 frm1;

//Constructor
public Form2(Form1 frm)
{
     frm1= frm;
     InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
    frm1.Show();
    this.Hide();
}

Answer: I would create a class called "FormHandler"
this may have a method like
here some prototype code (not tested)
public static class FormHandler
{
   private static readonly Dictionary<string,Form> Instances = new Dictionary<string,Form>();

   public TForm CreateFrom<TForm>()
   {
      string typeName = typeof(TForm).FullName;

     if(Instances.ContainsKey(typeName))
     {
          return Instances[typeName]
     }
     else
     {
       // Create Instace with Activator.CreateInstance,
       // and bind the dispose event to remove the form from the collection
       // on dispose . Also make sure that you unbind the dispose Event
       [...]
      }
}

Now the buttonClick would just call
FormHandler.CreateForm<Form2>().Show();

with seperating the code to a new class you can avoid copy and paste in all buttons


Down-set closure of subsets

Question: I am confused by the following statement in my lecture notes on down-set closure of subsets: "The family of down-sets containing a given subset $E \subseteq S$ is nonempty since $E \subseteq S$ and $S$ is a down-set.  It follows that the intersection of all down-sets containing E,
$$Cl^\downarrow(E):= \bigcap_{L \supseteq E} L,$$
is the smallest down-set containing E.
This is confusing to me because isn't $Cl^\downarrow(E)$ simply equivalent to $E$ if only everything in $E$ is is common to all $L$'s?  Furthermore, if so, why then isn't $E$ also the smallest down-set containing $E$?  (Of course in the case that there's more in common between the $L$'s than just $E$, then it is even clearer that $E$ would be the smallest down-set containing itself, right...?)
Answer: To answer the last question first, $E$ cannot be the smallest downset containing $E$ if $E$ is not a down-set in the first place. Consider the set $E=\{1,3\}$ in $\Bbb Z$, the set of integers, with its usual ordering: $E$ is clearly not a down-set, since, for instance, $0\le 1\in E$, but $0\notin E$. For each $n\in\Bbb Z$ let $D(n)=\{k\in\Bbb Z:k\le n\}$; then $D(n)$ is a down-set, and every non-empty down-set is either one of these sets $D(n)$ or $\Bbb Z$. So what down-sets contain $E$? It's not hard to see that $D(n)\supseteq E$ if and only if $n\ge 3$: $D(3),D(4),D(5),\ldots$ all contain $E$, and $D(2),D(1),D(0),\ldots$ do not. Of course $\Bbb Z\supseteq E$, so
$$\begin{align*}
\operatorname{Cl}^\downarrow(E)&=\bigcap\{L\subseteq\Bbb Z:L\supseteq E\text{ and }L\text{ is a down-set}\}\\
&=\Bbb Z\cap\bigcap_{n\ge 3}D(n)\\
&=D(3)\;,
\end{align*}$$
since $D(3)\subseteq D(4)\subseteq D(5)\subseteq\ldots\subseteq\Bbb Z$. In other words, the down-set closure of $\{1,3\}$ is $D(3)=\{k\in\Bbb Z:k\le 3\}$, the set of all integers less than or equal to $3$; a little thought should convince you that this really is the smallest down-set containing $\{1,3\}$, and it's certainly not equal to $\{1,3\}$.
This example is especially simple because this partial order is actually a linear (or total) order; this makes the down-sets very easy to describe, and it makes it very easy to see what the smallest down-set containing a given set is. However, the definition works as claimed in any partial order. I'll expand what's in your notes a bit to try to make this clearer.
If $\langle S,\le\rangle$ is any partial order, then $S$ is a down-set: this just means that if $x\le y\in S$, then $x\in S$, which is certainly true. Now let $E$ be any subset of $S$, and let
$$\mathscr{D}=\{D\subseteq S:D\supseteq E\text{ and }D\text{ is a down-set}\}\;;$$
we've just seen that $S\in\mathscr{D}$ — it's a down-set, and it contains $E$ — so $\mathscr{D}\ne\varnothing$. Your definition of the down-set closure of $E$ then says that $\operatorname{Cl}^\downarrow(E)=\bigcap\mathscr{D}$. To show that this is the smallest down-set containing $E$, we have to show three things:

it contains $E$;
it's a downset; and
if $D$ is any down-set containing $E$, then $\operatorname{Cl}^\downarrow(E)\subseteq D$.

(1) is easy: $\operatorname{Cl}^\downarrow(E)$ is the intersection of sets that all contain $E$, so $\operatorname{Cl}^\downarrow(E)\supseteq E$.
(2) isn't much harder. Suppose that $x\le y\in\operatorname{Cl}^\downarrow(E)$. Then for each $D\in\mathscr{D}$ we have $x\le y\in D$, and since $D$ is a down-set this implies that $x\in D$. Thus, $x$ is an element of every $D\in\mathscr{D}$, and therefore $x\in\operatorname{Cl}^\downarrow(E)$; this shows that $\operatorname{Cl}^\downarrow(E)$ is a down-set.
(3) is very easy: if $D$ is a down-set containing $E$, then $D\in\mathscr{D}$, so $\operatorname{Cl}^\downarrow(E)=\bigcap\mathscr{D}\subseteq D$.
In short, $\operatorname{Cl}^\downarrow(E)$ is exactly what was claimed: the smallest down-set containing $E$, smallest in the sense that it's a subset of every down-set that contains $E$.
If $E$ is itself a down-set, then of course $E\in\mathscr{D}$, and in that case we have
$$E\subseteq\operatorname{Cl}^\downarrow(E)=\bigcap\mathscr{D}\subseteq E$$
and hence $\operatorname{Cl}^\downarrow(E)=E$, but this happens only when $E$ is a down-set to begin with.
Comment: Wow, this is incredible.  Thank you for so thoroughly and clearly answering my question...you have really shown me the light, and the error of my ways, here; in particular, I guess I need to be careful with incorrectly assuming too much.  Thanks so very much again for a most beautiful answer.
Comment: @confusedmike: You're very welcome; I'm glad that it helped.

Down-set closure of subsets


Localizar linha que se inicie com negação da expressão

Question: Eu possuo um arquivo de texto com muitas linhas. É possível eu encontrar a primeira linha que não case com a regex? Exemplo, quero fazer uma regex que me mostre a primeira linha que não comece com BOLO
BOLO
BOLO
CHOCOLATE
Estou usando o sublime, ou seja, minha regex tem que achar a palavra CHOCOLATE. Lembrando que minha regex precisa ser em cima da palavra BOLO porque não sei qual a linha que vem após.
Answer: Combine a ancora (^) de início com o lookhead negativo (?!) isso vai identificar as linhas que não começam com BOLO
^(?!BOLO)

Texto:
BOLO
BOLO
CHOCOLATE
RECEITAS BOLO

Esse exemplo casa as duas últimas linhas.
Veja funcionando no REGEX101
Comment: Obrigado, deu certo.


Bind9 warning on Debian

Question: I'm running a Bind9 (9.8.4-rpz2+rl005.12-P1) DNS on a Debian 7.9 server and all is working fine, but whenever I try to restart the named service I get the following error into syslog:
WARNING: key file (/etc/bind/rndc.key) exists, but using default configuration file (/etc/bind/rndc.conf)
named-checkconf command does not give me any error.
Since I don't want my DNS stop working prior to do anything I would like to have some tips from someone that knows better than me how can I get rid of this warning or if I should ignore this message.
Answer: The warning is telling you that you have an rndc.key configuration file (possibly/probably left over from an older version) but it's not being used.  The default configuration file rndc.conf is what bind is actually using for its configuration.
Comment: @Iain 1010 to go!  Yay for REMAAS...
Comment: You should do this more often.
Comment: So if I remove or rename the /etc/bind/rndc.key I should get rid of that warning message?
Comment: Yes.  p.s. you can accept this answer if you find it useful by clicking the check mark.
Comment: That'll be just 996 now then.
Comment: Fixed my warning and checked your answer ;-) Thanks!

Bind9 warning on Debian


Two-way bind não funciona se o model for algo como ng-model="record.name" para os Kendo UI controls

Question: Tenho um problema com o Kendo UI controls
meu HTML
 <input type="text" ng-model="record.name" kendo-numeric-text-box />
 <input type="text" ng-model="record.name"> </input>
 <button ng-click="resetRecord()" >test bind</button>

meu test.js
$scope.record ={};
$scope.resetRecord= function(){
        $scope.record = {};
    }

Quando executo a função resetRecord somente o input padrão limpa o seu conteúdo, os input do Kendo UI não limpa, eu tentei $scope.record =null mas não funciona também.
Se eu mudar o código abaixo, ele funciona, mas eu preciso que ele funciona como acima.
$scope.resetRecord= function(){
        $scope.record. name = null;
    }

Isso acontece com todos os Kendo UI input, não somente com o kendo-numeric-text-box
Se existir uma maneira de interagir com o objecto  record, descobrindo todas as suas propriedades, como name dava certo pra mim.
Minha intenção é somente ter um controlador para todas as telas crud do sistema, eu não gostaria de escrever um controlador e a definição do modelo para cada entidade do sistema.
Será um bug?
Answer: A solução é apenas adicionar o atributo k-rebind
<input type="text" ng-model="record.name" k-rebind="record.name" kendo-numeric-text-box />

Two-way bind não funciona se o model for algo como ng-model=“record.name” para os Kendo UI controls


PHP 301 redirect location URI format

Question: Is this a correct URI for the header('Location: '), specifically ./?
header ('HTTP/1.1 301 Moved Permanently');
header ('Location: ./');

Thank you.
Comment: You should use an absolute URI. See: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.30
Comment: Are you trying to add a trailing slash to URLs? There are better ways to do that.
Comment: I'm trying to redirect permanently from the file that contains that code to the default file (index.something) that's contained in the same folder as the initial file that did the redirection.
Answer: You can also use:
header('Location: /', false, 301);

I assume you want to redirect to the 'homepage', that'd be / instead of ./
Comment: According to the standard, an absolute URL is required. This will work, but is not valid
Comment: As @Pekka mentioned see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.30
Comment: Hi, I want to redirect to the root of the folder where the file that contains that code resides. In this particular case it is the root of the site as well. I'm worried because I read HTTP/1.1 requires absolute path.
Comment: I see. So is there a `real` risk by using `./` or `/`?
Comment: Thanks for the comments, didn't know an absolute url was required. Upvoted the correct solution.
Answer: You must use an absolute URI according to the spec so something like the following should work for you:
// check if the server is secure or not to determine URL prefix
if(isset($_SERVER['HTTPS']) and 'on' === $_SERVER['HTTPS']) {
    $location = 'https://';
} else {
    $location = 'http://';
}

// get the servers base URL
$location .= $_SERVER['SERVER_NAME'] . '/';

// grab the current URI without a file name in it
$location .= dirname($_SERVER['REQUEST_URI']) . '/';

header('Location: ' . $location);
exit();

PHP 301 redirect location URI format


RAID 5 Online Capacity Expansion sector size changed

Question: I just started RAID 5 Online Capacity Expansion, and noticed sector size went form 4K to 512B. Could this be a problem?`I did not a have a sector size option when adding the disk.. Running on HighPoint RocketRAID 2300 controller.
Answer: You will lose a bit of diskspace efficiency in this situation.
Consider the following scenario.  You have a .txt file saved to the drive.  It parks in a 512Byte block size and is only 200Byts.  It takes up the entire spot.  Smaller block sized lend to more efficient use of space and larger block sizes tend to have a higher level of performance.  You can format a VMFS VMware volume with 4Mb bock sizes and the performance is excellent but, quite a bit of space is wasted.
In terms of space efficiency, smaller allocation unit sizes perform better. The average space wasted per file will be half the chosen AUS (allocation unit size). So 4K wastes 2K per file and 64K wastes 32K.  If you have lots of small files, then it's a good idea to keep the allocation size small so your harddrive space won't be wasted. If you have lots of large files, keeping it higher will increase the system performance by having less blocks to seek.


How to prove this inequality $\frac{x^y}{y^x}+\frac{y^z}{z^y}+\frac{z^x}{x^z}\ge 3$

Question:
let $x,y,z$ be positive numbers, and such $x+y+z=1$

show that
$$\dfrac{x^y}{y^x}+\dfrac{y^z}{z^y}+\dfrac{z^x}{x^z}\ge 3$$
My try:

let
  $$a=\ln{\dfrac{x^y}{y^x}},b=\ln{\dfrac{y^z}{z^y}},c=\ln{\dfrac{z^x}{x^z}}$$
  so
  $$a=y\ln{x}-x\ln{y},b=z\ln{y}-y\ln{z},c=x\ln{z}-z\ln{x}$$
  and we note
  $$az+bx+yc=(y\ln{x}-x\ln{y})z+(z\ln{y}-y\ln{z})x+(x\ln{z}-z\ln{x})y=0$$
  so
  $$\dfrac{x^y}{y^x}+\dfrac{y^z}{z^y}+\dfrac{z^x}{x^z}=e^a+e^b+e^c$$
  so
  $$\Longleftrightarrow e^a+e^b+e^c\ge 3$$
  But then I can't prove it.

If this problem is to prove
$$ze^a+xe^b+ye^c\ge 3,$$
I can prove it,because
$$ze^a+xe^b+ye^c\ge=\dfrac{z}{x+y+z}e^a+\dfrac{x}{x+y+z}e^b+\dfrac{y}{x+y+z}e^c$$
so
use Jensen's inequality,we have
$$ze^a+xe^b+ye^c\ge e^{\dfrac{az+bx+yc}{x+y+z}}=3$$
This problem comes from How prove this $\dfrac{x^y}{y^x}\ge (1+\ln{3})x-(1+\ln{3})y+1$?
Thank you very much!
Comment: without $x+y+z=1$, the equality is OK also.
Comment: $ze^a+xe^b+ye^c\ge e^{\frac{az+bx+yc}{x+y+z}}=1$
Comment: why without this problem is also?
Answer: Another solution.
Without loss of generality, we can assume that $0<x\le y\le z$ and so $x=az$, $y=bz$, $0<a\le b\le1$. By the AM-GM inequality, we find that
\begin{align}
\frac{x^y}{y^x}+\frac{y^z}{z^y}+\frac{z^x}{x^z}&\ge 3\sqrt[3]{x^{y-z}y^{z-x}z^{x-y}}=3\sqrt[3]{(az)^{(b-1)z}(bz)^{(1-a)z}z^{(a-b)z}}=3\sqrt[3]{a^{(b-1)z}b^{(1-a)z}}=\\
&=3(a^{b-1}b^{1-a})^{z/3}
\end{align}
so we only need to prove that $a^{b-1}b^{1-a}\ge1$, which Hansen did in the answer below. We also see that the condition $x+y+z=1$ is not needed.
Comment: The second solution is wrong. $b\log(a)0,\,\forall a<b<1$.
Comment: @IanMateus: I did this because I did not want to claim credit for the solution as the main idea was Karl Marx'. But if writing a new answer is the protocol, I will do so.
Comment: @Hansen It's been a while since you warned him, you surely can do it :-)
Comment: The Hint part is wrong. The minimum of the right hand side is $1$ not $3$.
Comment: Please note the objection from @yegulalp below. It unfortunately invalidates the proof premised on the invariance over variable permutation. Do you have any idea mending the proof or for a new one?
Answer: This is to prove $a^{b-1}b^{1-a}\ge 1$ as needed in Ron Ford's answer above. Let $f(b)=(1-b)(-\log a)-(1-a)(-\log b)$, $b\in [a,1]$. $f(a)=f(1)=0$. $f$ is concave, as $f''(b)=-\frac{1-a}{b^2}<0$. So $f(b)>0,\,\forall b\in(a,1)$ and the result follows.
Comment: No problem. I like your solution.
Answer: The inequality as posed in the OP appears to be correct.  The accepted proof (Ford/Hansen) is not.
Note that the proof doesn't require the assumption that $x+y+z=1$.  Take $x=6$, $y=2$, and $z=1$.  Then the left side is ${36\over 64} + 2 + {1\over 6} =  2 + {35\over 48} < 3$, violating the inequality.  Clearly the proof cannot be correct as stated.
The error in the Ford/Hansen proof is the assumption we can take $x \leq y \leq z$.  This is not generally possible because the LHS of the inequality is not invariant to permuting any pair of the variables.  Note that if we swap $x$ with $y$, the first term becomes its own reciprocal and the second and third terms become each other's reciprocals:
Define
$$A = x^{y}/y^{x}, B = y^{z}/z^{y}, C = z^{x}/x^{z}.$$
Exchanging $x$ with $y$ makes $A \rightarrow 1/A$, $B \rightarrow 1/C$, and $C \rightarrow 1/B$.
Furthermore, no proof using the AM-GM inequality can work.  Applying AM-GM we get:
$$ A + B + C \geq 3(ABC)^{1/3}.$$
If $ABC < 1$, we can't finish the proof.  If $ABC > 1$, then consider the case where we swap $x$ and $y$:
$$ A^{-1} + B^{-1} + C^{-1} \geq 3(ABC)^{-1/3}$$
Unless $ABC=1$, the bound is insufficient in one of the two cases above to prove the desired result. If the bound works for a given $x$, $y$, and $z$ then it won't suffice for the case where we swap $x$ and $y$.
Comment: I've removed the erroneous statements and numerical example to which Daniel responded.
Comment: Your objection is correct. Any ideas for a proof or counterexample? Is the reason you say this inequality "appears to be correct" some numerical verification?


onload não funciona com setTimeout

Question: Estou a horas tentando organizar esse script de acordo com a minha necessidade, a questão é que preciso que o script carregue somente quando toda a pagina carregar e para isso temos o onload.. bom porem quando eu insiro o onload não funciona... outra questão, estou tentando fazer com que apareça o botão curtir do Facebook ao final da contagem que no caso do código irá mostrar o 00 porem gostaria de inserir um iframe tentei também inserir de alguma forma porem sem sucesso. Aproveitando o ensejo se alguém puder me explicar porque a contagem se inicia no 2 ao invés do determinado 3.
Esse é o código que estou trabalhando: https://jsfiddle.net/4mapbkq7/1/
Comment: Mas cadê o onload do seu código? E posta o código aqui mesmo, no próprio editor tem um botão para adicionar código html/css/js e que funciona parecido com o jsfiddle.
Answer: Nesse código consegui colocar botão curtir e iframe

 var start = new Date();
 start = Date.parse(start)/1000;
 var seconds = 3; // TEMPO EM SEGUNDOS EM QUE HAVERÁ O REDIRECIONAMENTO
 function CountDown(){
     var now = new Date();
     now = Date.parse(now)/1000;
     var counter = parseInt(seconds-(now-start),10);
     if(counter <= 9){
      document.getElementById('countdown').innerHTML = ' 0'+counter;
     }else{
      document.getElementById('countdown').innerHTML = counter;
     }
     if(counter > 0){
         timerID = setTimeout("CountDown()", 100)
     }else{
   document.getElementById('countdown').innerHTML = '
';
  }
 }
 window.setTimeout('CountDown()',100);
3

onload não funciona com setTimeout


How to create a string of fixed byte size

Question: I need to send a sequence of spaces or zeros, whose size is of fixed byte length. The in house framework I am working with takes care of converting string into bytes as per encoding. So in nutshell I need to create a string of given length.
I found out that one space is of two bytes in Java, but it might differ based on encoding used. I tried ensureCapacity method of byte [] with min length and maximum capacity, but while converting it to String, there are no padding of zeros, even though byte array length is same as maximum capacity I am giving.
I am getting a little confused while trying to grasp the concept of bytes, string, charsets, byte [], new String(byte []), encoding, String.toBytes etc.
How do i go about creating the same. Also if anyone knows a  good reference on these topics, please share. I am using Java
Comment: Spaces and zeros both encode as single bytes in UTF-8 encoding. So if you need a result of exactly, say, 10 bytes, just take a `String` of 10 characters with any combination of spaces and zeros, convert it to bytes using UTF-8 encoding and  the result should be a `byte[]` of length 10.
Comment: I have to do reverse of it. I know the size of bytes and have to create a string out of it. The byte length is a parameter as i have to create many strings for different byte size. Also, what should be my criteria for selecting the encoding ?
Comment: Hello, For converting Bytes Array to String and reverse, you should have a look at this : https://www.baeldung.com/java-string-to-byte-array. However, to solve your underlying problem, maybe google byte string should worth a look.
Comment: For bytes-to-String conversion, the encoding you need to specify has already decided for you by the creator of the byte stream.  But if the bytes really are nothing more than spaces (0x20) and zeros (0x30), you can safely treat it as UTF-8.
Answer: Generally any standard english character (assuming you use UTF-8, which you currently don't) consists of 1 byte of data. This is because some higher up people decided what characters take up what bytes and how they should be displayed. To save space, they gave the most common characters single byte values. Any special characters, like symbols from asian languages, use more bytes depending on their placement within the character definitions.
To check how many bytes a string has you can use this website: https://mothereff.in/byte-counter
It will show you the amount of bytes used for the text in UTF-8. If you'd want to check it from code you could convert the string into a byte array and that should hold the same result!


Probabilities: Meeting people

Question: The probability of women meeting a man is $m$. Let's look at the perspective of a specific man. The probability of meeting him is $\tilde m$.
Say women look twice for men. Then (assuming $\tilde m$ is so small that $\tilde m \tilde m$ is negligible), the probability of a woman meeting the specific man is $\tilde m + \tilde m$. The probability of meeting both this specific man, and any other man, is (given two searches)
$$ \tilde m m  + m \tilde m$$
What is the probability of a woman meeting the specific man and at least another man, given that she searches $s$ times? As I showed above, the probability is $2m \tilde m$ for $s=2$.
For $s=3$, this would be $6\tilde m m + 3\tilde m m m $. I lack finding a general formula here, and these equations get messier the higher $s$ gets (and I am actually writing down all the potential combinations). Could someone give me some pointers?
Comment: By "at least another man", does that include that specific man? or every man other than that specific guy?
Comment: @BirdKiller1989 it includes that specific man, that is why $\tilde m$ appears in my expressions. It is (*must have this specific man* + *must have at least another man*)
Answer: The question doesn't seem to add up. If $\tilde m\tilde m\approx 0$ I don't understand why it's not true that $mm\approx 0$ or $\tilde m m\approx 0$. Also the $6\tilde m m$ should be, instead $6\tilde m m (1-\tilde m-m)$
I'll try to solve your question with some considerations and changing some notation for easiness.
Let there be two men $A$ and $B$. For any search, $X_A$ is the event of finding man $A$ (equivalent for $B$), and $P(X_A)=a$ and $P(X_B)=b$. Let $X_A^s$ finding him after $s$ searches.
$$P(X_A^s\cap X_B^s) = \sum_{i_A=1}^{s-1}\sum_{i_B=1}^{s-1}\frac{s!}{i_A!i_B!(s-i_A-i_B)!}a^{i_A}b^{i_B}(1-a-b)^{s-i_A-i_B}
$$
What I did there was taking into account all the ways where there can be man $A$ and man $B$ found at least once, multiply it by the probability of that happening and then adding all together.
For $s=8$
$$P(X_A^8\cap X_B^8) = \sum_{i_A=1}^{7}\sum_{i_B=1}^{7}\frac{8!}{i_A!i_B!(8-i_A-i_B)!}a^{i_A}b^{i_B}(1-a-b)^{8-i_A-i_B}
$$
Simplify for the final answer (I'll think about how to do it, if possible)
EDIT (simplifying)
If we assume $a=b$
$$P(X_A^8\cap X_B^8) = \sum_{i=2}^6 \binom{8}{i}a^i(1-a)^{8-i}
$$
From here, using Wolfram Alpha:
$$P(X_A^8\cap X_B^8)=14a^8-56a^7+140a^6-224a^5+210a^4-112a^3+28a^2$$
And using your notation:
$$14\tilde m^8-56\tilde m^7+140\tilde m^6-224\tilde m^5+210\tilde m^4-112\tilde m^3+28\tilde m^2$$

Probabilities: Meeting people


Como faço para iniciar o Tomcat como serviço no Linux?

Question: Preciso de colocar um sistema WEB em produção usando o Tomcat 7. Sei que posso iniciar com a shell catalina.sh start mas gostaria de algo que funcionasse após o reboot e que o Tomcat entrasse normalmente.
Answer: Supondo o Tomcat7 instalado em /usr/local/tomcat você pode colocar a seguinte shell no diretório /etc/init.d
Você deve criar um usuário tomcat de forma que possa executar a shell dentro da sandbox dele.
Arquivo: tomcat7
#!/bin/sh
# chkconfig: 345 98 99
# description: Tomcat auto start-stop script.
#
# Set OWNER to the user id of the owner of the Tomcat software.

OWNER=tomcat

case "$1" in
    'start')
        su - $OWNER -c "/usr/local/tomcat/bin/catalina.sh start >> /usr/local/tomcat/logs/tomcat7.log 2>&1"
        touch /var/lock/subsys/tomcat7
        ;;
    'stop')
        su - $OWNER -c "/usr/local/tomcat/bin/catalina.sh stop  >> /usr/local/tomcat/logs/tomcat7.log 2>&1"
        rm -f /var/lock/subsys/tomcat7
        ;;
    *)
        echo "Uso: $0 {start|stop}"
        RETVAL=1
esac

# RESULT=`ps -ef | grep catalina | grep -v grep `
# echo $RESULT

exit $RETVAL

O nome de usuário tomcat não é obrigatório. Pode ser tomcat7 por exemplo. O impotante é que o nome seja significativo na gestão de seus ativos de software.
Instalando
Para adicionar o shell script ao chkconfig faça:
cd /etc/init.d
chmod 755 tomcat7
update-rc.d tomcat7 defaults

Com o último comando, estamos dizendo ao sistema para inicie o script automaticamente no runlevel 3.
Mais detalhes do que seja um RunLevel veja nesse link
Para iniciar a execução do script sem um Rebbot faça:
service tomcat7 start

Para verificar se está rodando, pode checar através do ps -ef | grep catalina
Conclusão
O chkconfig cria links simbólicos apontando para o shell script em /etc/init.d dentro dos diretórios dos runlevel correspondentes : /etc/rc[0-6].d
Verifique o diretório:
ls -lA /etc/rc3.d

Observe que os links simbólicos ou começam com S (start) ou com K (kill) seguido de um número que representa a sua sequência de carregamento.
A sequência de carregamento é especificada na seguinte linha do script:
chkconfig: 345 98 99

Os números de inicialização/finalização podem ser os mesmos.
Desinstalando
Se precisar restaurar o sistema como estava antes disso tudo faça:
service tomcat7 stop
update-rc.d -f tomcat7 remove
rm -f /etc/init.d/tomcat7

Isso removerá o tratamento do chkconfig que você inseriu.
Answer: Você pode executar esse script em /etc/rc.local.
Esse arquivo é executado logo após o boot.
O formato deve ficar mais ou menos assim:
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0″ on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing

catalina.sh start

# Outro código ... etc...

exit 0;

Outra forma é criar um script em /etc/init.d/tomcat7.
Contendo:
#!/bin/bash

### BEGIN INIT INFO
# Provides:        tomcat7
# Required-Start:  $network
# Required-Stop:   $network
# Default-Start:   2 3 4 5
# Default-Stop:    0 1 6
# Short-Description: Start/Stop Tomcat server
### END INIT INFO

PATH=/sbin:/bin:/usr/sbin:/usr/bin

start() {
 sh /usr/share/tomcat7/bin/startup.sh
}

stop() {
 sh /usr/share/tomcat7/bin/shutdown.sh
}

case $1 in
  start|stop) $1;;
  restart) stop; start;;
  *) echo "Run as $0 <start|stop|restart>"; exit 1;;
esac

Lembrando de dar as permissões ao script (como administrador):
chmod -x /etc/init.d/tomcat7
update-rc.d tomcat7 defaults

E, finalmente, você poderá iniciar o serviço:
service tomcat7 start

Comment: Você poderia também usar `sudo -u $OWNER "..."` para poder executar a operação com algum usuário definido como na outra resposta.
Answer:
Segue o passo a passo para instalação do Tomcat 9 e Serviço no Linux, script atualizado está nesse link.

#!/bin/bash
### Install Tomcat 9 + JRE8 on Ubuntu, Debian, CentOS, OpenSUSE 64Bits
### URL com Screencast de Instalação do Tomcat9
### http://www.linuxpro.com.br/2017/04/instalando-tomcat-9-no-ubuntu/
### Link: https://www.digitalocean.com/community/tutorials/how-to-install-apache-tomcat-8-on-centos-7

## First install wget
## Primeiro instale o wget

# Check if user has root privileges
if [[ $EUID -ne 0 ]]; then
echo "You must run the script as root or using sudo"
   exit 1
fi

groupadd tomcat && useradd -M -s /bin/nologin -g tomcat -d /usr/local/tomcat tomcat

cd /usr/local/
wget --header 'Cookie: oraclelicense=a' http://download.oracle.com/otn-pub/java/jdk/8u131-b11/d54c1d3a095b4ff2b6607d096fa80163/jre-8u131-linux-x64.tar.gz
tar -xf jre-8u131-linux-x64.tar.gz && rm -f jre-8u131-linux-x64.tar.gz
mv jre1.8.0_131 java

echo 'JAVA_HOME=/usr/local/java
export JAVA_HOME
PATH=$PATH:$JAVA_HOME/bin
export PATH' >> /etc/profile

source /etc/profile
java -version

cd /usr/local/
wget http://mirror.nbtelecom.com.br/apache/tomcat/tomcat-9/v9.0.0.M19/bin/apache-tomcat-9.0.0.M19.tar.gz
tar -xvf apache-tomcat-9.0.0.M19.tar.gz
mv apache-tomcat-9.0.0.M19 tomcat
rm -f apache-tomcat-9.0.0.M19.tar.gz

cd /usr/local/tomcat
chgrp -R tomcat conf
chmod g+rwx conf
chmod g+r conf/*
chown -R tomcat webapps/ work/ temp/ logs/
chown -R tomcat:tomcat *
chown -R tomcat:tomcat /usr/local/tomcat

echo '# Systemd unit file for tomcat
[Unit]
Description=Apache Tomcat Web Application Container
After=syslog.target network.target
[Service]
Type=forking
Environment=JAVA_HOME=/usr/local/java
Environment=CATALINA_PID=/usr/local/tomcat/temp/tomcat.pid
Environment=CATALINA_HOME=/usr/local/tomcat
Environment=CATALINA_BASE=/usr/local/tomcat
Environment='CATALINA_OPTS=-Xms512M -Xmx1024M -server -XX:+UseParallelGC'
Environment='JAVA_OPTS=-Djava.awt.headless=true -Djava.security.egd=file:/dev/./urandom'
ExecStart=/usr/local/tomcat/bin/startup.sh
ExecStop=/bin/kill -15 $MAINPID
User=tomcat
Group=tomcat
[Install]
WantedBy=multi-user.target' > /etc/systemd/system/tomcat.service

systemctl daemon-reload
systemctl start tomcat
systemctl enable tomcat

## Open in web browser:
## http://server_IP_address:8080


Python OpenCV - Erro ao usar função de desenho

Question: Eu já consegui executar esse código antes, porém agora não funciona. Ele precisa desenhar um quadrado na tela do vídeo.
Erro:

Traceback (most recent call last):
     File "/home/ggoulart/PycharmProjects/INTPYT_HandTracker/Main.py", line    13, in
     cv2.rectangle(gray, 100, 100, (0,255,0), 3)
     SystemError: new style getargs format but argument is not a tuple

E o código executado:
import cv2
import numpy as np

cap = cv2.VideoCapture(0)

# Loop
while (1):

    _, frame = cap.read()

    gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)

    cv2.rectangle(gray, 100, 100, (0,255,0), 3)

    cv2.imshow('Test',gray)

    k = cv2.waitKey(100)
    if k == 27:
        break

cap.release()
cv2.destroyAllWindows()

Informações adicionais:
OpenCV version: 3.x
Host OS: Linux (Fedora 23)
Compiler & CMake: GCC 5.3 & CMake 3.5
Answer: A chamada da função cv2.rectangle() está incorreta.
O segundo e o terceiro parametro são tuplas que representam as coordenadas dos vértices opostos do retângulo que será desenhado na imagem.
A chamada abaixo desenha um retângulo de 100x100 pixels na coordenada 0,0 na imagem:
cv2.rectangle(gray, (0,0), (100,100), (0,255,0), 3)

Referência:

cv.Rectangle( img, pt1, pt2, color, thickness=1, lineType=8, shift=0 ) → None
img – Image.
pt1 – Vertex of the rectangle.
pt2 – Vertex of the rectangle opposite to pt1
rec – Alternative specification of the drawn rectangle.
color – Rectangle color or brightness (grayscale image).
thickness – Thickness of lines that make up the rectangle. Negative values, like CV_FILLED , mean that the function has to draw a
  filled rectangle.
lineType – Type of the line. See the line() description.
shift – Number of fractional bits in the point coordinates.

Espero ter ajudado.