Quantifying a variable in a set after specifying the set

Question: My linear algebra instructor claims that the expression for a set of vectors
$$ B = \left\{ \vec v \in \mathbb{R^2} : \vec v = a \begin{bmatrix}2 \\ 1\end{bmatrix} \right\}, \text{ where } a \in \mathbb{R} \tag{1}$$
is incorrect, whereas
$$ B = \left\{ \vec v \in \mathbb{R^2} : \vec v = a \begin{bmatrix}2 \\ 1\end{bmatrix}, \text{ where } a \in \mathbb{R} \right\} \tag{2}$$
is correct.
His reasoning is that the variable $a$ doesn't exist anymore once the set is closed, so there is nothing to be quantified, and the first expression is meaningless.
On the other hand, a definition in the textbook we are using indicates that an  expression such as
$$ \text{Let } a \in \mathbb{R}. \text{ Then, } B = \left\{ \vec v \in \mathbb{R^2} : \vec v = a \begin{bmatrix}2 \\ 1\end{bmatrix}\right\} \tag{3}$$
is correct.
I've also learned in another class, which tackled formal logic a little more deeply than this linear algebra class, that quantifying a variable before or after a statement involving the variable is mostly an arbitrary/stylistic decision on the part of the writer. If we can quantify a variable before a statement, we can quantify it after a statement as well. According to this other class, the first statement might be okay, although I don't remember tackling sets specifically when working with quantifiers.
I know there is such a thing as quantifier scope in formal logic, but I'm not sure whether set brackets delineate quantifier scope in mathematical statements such as the above, as my linear algebra instructor seems to suggest.
Since ultimately a statement such as this should make sense when expressed in natural language, I think the first statement is one where the speaker mentions, after specifying the set, that, "by the way, the $a$ in the preceding statement (which happens to contain a set in this case) is a real number, in case that wasn't clear", which is similar to how a speaker might mention the domain of the variable prior to specifying the set, as in statement $(3)$.
I was wondering whether anyone can confirm or deny my instructor's claim, and whether the first statement is truly a mathematically meaningless statement.
Comment: Both (1) and (2) are meaningful, but they are not the same. The set in (1) has exactly one element, which element depends on the pregiven value $a$, while the set in (2) has as many members as many value $a$ can take from $\Bbb R$.
Comment: But "for some $a\in\mathbb{R}$", _inside_ the set definition, means that the set _does_ have an element for each possible value of $a$, since all those possibilities would make the existential statement true.
Comment: @Berci Since there is no pregiven value of a, that would make (1) meaningless, no?
Comment: But I think I'm starting to see what you mean. It doesn't make sense to quantify the variable prior to the set, because then the set would only contain one element. And quantifying it after the set is similar to quantifying it before. Maybe the variable does have to be quantified within the set after all... And I guess that makes $(3)$ distinct from $(2)$ as well. Regardless what we pick for $a$, the set in $(3)$ will contain just one element, namely the vector that's been scaled by $a$.
Answer:
The set $$ B = \left\{ \vec v \in \mathbb{R^2} : \vec
    v = a \begin{bmatrix}2 \\ 1\end{bmatrix}, \text{ where } a \in
    \mathbb{R} \right\} \tag{2},$$ that is, $$ B = \left\{a \begin{bmatrix}2 \\
    1\end{bmatrix}:a \in \mathbb{R} \right\} \tag{2},$$ is the set of vectors of the form $a\begin{bmatrix}2 \\    1\end{bmatrix},$ where $a$ is real; in other words, each element of
$B,$ for some real $a,$ equals $a\begin{bmatrix}2 \\
1\end{bmatrix}.$ This is the set that you want.
On the other hand, the statement $$ B = \left\{ \vec v \in \mathbb{R^2} : \vec v = a
\begin{bmatrix}2 \\ 1\end{bmatrix} \right\}, \text{ where } a \in
\mathbb{R} \tag{1}$$ means that for some (pre-specified) real $a,$ the set $B$ contains precisely the element $a \begin{bmatrix}2 \\ 1\end{bmatrix}.$
Similarly, the statement $$ \text{Let } a \in \mathbb{R}; \text{ then, } B
= \left\{ \vec v \in \mathbb{R^2} : \vec v = a \begin{bmatrix}2 \\ 1\end{bmatrix}\right\} \tag{3}$$ says that $B$ is a single-element set, but this time $a$ is an arbitrary, instead of a pre-specified, real number.


Ratio of two centered independent centered chi^2

Question: Let X and Y be independent $\chi^2$ variables with $k$ degrees of freedom. What is the distribution of
$\frac{X-E[X]}{Y-E[Y]}$?
I know that without subtracting the means it would be F distribution, but I can't find anything about the ratio when both variables are centered.
In particular, is it true that the median of this distribution is 1?
Comment: It doesn't seem to be the case that the median is 1, no; for example a largish simulation with k=2 indicates that a median of 1 is untenable; it appears to be more like 0.133 or so. For k=1 [it appears to be about 0.31](https://i.stack.imgur.com/zXY9q.png).
Answer: If I'm not mistaken, at least for even $k$, this is solvable, but it is very tedious. Following is the outline, in which, for simplicity, I'm omitting constant terms from any integral (i.e., those not involved in the integration).
The ratio distribution of two independent $\chi^2$ RVs is
$$
\sim \int_y |y| (zy)^{\frac{k}{2} - 1}e^{-\frac{zy}{2}} y^{\frac{k}{2} - 1}e^{-\frac{y}{2}} \text{d}y
=
\int_y |y| (zy^2)^{\frac{k}{2} - 1}e^{-\frac{y(z + 1)}{2}}  \text{d}y
 \; (1)
$$
(again, note that constants are omitted from the integral).
Similarly, if you shift the RVs by $a$ (which, in your case is the mean), then the ratio distribution is
$$
\sim \int_y |y| (zy - a)^{\frac{k}{2} - 1}e^{-\frac{zy}{2}} (y - a)^{\frac{k}{2} - 1}e^{-\frac{y}{2}} \text{d}y
\\
=
\int_y |y| (zy^2 - ay(z + 1) + a^2)^{\frac{k}{2} - 1}e^{-\frac{y(z + 1)}{2}} \text{d}y
\; (2)
$$
(once again, note that constants are omitted from the integral).
Note that
$$
\int_y |y| (zy^2 - ay(z + 1) + a^2)^{\frac{k}{2} - 1}e^{-\frac{y(z + 1)}{2}} \text{d}y \; (3)
\\
=
\int_{y > 0} y (zy^2 - ay(z + 1) + a^2)^{\frac{k}{2} - 1}e^{-\frac{y(z + 1)}{2}} \text{d}y
-
\int_{y < 0} y (zy^2 - ay(z + 1) + a^2)^{\frac{k}{2} - 1}e^{-\frac{y(z + 1)}{2}} \text{d}y
.
$$
If $k$ is even, then $q = \frac{k}{2} - 1$ is an integer, and, in (3),
$$
(zy^2 - ay(z + 1) + a^2)^{\frac{k}{2} - 1} = (zy^2 - ay(z + 1) + a^2)^q
$$
so that trinomial expansion can be used. The integral corresponding to each term in the expansion has a closed form solution.
I wish you the best of luck!!!
Answer: The behaviour of the distribution is quite 'wild' for small values of parameter $k$.
Here is a Monte Carlo simulation of the pdf of the ratio when $k = 1$:

... and when $k = 2$:

However, it rapidly stabilises as $k$ increases, and when $k$ is larger, is extremely well approximated by a Cauchy distribution (same as Student's $t$ with 1 df), i.e.
$$f(x) = \frac{1}{\pi  \left(x^2+1\right)}$$
... which seems very pretty, considering how messy the symbolics are.
Here is a plot of the pdf of the ratio when $k = 25$:

the rough blue curve is the simulated Monte Carlo pdf of the ratio
the dashed red curve underneath is the exact Cauchy pdf

The fit appears amazing - too good to be arbitrary.
Touchy-feely explanation
To get a feel for why this is the case, first observe that the distribution of $X-k$ which has form:
$$f(x) = \frac{2^{-\frac{k}{2}} e^{-\frac{1}{2} (k+x)} (k+x)^{\frac{k}{2}-1}}{\Gamma \left(\frac{k}{2}\right)}$$
... tends to normality (in particular, it seems $N(0, 2k)$) as $k$ becomes large: see for instance:

Then, note that the ratio of two Normals with zero mean is Cauchy, and we have the gist of it.


Passar letra maiúsculas para minúsculas

Question: Tenho um componente do richfaces datatable que retorna um registro do banco e esse registro vem com letras maiúsculas.
Exemplo: PAULO FERNANDES DA SILVA.
Teria algo que eu pudesse fazer para editar esse nome com CSS para Paulo Fernandes Da Silva para ser mostrado no datatable?
Ps.: Estou usando HTML4.
Answer: Uma possibilidade é converter o nome para minúsculas antes de inserir no HTML, e depois estilizar com text-transform: capitalize;

var nome = 'PAULO FERNANDES DA SILVA';

document.getElementById('nome').innerHTML = nome.toLowerCase();
#nome {
  text-transform: capitalize;
}

Comment: aí não sei. Você colocou a tag javascript, achei que já estava recebendo o dado por ele.
Comment: variável nome está estática. Mas ela vem do banco, como eu posso fazer para ele receber esse dado da base com javascript?

Passar letra maiúsculas para minúsculas


C# Ler arquivo TXT e deletar

Question: Boa Tarde, estou desenvolvendo um programa que lê um certo arquivo (contém mais de 60k de linhas) remove uso desnecessários e organiza e grava em outro arquivo.
using (StreamReader leitor = new StreamReader(lerArquivo))
{
    while (!leitor.EndOfStream)
    {
        var linha = new ArquivoTxt();
        linha.Linha = leitor.ReadLine();
        conteudoArquivo.Add(linha);
    }

    var gravarArquivo = @"C:\log\meutxt.txt";

    using (StreamWriter sw = new StreamWriter(gravarArquivo))
    {
        conteudoArquivo = conteudoArquivo.Where(_ => _.Linha.StartsWith("|") &&
                                                     _.Linha.Substring(0, 2) != "|0" &&
                                                     _.Linha.Substring(0, 2) != "|-" &&
                                                     _.Linha.Substring(0, 2) != "|C" &&
                                                     _.Linha.Substring(0, 2) != "|I" &&
                                                     _.Linha.Substring(0, 2) != "| " &&
                                                     _.Linha.Substring(0, 2) != "|R" &&
                                                     _.Linha.Substring(0, 2) != "|D" &&
                                                     _.Linha.Substring(0, 2) != "|E").ToList();

        foreach (var item in conteudoArquivo)
        {
            string[] linha = item.Linha.Split('|');
            string ordemVenda = linha[1].Trim();
            sw.WriteLine(linha[1]);
        }

        sw.Close();
    }
}

só que no retorno ele só me retorna a 1ª coluna do Arquivo e eu queria o retorno da Linha inteira
Comment: não é pq você está lendo apenas a `linha[1]` ??
Comment: E por que usa o `using` e fecha o arquivo? E existe algum motivo para criar variável onde não precisa e deixar de criar onde será muito útil?
Comment: @LeandroAngelo eu já tentei mudar não retorna oque eu quero
Comment: @Maniero eu estou iniciando, ainda não sei muito.
Answer: Assim não consegue o que pretende?
string[] caracteresAceites = new string[] { "|0", "|-", "|C", "|I", "| ", "|R", "|D", "|E" };

using (StreamReader leitor = new StreamReader(lerArquivo))
{
    using (StreamWriter sw = new StreamWriter(@"C:\log\meutxt.txt"))
    {
        while (!leitor.EndOfStream)
        {
            string linha = leitor.ReadLine();

            if(linha.StartsWith("|") && !caracteresAceites.Contains(linha.Substring(0, 2)))
            {
                string[] _linha = linha.Split('|');

                if(_linha.Length > 1)
                    sw.WriteLine(_linha[1].Trim());
            }
        }
    }
}

Dei uma "otimizada" no seu código
Não precisa do sw.Close() porque o using já faz isso (e o Dispose do objeto).
Comment: Que bela otimizada em :D, estou começando na programação, obrigado pela ótima otimizada e claro deixando o código mais fácil de se entender
Comment: Não resolve o seu problema? Obrigado :)
Comment: não consegui, no caso ele me retorna somente a 1 coluna Ordem de Venda, oque eu queria que ele me retornasse a linha do bloco de notas inteira, porém ele ta quebrando a linha e limpando tudo que vem depois do |Ordem de Venda|
Answer: Troque:
sw.WriteLine(linha[1]);

para:
sw.WriteLine(item.Linha);

Comment: rapaz! obrigado eu troquei (linha[1]) por (item.Linha), e consegui oque eu esperava.

C# Ler arquivo TXT e deletar


Logic app Outlook subject filter not working

Question: I have a logic app that Initializes a Variable (Timestamp + a phrase), sends an email with that as the subject line, then polls the destination mailbox (O365 mailbox) looking for that exact Subject line, using the get emails (v3) function.
And yet, when the get email function runs, it doesn't retrieve anything, showing only a blank output which is breaking other parts of the Logic App:

The String looks like this: '2023-12-08T03:57:22.3748840Z Round Robin Test Email'
I've tried all sorts of quotation marks, string(variables('var1')), I've tried concatting the string with a search parameter, tried using the customer search query - and nothing works.
Currently, I've reverted back to just calling the Variable:

It's driving me loony and up the wall. Either I've missed something obvious or there's a bug or something else?
Comment: If you are taking current time and sending an email amending that time as Subject line then logic app takes few seconds to send the email to the outlook. So if you try to fetch that email in the same workflow then it will give you blank result because at that moment, subjected email might not been sent to the inbox.
Comment: You can get the email using the phrase like "Round Robin" as the subject filter
Comment: @IkhtesamAfrin - Unfortunately no, we can't just use Round Robin, we need the timestamp as each email is unique (there are reasons for this) The get-email runs in an until loop for ~1 minute until it gets it - which is never does, I even added a delay in the workflow - it doesn't match.
Comment: I have added a delay of 20sec before the Get emails action and I am able to fetch the email details, check [this](https://i.imgur.com/sozXw9E.png) and [this](https://i.imgur.com/yvA6mHv.png)
Comment: You could use another app and have the new email trigger as the trigger.
Comment: @skin, no because there's no way to go back in time and get the timestamp from the previous run.
Comment: @IkhtesamAfrin - the Get Email though sits inside an until - so it should keep retrying for up to a minute until it gets the message - but it doesn't.
Comment: @TheDemonLord can you share the screenshot of your until loop? Even I was getting blank earlier but now I am getting data after adding delay of 20sec. what's the until condition in your case?
Comment: @TheDemonLord I believe until loop will execute based on the loop condition.
Comment: Yes there is, you just gotta do the work.
Comment: @TheDemonLord If you want to use Until loop only and don't want to add Delay in your workflow then you can increase the count of the Until loop to 2. By doing so you will get the data in the second call
Answer:
when the get email function runs, it doesn't retrieve anything, showing only a blank output which is breaking other parts of the Logic App

You have added both the Send Email and Get Emails actions in one workflow and you are passing the current time in the Email subject. By the time Get emails action polls the Inbox for the exact subject line, that email might not reach the Inbox at that moment, as logic app takes few seconds to send email to our Outlook. So You might consider adding delay in your workflow post Send Email (V2) action.
Though you are using Get Emails (V3) action inside Until loop but the execution of the loop depends on the loop condition.
Here I am using Delay in the workflow to get the email details. You can modify the count according to your requirement.

I am able to get the details as shown below-

If you still want to use Until loop, then you need to modify the loop condition by keeping few seconds of execution time.


Is it still worth going into machine learning/AI?

Question: I am a high school senior about to start my undergraduate education. I've done an internship for the past two years working with constitutional neural networks and RNNs. I love doing research, and I know that's what I want to do in the future, and given my interest and proficiency in the field I had assumed that I would research AI.
Recently, though, I've begun to rethink this. There has been more and more research coming out that points to the automation of AI research (for example, these three papers). Speaking about the third paper, Nando de Freitas joked in his recent talk, "If you're designing gradient descent algorithms for MNIST, you're out of a job."
We are not at the end of machine learning research, but will we be in another 10, 20, 30 years? Will we reach a point in the next few decades where there is no more major AI research to be done by humans? Starting college, I want to go into a field with a rich future and great potential for innovation. Will deep learning still be that in 10 years when I'm looking for a job?
Comment: Well, isn't machines building all the stuff the future?

Go from there... Don't take individual comments too seriously but rather look at the overall market situation. Here is a good resource: https://www.bls.gov/oes/current/oes_nat.htm#15-0000
Comment: If AI/ML work is automated, it seems plausible that as an AI/ML researcher, you would be doing the work around automating it. Moreover, automatic methods are not able to integrate information about subject matter: working on AI for national security is a different topic than AI for malware analysis, and knowing how to extract features from these different sources of data is a key part of the task.
Comment: I've a younger brother (18 yrs), and I have pushed on him to become as technical as possible. I'll pass on the same suggestions, whether you end up working with neural nets or some other CS/engineering field, it will benefit you to be a proficient programmer in languages like C++, Python, Java. Also, learn to use a Linux/UNIX shell.
Comment: The only thing that's changed in recent years is the speed at which new algorithms are developed. So while individual types of algorithms risk being outdone by better techniques the field is nowhere near saturation in terms of what's left to be discovered. I'll bet money that 10 years from now there will be something out there that blows our current deep learning techniques out of the water, maybe even not using neural networks at all.
Answer: My father went to university shortly after World War II and he used to tell me about how he once did a long Fourier transformation and how they used those very long paper rolls, as they did it in a paper pencil approach.
When I went to school in the 80s, people used to think, that in some time in the future everybody would have to deal with computers. And we supposed to be the generation who could not avoid computers. Not everybody did believe it, but school tried to prepare us by teaching us BASIC and PASCAL!
Now it turns out, we still need a lot of people who know about Fourier transformations and yes, next to everybody uses computers today. But how wrong were they, teaching programming to everyone, because they believed, that "working with computers" meant "programming computers"?
I met a young automobile engineer last year and he told me, how all those engineering students went into "automobile" because they somehow love fuel burning engines and now see, that electric mobility is what they will earn their money with, in the future.
Obviously, doing computer analyses in 10, 20, 30 years will be totally different from what it is today. And nobody can tell you now, what it will be like. There is good reason to conject, that data analysis is going to be of huge importance and that some of the jobs done today by specialists will be done in 20 years by anyone with his watch or mobile or... But new questions will come up, new things to learn and to master, things that will need specialists (at least for a time). Don't start a career in information technology assuming, that you won't have to learn and to adapt to new technologies your whole life through. Try to learn a lot, try to be fit for change. Learn those things, that will never change (mostly mathematics) and don't overdo that fancy new method, that everyone praises now just to reject it, when the next hot thing comes around.
SQL has been used 40 yrs ago and is used today. For someone who knows their linear algebra, their basics in databases, knows about object oriented programming as well as functional programming, classical statistics as well as Baysian and Machine Learning, can communicate with ordinary people, with business people and lawyers and is constantly open to new challenges, there will be lots of interesting work opportunities in the future. We just don't know, what they will be.
So if you love all the consituents of what makes machine learning, go for it. If just think, that support vector machines are cool - well, think twice.


How to simulate Haskell's pattern matching using visitor pattern in Java

Question: I am new to Java and I am trying to use visitor pattern to simulate pattern matching. For this Haskell function
getOrDefault :: Maybe a -> a -> a
getOrDefault (Just x) = const x
getOrDefault Nothing = id

which returns a value of type a (given a value of type Maybe a and a default value), the following Java codes work.
interface Visitor<T, S> {
    S visitJust(Just<T> j);
    S visitNothing(Nothing<T> n);
}

abstract class Maybe<T> {
    public abstract <S> S accept(Visitor<T, S> v);

    public T getOrDefault(T defaultValue) {
        return this.accept(new Visitor<T, T>() {
            @Override
            public T visitJust(Just<T> j) { return j.value; }

            @Override
            public T visitNothing(Nothing<T> n) { return defaultValue; }
        });
    }
}

class Just<T> extends Maybe<T> {
    final T value;

    public Just(T value) {
        this.value = value;
    }

    public <S> S accept(Visitor<T, S> v) {
        return v.visitJust(this);
    }

}

class Nothing<T> extends Maybe<T> {
    public <S> S accept(Visitor<T, S> v) {
        return v.visitNothing(this);
    }
}

When I try to simulate this function that obtains the "length" of a value of type Maybe [a]
getLength :: Maybe [a] -> Int
getLength (Just x) = length x
getLength Nothing = -1

, the Java-version getLength I write is
public int getLength() {
    return this.accept(new Visitor<List<T>, Integer>() {
        @Override
        public Integer visitJust(Just<List<T>> j) { ... }

        @Override
        public Integer visitNothing(Nothing<List<T>> n) { ... }
    });
}

But it doesn't work, since T and List<T> are incompatible. How to fix this?
Comment: Yes I know that I can simply call `list.size()` and I agree with you. But this is just a snippet to help me understand how to use visitor pattern in Java. @AndyTurner
Comment: Aside from the question of getting this to compile: why are you trying to write it like this in Java? There's an easy way to get the length of a list: you call `list.size()`. It doesn't seem particularly useful to write in Haskell's idiom.
Comment: However, for your actual question: please show where you're declaring the `getLength()` method (as in, the containing class).
Comment: Sorry I don't make my question clear enough. I am declaring `getLength()` in the abstract class `Maybe`. @AndyTurner
Comment: @AlfredTan You can't declare it inside `Maybe` since otherwise you will have to implement `getLength()` for all `T`s, even for e.g. `Maybe`. Length is not defined for `Maybe`, but only for `Maybe>`. Exactly like in Haskell. As suggested below, a static generic function can be defined on that more specific case.
Comment: @chi I got it. Thanks for your explanation!
Answer: Declare getLength() as a static method with its own type variable:
  public static <T> int getLength(Maybe<List<T>> maybe) {
    return maybe.accept(new Visitor<List<T>, Integer>() {
      @Override
      public Integer visitJust(Just<List<T>> j) { ... }

      @Override
      public Integer visitNothing(Nothing<List<T>> n) { ... }
    });
  }

Comment: @AlfredTan Any instance methods in `Maybe` have to work for all `T`, not just for lists.


(BOOL) webView... not firing on all requests

Question: I'm working on an iOS app using UIWebViews, and I'm running in to some interesting behavior.
I'm trying to load content from my website into an iOS app via a UIWebView, but I want to block certain calls made by the website (such as some of my analytics) to speed up the load within the WebView.  If I connect the device to a proxy (I've been using Charles Proxy) I can see these requests going out, just as I would expect them to.  However, for whatever reason,
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {

Is not capturing the requests I'm looking for.  In fact, webView:(UIWebView *)... is only firing on about a third of the calls that I see going out over the proxy.
Does anyone know why that might be?  Or have any idea what I can do to intercept all of the calls made by a UIWebView?
Thank you
Comment: did you set the delegate?
Comment: Yes.  It fires maybe 12 times/page load, and I see closer to 40 requests go out over the proxy.
Answer: You will not get delegate calls for all requests from the web view (for example, resource requests, such as JavaScript and images).
To have a precise control over all requests, you will need to implement a NSURLProtocol in which you can decide what request to allow and what to block.


Enum State pattern for android

Question: I'm trying to create a Enum STATE pattern so I can set the current state of my operations.
In C# (i think) I used this pattern:
<code>Enum State { STARTED, STOPPED, PAUSED };
State _s;

public foo() {
   _s = State.STARTED;
}
</code>
I did read somewhere that you shouldn't or couldn't use Enum in Android. How can I replicate this design pattern in Android?
Comment: I'm not so sure that you can't use enums for Android. That information might be obsolete due to performance gains of the VM: http://stackoverflow.com/questions/5143256/why-was-avoid-enums-where-you-only-need-ints-removed-from-androids-performanc
Comment: Enums are slightly less efficient than ints, but it probably won't be a big enough difference to matter. Is that what you were referring to?
Comment: Okey, that actually answerd my question. Thanks alot @Blacklight
Answer: You definitely can use them. Android's libraries don't which probably perpetuates the myth/out of date advice. It's easy to switch from one to the other, so start with enums and only change if you experience performance issues, but I doubt you will.
Comment: Yes it worked like a charm. For future readers: `private static enum State {STARTED, STOPPED, RESETED};
 private State state;` and to set the state `state = State.STARTED;`

Enum State pattern for android


Expectation and convergent

Question: Let $X$ be a random variable, and let $A_n=\{\omega: n\leq|X(\omega)|< n+1 \}$.
How I can deduce

$E(X)$ is finite iff $\sum_{n=1}^{\infty} P(|X|\geq n)$ is convergent,
If $E(X)$ is finite then $n P(|X| \geq n) \to 0$ as $n \to \infty$.

Please hint for this question.
Comment: Why are the $A_n$ defined, they appear to be of no use.
Comment: *Hint.* We have $$ \sum_{n=1}^{\infty} P(|X| \geq n) \leq E |X| \leq \sum_{n=0}^{\infty} P(|X| \geq n) $$ and $$ n P(|X| \geq n) = E( n \mathbf{1}_{\{|X| \geq n\}} ), \qquad n \mathbf{1}_{\{|X| \geq n\}} \leq |X| $$.
Comment: please explian part 2 for me @SangchulLee
Answer: Hints: 1. Use the expression $E(|X|)= \int_{0}^\infty \mathbb{P}(|X|\geq t) \text{d} t$ which can be derived by Fubini's Theorem, and the fact that $ \mathbb{P}(|X|\geq n+1) \leq \mathbb{P}(|X|\geq t)\leq \mathbb{P}(|X|\geq n) $ when $ n+1\geq t \geq n $.

Notice that $|X| 1_{|X|\geq n} \geq n 1_{|X|\geq n}$.
Comment: https://math.stackexchange.com/questions/2591626/integral-and-summation this question follow this too  .. I use this relation to prove the first side in 1) $\sum_ {n=1}^{\infty}n p(A_n)$ $\leq$ $E|X|  what about the other side in 1@calrk
Comment: what about 2. if i take n goes $\infty$

Expectation and convergent


Split an array into four sub-array

Question:
Given an array, it contains N element, which are all positive integers; if we can  find three elements, and they divide the array into four parts (Notice: the three elements are not contained in any part of the four), and the sum of each part are equal, then we call the array a "balanced" array. Design an algorithm to judge whether an array is balance, with limit: Time O(N), Space O(N).

Here is an example:
a = [1,7,4,2,6,5,4,2,2,9,8];
b = [1,8,10,5,3,1,2,3]

a is balanced, 'cause the element 4, 5, 9 divide the array into [1,7], [2,6], [4,2,2], [8], the sum of each is 8.
b is not balanced, because we can not find a solution.
Any idea is appreciated!
Comment: Where are you stuck ?
Comment: I do not know how to solve it with O(N) time
Comment: You don't know the logical process, or have you found problems implementing it in your code ?
Comment: the logical process
Comment: Can you find the index of the element which divides the array into *two* equal-sum parts? If so, do that, then divide each of the parts in the same way. Remember, O(n) doesn't mean a single pass over the array, it means a constant number of single passes.
Comment: @AndyTurner Notice that the split elements is not contained in the sub array, I'm afraid your method do not work...
Answer: Hints
Consider the first element to be removed.
Once you know this position, you can compute the size of the first part.
Once you know the size of the first part, you can compute the location of the second element to be removed, and so on (because all elements are positive integers).
Now you need to find a way to perform this in O(N).  Try thinking about what you can do to reuse computations that have already been done, e.g. by keeping a rolling sum of the size of each of your parts.
Answer: You can try with this solution:
class BalancedArray
{

  public static void main( String[] args ) throws java.lang.Exception
  {
    int[] a = {      1, 7, 4, 2, 6, 5, 4, 2, 2, 9, 8   }; //BALANCED
    //int[] a = {7,0,6,1,0,1,1,5,0,1,2,2,2}; //BALANCED
    //int[] a = {1}; //NOT BALANCED
    int l = a.length;
    if ( l < 7 )
    {
      System.out.println( "Array NOT balanced" );
    } else
    {
      int maxX = l - 5;
      int maxY = l - 3;
      int maxZ = l - 1;
      int x = 1;
      int y = 3;
      int z = 5;
      int sumX = 0; //From 0 to x
      int sumY = 0; //From x to y
      int sumJ = 0; //From y to z
      int sumZ = 0; //From z to l

      for(x = 1; x < maxX; x++)
      {
        sumX = calcSum(a,0,x);

        for(y = x + 2; y < maxY; y++)
        {
          sumY = calcSum(a,x+1,y);

          if(sumY != sumX){
            continue;
          }

          for(z = y + 2; z < maxZ; z++)
          {
            sumJ = calcSum(a,y+1,z);

            if(sumJ != sumY)
            {
              continue;
            }

            sumZ = calcSum(a,z+1,l);

            if(sumZ != sumJ){
              continue;
            }

            if(sumZ == sumX && sumX == sumY && sumY == sumJ)
            {
              System.out.println( "Array balanced!!! Elements -> X:" + x + " Y: " + y + " Z:" + z );
              return;
            }

          }
        }
      }

      System.out.println("Array NOT balanced!!");
    }
  }

  private static int calcSum(int[] src, int start, int end)
  {
    int toReturn = 0;
    for ( int i = start; i < end; i++ )
    {
      toReturn += src[i];
    }
    return toReturn;
  }
}

I made these assumptions:

between each of the three elements, which should split the array in 4 parts, there must be at least a distance of 2;
to be divided in 4 sub-arrays the source array must be at least 7 elements long;

Split an array into four sub-array


Display (All) Data from two classes on Parse.com in UITableView

Question: I want to be able to display all of the data from two classes from Parse.com but it is not working. Every time I go to open the tableview the app crashes. Here is my code. I used the guidance from https://www.parse.com/questions/query-with-two-classes to aid me.
- (id)initWithStyle:(UITableViewStyle)style {
    self = [super initWithStyle:style];
    if (self) {
        // This table displays items in the class
        self.parseClassName = @"rep";
        self.parseClassName = @"rep2";

        self.pullToRefreshEnabled = YES;
        self.paginationEnabled = NO;
        self.objectsPerPage = 100;
    }
    return self;
}

- (PFQuery *)queryForTable {

    PFQuery *1query = [PFQuery queryWithClassName:@"rep"];

    PFQuery *2query = [PFQuery queryWithClassName:@"rep2"];

    PFQuery *query = [PFQuery orQueryWithSubqueries:@[1query,2query]];
            [query whereKey:@"user" equalTo:[PFUser currentUser]];
    [query findObjectsInBackgroundWithBlock:^(NSArray *results, NSError *error) {

    }];

    return query;
}

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
                        object:(PFObject *)object {
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                      reuseIdentifier:CellIdentifier];
    }

    // Configure the cell to show todo item with a priority at the bottom
    cell.textLabel.text = [object objectForKey:@"name"];
    cell.detailTextLabel.text = [NSString stringWithFormat:@"Username: %@",
                                 [object objectForKey:@"username"]];

    return cell;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{

    return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{

    // Remove the row from data model
    PFObject *objectToDel = [self.objects objectAtIndex:indexPath.row];

    [objectToDel deleteInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {

        UIAlertView *Alert = [[UIAlertView alloc]  initWithTitle:@"Item Was Deleted Successfully. Pull Down to Refresh Tab" message:nil delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil,  nil];
        [Alert show];

    }
     ];
}

@end

>     Specwatch[668:192464] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'All sub queries of an
> `or` query should be on the same class.'
>     *** First throw call stack:
>     (0x182319900 0x181987f80 0x182319848 0x1000bd8b4 0x100025c10 0x100072514 0x100071e00 0x18700c0c0 0x1870cbda8 0x1870cbc80
> 0x1870caec8 0x1870caa6c 0x1870ca694 0x1870ca5fc 0x187007778
> 0x184a16b2c 0x184a11738 0x184a115f8 0x184a10c94 0x184a109dc
> 0x184a0a0cc 0x1822d0588 0x1822ce32c 0x1822ce75c 0x1821fd680
> 0x18370c088 0x187074d90 0x10006d054 0x181d9e8b8)
>     libc++abi.dylib: terminating with uncaught exception of type NSException
>     (lldb)

Comment: Please paste the log after the crash and indicate on which line it occurs.   The two in a row assignment to parseClassName is effectively like just the second line.  Your queryForTable method is also unusual forming a query with OR, then further qualifying it, then running it, then returning it (all unusual).
Comment: you should scroll back to the log top, post the key info.
Comment: I posted the full report in the original question @SeanChense
Comment: I poste the full report in the original question @danh
Comment: I just need to know how to display two queries for two different classes in a tableview
Comment: You won't be able to use a PFQueryTableViewController to do this, because it requires a PFQuery which can operate only on one class at a time.  The way to do it is a regular UITableViewController which calls a cloud function that makes two individual queries and merges their results.
Comment: can you give me a link or something for guidance on this. Everyone has a PFQueryUITableViewController @danh
Answer: I'll try to summarize how to go about emancipating yourself from the PFQueryTableViewController (and UITableViewController for that matter.  The world would be a slightly happier place if neither of these classes had been invented (imo)).  Create a UIViewController subclass called ViewController.
In IB, add a UIViewController (setting its class to ViewController), give it a UITableView constrained to the edges of the view.  Hook up the datasource, delegate and an outlet called tableView.  Add a prototype cell.  For now, just use a standard subtitle or left detail UITableViewCell.  Give the cell an identifier of @"cell".
// viewcontroller.m
@interface ViewController () <UITableViewDataSource, UITableViewDelegate>

@property(weak,nonatomic) IBOutlet UITableView *tableView;
@property(strong,nonatomic) NSMutableArray *objects;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [PFCloud callFunctionInBackground:@"getTwoClasses" withParameters:nil block:^(NSArray *objects, NSError *error) {
        self.objects = objects;
        [self.tableView reloadData];
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.objects.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    PFObject *object = self.objects[indexPath.row];
    cell.textLabel.text = [object objectId];
    cell.detailTextLabel.text = [object parseClassName];
    return cell;
}

That very simple implementation should be all that's needed on the client.  On the server, we just need a cloud function called "getTwoClasses" to get objects from two classes (rep and rep2).
Deploy this function to do that...
Parse.Cloud.define("getTwoClasses", function(request, response) {
    var reps;
    var user = request.user;
    var repQuery = new Parse.Query("rep");
    repQuery.equalTo("user", user);
    query.find().then(function(result) {
        reps = result;
        var rep2Query = new Parse.Query("rep2");
        rep2Query.equalTo("user", user);
        return rep2Query.find();
    }).then(function(result) {
        response.success(reps.concat(result));
    }, function(error) {
        response.error(error);
    });
});

Comment: Thank you! there are two syntax errors that were throwing me off and that was placing a comma between "user" and user in the repQuery.equalTo  functions
Comment: Oops.  Sorry.  Edited.
Comment: If you feel its a correct answer, it's customary to mark it correct.
Comment: I was going to do that! I just don't have access to edit it and I was waiting for you to switch that! Thank you so much @danh


Limit of $\left(\frac {2}{3}\right)^n \cdot n^4 \cdot \frac {1- 1/ {n^4}} {4+ n^7/ {3^n}}$ as $n$ tends to infinity

Question: I already took some steps to simplifying the original question and im stuck at this point:
$$ \lim_{n \to \infty} \left(\frac {2}{3}\right)^n \cdot n^4 \cdot \frac {1- \frac {1} {n^4}} {4+ \frac {n^7} {3^n}} $$
I know that $$\lim_{n \to \infty}\left(\frac {2}{3}\right)^n=0$$
since $$0<\frac{2}{3}<1$$
and that $$\lim_{n \to \infty}\frac {1} {n^4}=0$$
and that I have to use d'Alembert's criterion to solve what $$\frac {n^7} {3^n}$$ is
but what I get is $$\frac 13*\frac {(n+7)^7}{n^7}$$
I suppose the next step is just $$\frac 13 <1$$
"therefore the limit is zero" but my question is how do I get rid of the
$$\frac {(n+7)^7}{n^7}$$
The last step is just:
$$0*\frac {1-0}{4+0}=0$$
Comment: You mean $n \to \infty$ in the limit, not $x \to \infty$. Also what do you mean when you say "since its $00 and <1 that I can say that its 0
Comment: Still not quite right. You know that $\lim_{n \to \infty} \left(\frac{2}{3}\right)^n = 0$. What you are saying is that $\frac{2}{3} = 0$ which is not true.
Comment: Im stating that $$(\frac{2}{3})^n = 0$$ once the limit is used just like $$\frac {1} {n^4}$$ turns into 0 after the limit is used
Comment: I edited your post to show how you should be stating your claims about limits. The notation $\lim_{n \to \infty}$ is necessary to use when talking about limits.
Answer: I think you can get this by doing a bit of algebra. Since $1-\frac{1}{n^4}<4+\frac{n^7}{3^n}$ for all $n \in \Bbb{N}$ then $$ \left(\frac{2}{3}\right)^n \cdot n^4 \cdot \frac{1- \frac{1}{n^4}} {4+ \frac{n^7}{3^n}}< \left(\frac{2}{3}\right)^n \cdot n^4$$ Now let's use the fact that exponents grow faster than powers. We know that there exists some $M \in \Bbb{N}$ that $$\left(\frac{4}{3} \right)^m>m^4 \quad \text{for all} \quad m>M$$ which means $$\left(\frac{2}{3}\right)^m \cdot m^4< \left(\frac{2}{3}\right)^m\left(\frac{4}{3} \right)^m \\ = \left(\frac{8}{9} \right)^m$$ and we know that $\lim_{m \to \infty} \left(\frac{8}{9} \right)^m=0$. Thus, for all $m>M$  $$\lim_{m \to \infty} \left(\frac{2}{3}\right)^m \cdot m^4 \cdot \frac{1- \frac{1}{m^4}}{4+ \frac{m^7}{3^m}} < \lim_{m \to \infty}\left(\frac{8}{9} \right)^m$$ which means by the comparison test that $$\lim_{m \to \infty} \left(\frac{2}{3}\right)^m \cdot m^4 \cdot \frac{1- \frac{1}{m^4}}{4+ \frac{m^7}{3^m}}=0$$
Answer: Hint: for any $m>0$, $d\in (0,1)$, it holds $n^m/d^n\to 0$...
Answer: HINT:
We have $$\frac{2^n(n^4-1)}{4\cdot3^n+n^7}<\frac{2^n}{4\cdot3^n}<\frac14\left(\frac23\right)^n$$


Retorno getInstallments Pagseguro

Question: O getInstallments do PagSeguro serve para retornar a quantidade de parcelas e o valor de cada parcela, ao informar um cartão e o valor da venda.
O retorno que obtenho é este:

Neste retorno cada item representa uma quantidade de parcelas e seu valor, o que não estou conseguindo é usar o foreach de alguma forma neste retorno e preencher um Select options.
Gostaria de preencher o select com a quantidade de parcela e o valor.
Para retornar os valores estou usando:
PagSeguroDirectPayment.getInstallments({
    amount: <?php echo $total_compra?>,
    brand: $("#bandeira").val(),
    maxInstallmentNoInterest: 2,
    success: function(response) {
        //console.log(response);

        bandeira = $("#bandeira").val();
        $("#parcelas_div").show(200);

        var options = "";
        var retorno_bandeira = response.installments.visa;

        for (var i = 0; i < retorno_bandeira.length; i++) {
            var quantidade = retorno_bandeira[i].quantity;
            var parcela = retorno_bandeira[i].installmentAmount;
            var valorTotal = retorno_bandeira[i].totalAmount;

            options += '<option value="' + quantidade + '" data-valor="' + parcela + '">' + quantidade + 'x de ' + parcela + ' = R$ ' + valorTotal + '</option>';
        }

        $("#parcelas").html(options);

    },
    error: function(response) {
        console.log(response);
    },
    complete: function(response) {
        console.log(response);
    }
});

O problema que está ocorrendo é o seguinte:
Se coloco na linha var retorno_bandeira = response.installments+"."+bandeira; retorno de todos os dados vem Undefined, mas, se adiciono o nome da bandeira diretamente na linha assim response.installments.visa; vem tudo normal, acredito que o problema esteja na forma de concatenar o nome da bandeira ao retorno.
Comment: Coloca aí suas tentativas pra gente dar uma olhada.
Answer: Você só precisa iterar sobre o array dentro de visa:

var parcelas = getInstallments(),
    visa     = parcelas.installments.visa;

for( var i = 0; i < visa.length; i++ ) {
  var quantidade = visa[i].quantity,
      parcela    = visa[i].installmentAmount,
      valorTotal = visa[i].totalAmount;

      // aqui você usa os valores definidos pra montar o select
}
Comment: Amigão, sua solução funcionou. Editei o cordo adicionando o código usado, pois tenho mais uma dúvida relacionado ao javascript, pode me dá mais uma força!
Answer:
Se coloco na linha var retorno_bandeira = response.installments + "." + bandeira, retorno de todos os dados vem Undefined, mas, se adiciono o nome da bandeira
  diretamente na linha assim response.installments.visa vem tudo
  normal, acredito que o problema esteja na forma de concatenar o nome
  da bandeira ao retorno.

Uma outra forma de acessar a propriedade do objeto é com a notação de colchetes:
bandeira = $("#bandeira").val();
var retorno_bandeira = response.installments[bandeira];
// ...

Retorno getInstallments Pagseguro


Como escrever e ler um arquivo .txt em Kotlin?

Question: Eu encontrei essa solução no stackoverflow english, porém aparece o erro unsolved reference em "it", "message" e "context"
import java.io.File

context.openFileOutput(filename, Context.MODE_PRIVATE).use {
    it.write(message.toByteArray())
}
val file = File(context.filesDir, "myfile.txt")
val contents = file.readText() // Read file```

Answer: Uma solução interessante que encontrei no site Tutorial Kart, foi que
em kotlin existe um método da classe File para criação de arquivos de texto chamado writeText(), ele irá criar um arquivo e se já existir ele irá sobrescrever o arquivo, para usar basta apenas instanciar um objeto a classe File e utilizar o método writeText():
val arquivo = File("dados-usuario.txt") //nos parênteses passe o nome do arquivo como parâmetro.
    arquivo.writeText("Nome: Luiz\n"+"idade: 10")//aqui você irá passar os dados

Prontinho! ao rodar o programa o arquivo será criado. Eu estou usando o Intellij então o arquivo será salvo em .../IdeaProjects/nomedoseuprojeto/arquivo.txt
Agora, para ler o arquivo você irá usar a classe bufferedReader() (existe outras maneiras de ler arquivos, mas esse funcionou melhor para mim) e o método readLines(), ficará assim:

val arquivo = File("dados-usuario.txt")
    arquivo.writeText("Nome: Luiz\n"+"idade: 10")
    val reader = arquivo.bufferedReader()
    val leitura = reader.readLines()
    for(line in leitura){
        println(line)
    }

Espero ter ajudado você que chegou até aqui, se quiser saber outros métodos recomendo ler esse tutorial:
https://www.tutorialkart.com/kotlin/kotlin-create-file/


Can Scalas manifest.erasure be correctly typed?

Question: I have a Java class that takes a generic type parameter and a class object related to that type:
public class Foo<T> {
    public Foo(Class<? extends T> type) {
    ...
    }
}

At first I thought I could make a clever wrapper for this in Scala:
class Bar[T](implicit m: Manifest[T]) {
    ...
    new Foo[T](m.erasure)
    ...
}

But this results in a compiler error similiar to this:
error: type mismatch;
found   : java.lang.Class[_$1(in value <local Bar>)] where type _$1(in value <local Bar>)
required: java.lang.Class[_ <: T]
class Bar[T](implicit m: Manifest[T]) { new Foo[T](m.erasure) }

I think I understand why this happens, but is there any way I could get the correct type of class and make this code compile?
Answer: How about m.erasure.asInstanceOf[Class[T]]?
By the way, see this question for an explanation of why erasure returns Class[_] and not Class[T].
Comment: As always, the answer was too simple. Thanks.


erratic failure of sessionAsSignerWithFullAccess

Question: The code below is a some test code that I have in an action button on an XPage. I need to get a handle on the current database with FullAccess in the code WFSUtils.sysOut just formats a printed message to the server console. Periodically the error message in the catch returns
2015-01-09 12:49:11 PM  HTTP JVM: WFS ~~~ Error in Update Demo 'sessionAsSignerWithFullAccess' not found
I am the signer of the XPage and the database is signed by the server ID. Sometimes it runs through just fine other time it fails with the message above. If I shut everything down then restart it will generally run but then start failing. It is very random and unpredictable.
debug = true;
try{

    if (debug) WFSUtils.sysOut("Starting YYY New SetupDemo");
    var serverName = database.getServer();
    var repID = database.getReplicaID();
    thisDB = sessionAsSignerWithFullAccess.getDatabase("","");
    thisDB.openByReplicaID(serverName,repID);
    if (debug) WFSUtils.sysOut( "SetupDemo Success" + thisDB.getTitle());
}catch(e){
    WFSUtils.sysOut("Error " + e.toString())
}finally{
    try{
        WFSUtils.recycleObjects([]);
        if (debug) WFSUtils.sysOut("SetupDemo Recycle Success");
    }catch(e){
        if (debug) WFSUtils.sysOut("SetupDemo recycle Failed");
    }

}

Answer: For one reason or another, it's important that all XPage elements be signed by the same ID when running. When they're not, sessionAsSigner and sessionAsSignerWithFullAccess get erratic as you describe - that may be the cause.
Comment: I have heard that but ensuring that there is a single signer of a database is pretty difficult particularly in a development environment. For whatever reason I have found that when I get that error then close the designer then open the XPage and execute the code it generally works, but not always. Very strange and very time consuming.
Comment: I signed the DB with my ID and now it works. So while developing should probably be signed by the person then sign it with the server in production.


Overwriting Kohana_Core

Question: Is is possible to overwrite Kohana_Core ?
I want to add another path to widgets (they aren't the same as modules) so i have to add theme into bootstrap.php as :
Kohana::Widget(array());

I don't want to edit the class Kohana_Core (system/kohana/Core.php) but just overwrite it.
I tried to add a new file called Core.php (Class Core extends Kohana_Core) into my APPPATH but no way.
I use Kohana 3.3
any idea ?
Answer: Get it !
Just add Kohana.php and not Core.php into APPPATH
Class Kohana extends Koahan_Core
{
   public static function Widget($widgets)
   {
    // Do something
   }
}

Overwriting Kohana_Core


Get all element contain or not some class

Question: I have html structure like

a

a1

b

b1

c

c1

d

d1

How can i get all element contain a or b or c class
$(".dv").each(function(){}); /// ? how to get

And how to get all element not contain a or b class
$(".dv:not(.a|.b)").each(function() {}); // ?how to get

Comment: As regards the `not`, this may or may not work: `.dv:not(.a,.b,.c)`. If it doesn't, you could try `.dv:not(.a):not(.b)`.
Comment: Just checking: you want all of the elements whose class is `a` or `b` or `c`, but you don't care about class `dv`? If so, then the selector `.a,.b,.c` is the correct one. If you want only the ones with class `dv` then it's a little more.
Comment: @Manngo Hi, I want them with `dv` class
Comment: Have you tried `$('.dv').find('.a,.b,.c')` ? This first finds the `dv` class, and then filters only the ones which match the second selector.
Answer: To select with or logic:
$( ".a, .b, .c" )

To select with not logic:
$( "div:not(.a, .b)" )

To select all .dv but without .d:
$( ".dv:not(.d)" )

Here's a snippet that counts all logics with the selectors above:

var orCount = $( ".a, .b, .c" ).length;
var andCount = $( "div:not(.a, .b)" ).length;
var notdCount = $( ".dv:not(.d)" ).length;

console.log('or logic count = ' + orCount);
console.log('and logic count = ' + andCount);
console.log('not d logic count = ' + notdCount);

a

a1

b

b1

c

c1

d

d1

Comment: Than you should use `not`, not `or` : `$( ".dv:not(.d)" )`
Comment: thankiu, but `or` logic i want with `.dv` class like `$( ".dv:(.a, .b, .c)" )` ?
Answer: The thing about jQuery is that it can take advantage of your skills in CSS, provided that the browser is up to date. If it is, then the following pure CSS selectors will do the job:
.dv.a, .dv.b, .dv.c {           /*  Matching Ones: */

}

.dv:not(.a):not(.b):not(.c) {   /*  Non Matching Ones: */

}

The following snippet will illustrate this:

.dv.a, .dv.b, .dv.c {
  color: red;
}

.dv:not(.a):not(.b):not(.c) {
  border: thin solid green;
}

a

a1

b

b1

c

c1

d

d1

Comment: thank, love use like css `.dv.a, .dv.b, .dv.c` do the trick :)
Comment: @DeLe Does that answer your question?


what's the definition of partial correlation for a population?

Question: is partial correlation only defined for a given sample? the definition based on residuals as on wikipedia seem to imply that's the case. is there a population definition for partial correlation?
Answer: This is comparable to correlation in sample / population for "normal" correlation.
Only in partial correlation, you talk about the effect of X on Y partialled out for Z.


Is this proof that if  $a_{n+1} = \sqrt{2 + \sqrt{a_n}}$ and $a_1 = \sqrt{2}$, then $\sqrt{2} \leq a_n \leq 2$ correct?

Question: Let $a_1 = \sqrt{2}$ and $a_{n+1} = \sqrt{2 + \sqrt{a_n}}$. Now I want to show by induction that $\sqrt{2} \leq a_n \leq 2$ for all $n$.
The base case is $n=1$ and it is clear $\sqrt{2} \leq a_1 \leq 2$. Then I assume that $\sqrt{2} \leq a_n \leq 2$ holds and I want to show $\sqrt{2} \leq a_{n+1} \leq 2$.
Then I note that $\sqrt{2} \leq a_{n+1} \leq 2 \implies \sqrt{2} \leq \sqrt{2 + \sqrt{a_n}} \leq 2$. By squaring both sides I get $2 \leq 2 + \sqrt{a_n} \leq 4$. Then by subtracting $2$, I get $0 \leq \sqrt{a_n} \leq 2$. This means that $0 \leq a_n \leq 4$. This is ok because I assumed $0 \leq \sqrt{2} \leq a_n \leq 2 \leq 4$.
Edit
How about this: Since I know $\sqrt{2} \leq a_n \leq  2$. Then it is clear that $0 \leq a_n \leq 4$. By taking square roots I get $ 0 \leq \sqrt{a_n} \leq 2$. Now if I add 2, $2 \leq \sqrt{a_n} + 2 \leq 4$. Taking another square root I get $\sqrt{2} \leq \sqrt{\sqrt{a_n} + 2} \leq 2$. So $\sqrt{2} \leq a_{n+1} \leq 2$.
Answer: Note that you want to show the case $n$ implies $n+1$, but you're going the other way.
The good thing about this sequence is the inductive step is indeed easy.
The base case is $\sqrt 2 \leq a_1 \leq 2$
We now assume $\sqrt 2 \leq a_n \leq 2$
Take a square root, then add two, then take a square root.
$$\sqrt{\root 4 \of 2+2} \leq \sqrt{2+\sqrt a_n}\leq \sqrt{\sqrt2+2}$$
$$\sqrt{\root 4 \of 2+2} \leq a_{n+1}\leq \sqrt{\sqrt2+2}$$
Note that since $\sqrt 2  + 2 < 4 \Rightarrow \sqrt {\sqrt 2  + 2}  < 2$ and similarily $2 < \root 4 \of 2  + 2 \Rightarrow \sqrt 2  < \sqrt {\root 4 \of 2  + 2} $
Add: Your edit makes perfect sense.
Comment: @Student : as I mentioned in my comment to Peter, it doesn't matter how you decide to prove that the $n$th case implies the $(n+1)$th case ; the only thing that is important is that you do prove it. Peter decided to construct the $(n+1)$th case out of the $n$th, i.e. he wrote the $n$th, assumed it true, and then did some computations to deduce that the $(n+1)$th is true by making it appear little by little. Let's say his technique is "a little harder to think to do in general, but is more clean mathematically speaking".
Comment: @Peter : What he meant is that he thought that he had to write what the $(n+1)$th case meant, and then make its statement somehow equivalent to the $n$th statement in order to conclude that the $(n+1)$th is true because the $n$th is.
Comment: @PatrickDaSilva I totally agree with you. Thanks for explaining it.
Comment: I thought you start with the ($n+1$)th case and break it down to the $n$th case when doing induction.
Comment: Think about the definition of an inductive set $S$.
a. $1\in S$
b. $n \in S \Rightarrow n+1\in S$
What would you get if you prove $n+1$ implies $n$? Induction works because we move from $n$ to $n+1$, which, having proven the base case $1$, transmits the property to $2$, $2$ to $3$, and so on...
Comment: @PatrickDaSilva: Could you take a look at my edit?
Comment: @Student ; this is essentially what "getting the $(n+1)$th case out of the $n$th" is about.
Comment: @PatrickDaSilva That was what I was trying to explain.
Comment: @Peter : I meant that he understood the logic behind induction, but his mechanics of "how to prove $n \rightarrow n+1$" were different and that is what his comment was about.


No appropriate default constructor available for std::unique_ptr

Question: This is a continuation of my previous post. Since it has already been closed I decided to make a new post. I removed half of the code to make it more readable.
Some of the posts I read:
Smart pointers with SDL
Is it possible to use SDL2 with smart pointers?
Couple of questions about SDL_Window and unique_ptr
class cGraphics
{
public:
    //  Creator functions
    std::unique_ptr<SDL_Window, decltype(&SDL_DestroyWindow)> Create_Window(int xWin, int yWin);

    //  ctor & dtor
    cGraphics() : m_Window(nullptr, SDL_DestroyWindow) {}
    cGraphics(int xWin, int yWin);
    ~cGraphics();
private:
    std::unique_ptr<SDL_Window, decltype(&SDL_DestroyWindow)> m_Window;

};

cGraphics::cGraphics(int xWin, int yWin)
{
    m_Window = std::move(Create_Window(xWin, yWin));

    if (m_Window == nullptr)
    {
        throw "SDL_Window or SDL_Renderer not ready!";
    }
}

cGraphics::~cGraphics()
{
    IMG_Quit();
    SDL_Quit();
}

std::unique_ptr<SDL_Window, decltype(&SDL_DestroyWindow)> cGraphics::Create_Window(int xWin, int yWin)
{
    return std::unique_ptr<SDL_Window, decltype(&SDL_DestroyWindow)>(SDL_CreateWindow("SDL Window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, xWin, yWin, SDL_WINDOW_SHOWN), SDL_DestroyWindow);
}

The compiler complains that:
'std::unique_ptr<SDL_Window,void (__cdecl *)(SDL_Window *)>::unique_ptr': no appropriate default constructor available

I understand that this error usually shows up when the compiler cannot locate a default constructor for some of the members. However this is not true as I explicitly declared a default value for the std::unique_ptr.
If the compiler is actually complaining about SDL_Window, which is an incomplete type (a C struct), what can I do about this?
Comment: As an aside, consider defining your own deleter manually (`struct Invoke_SDL_DestroyWindow { void operator()(SDL_WINDOW* p) const noexcept { SDL_DestroyWindow(p); } };`) and use that instead of lugging around additional pointers and indirecting through them.
Comment: @Justin: Or maybe it might be easier just to [add an explicit template-specialization](https://en.cppreference.com/w/cpp/language/extending_std): `template <> inline void std::default_delete::operator()(SDL_Window* p) const { SDL_DestroyWindow(p); }`. http://coliru.stacked-crooked.com/a/91120d518230a816
Comment: @Deduplicator That is on the borderline of what's allowed. I would strongly recommend not doing it. It makes it very easy to make mistakes. Consider how `SDL_Window*` is created by `SDL_CreateWindow`, not via `new SDL_Window;`. Thus, after writing that code, if `std::make_unique(...)` were written, you'd have undefined behavior. Simply put, that's extremely easy to mess up.
Comment: What @Deduplicator says is very true. `std::unique_ptr` with a deleter function pointer is twice the size as one without it. It's a waste of space. You're lugging around an extra pointer that you never change, and it also makes it harder for the compiler to optimize (it might not be able to tell that the deleter function never changes). If it's too much of a pain (IMO it is), write a simple wrapper that creates a deleter from a function pointer: https://godbolt.org/g/sM75NC (C++17, but you can get close to that syntax before it)
Comment: @Justin: As `SDL_Window` is incomplete, the call to `std::make_unique` will result in a compilation-error. No danger there.
Comment: @Deduplicator Yes, I assumed so. However, if you tried to do that in the general case, it's easy to go wrong. If I saw that code in a code review, I'd be really skeptical.
Answer: A std::unique_ptr<SDL_Window, decltype(&SDL_DestroyWindow)> is not default constructable.  That means in
cGraphics::cGraphics(int xWin, int yWin) ***
{
    m_Window = std::move(Create_Window(xWin, yWin));

    if (m_Window == nullptr)
    {
        throw "SDL_Window or SDL_Renderer not ready!";
    }
}

When you reach the part *** the compiler is going to try and default construct m_Window since you didn't do so in the member initialization list.  That attempt from the compiler to default construct m_Window is what causes the error.  We can fix this by moving m_Window = std::move(Create_Window(xWin, yWin)); out of the constructor body and putting it intp the member initialization list like
cGraphics::cGraphics(int xWin, int yWin) : m_Window(Create_Window(xWin, yWin))
{
    if (m_Window == nullptr)
    {
        throw "SDL_Window or SDL_Renderer not ready!";
    }
}

If you don't want to do that then you can delegate to the default constructor and then assign to m_Window like you were doing originally.  That would look like
cGraphics::cGraphics(int xWin, int yWin) : cGraphics()
{
    m_Window = Create_Window(xWin, yWin);

    if (m_Window == nullptr)
    {
        throw "SDL_Window or SDL_Renderer not ready!";
    }
}

Comment: You do not need `std::move` there - the `CreateWindow` function is already returning a temporary.
Comment: Aside: the `std::move` is unnecessary in all these bits of code.
Comment: @SergeyA I've removed the moves, didn't see they were redundant, thanks.  As far as why delegating works, it is because the OP correctly initializes the pointer to `nullptr` in the default constructor.
Comment: @NathanOliver, sure I figured it out after I typed the comment (and even was within grace window to remove this evidence of my stupidity!) :)
Comment: @NicholasHumphrey, as a matter of fact, initializer list is more elegant than delegating constructor.
Comment: @NicholasHumphrey use `insert` or `emplace` to insert elements, `find` for lookup. You won't be able to use subscript operator, unfortunately. You also seem to misunderstand the cause of the problem. It is not that C structs do not have default ctor - the do! It is the `unique_ptr` with deleter which does not have one.
Comment: @NicholasHumphrey Something like `m_TextureMap.emaplce("some string", function_that_returns_uinique_ptr());` should work.
Comment: @NicholasHumphrey You might be better off asking another question.  Without seeing a [mcve] it's hard for me to say what the problem is.
Comment: Thanks! This definitely solves my problem. The delegation is more elegant I guess, but the key is that I forgot to inform the compiler how to initialize m_Window (I thought I could use the method inside of the ctor which is wrong).
Comment: @SergeyA @aschepler Thank you guys, yeah you are right, they return a temp object already so no need to `std::move`.
Comment: @SergeyA Thanks! Good to know. BTW can I ask an additional question? Suppose I put some `std::unique_ptr` of `SDL` objects (e.g. `SDL_Texture`, like `SDL_Window` they are just C structs, so no default ctor) into a container, say `std::unordered_map`, how can I avoid the same error msg? Do I need to wrap the `std::unique_ptr` with another class and write a default ctor? Seems to be too much though.
Comment: Thanks for clarifying that, I didn't know C struct also has ctor, my fault~ Yes I'm using `emplace` but get the same complaint (Basically I have a `std::unordered_map> m_TextureMap`, and compiler complains that there is no default ctor for that unique pointer. The only way I can think about is to create a wrapper class for that unique pointer and then create a ctor for it, because I cannot use the same method in this post. Is there a better way?
Comment: @NathanOliver Thanks. I'm indeed using something similar: `m_TextureMap.emplace(texid, CreateTexture(texres, r, g, b));` in which m_TextureMap is the `std::unordered_map` and `CreateTexture()` returns a unique pointer. I think the error is of similar reason I encountered in my main post?
Comment: Sure I'm going to open another post. :D
Answer: Here is how you defined your unique_ptr:
std::unique_ptr<SDL_Window, decltype(&SDL_DestroyWindow)> m_Window;

That means, it's constructor has to be called with an instance of the custome deleter, in your case, function SDL_DestroyWindow - remember, you told the pointer what is deleter's type, not what the actual deleter (a function pointer in your case).
To make this code work, you have to properly construct your pointer with a deleter instance, for example:
cGraphics::cGraphics(int xWin, int yWin) :
                     m_Window{Create_Window(xWin, yWin)} {...}


Why are 1/2 (or 3/4, etc) violins called that way if they are not 1/2 size?

Question: On the question Do 1/2 size violins sound at normal pitch? I found out that 1/2 violins are actually ~86% of a full size violin.
What do the fractions 7/8, 3/4, 1/2 etc for violin sizes represent, if they don't represent the body size or the scale length of the instrument?
Answer: It's just a naming convention for the scale length. The numbers don't actually equate to anything. See the quote below:

Smaller scale instruments are used extensively to teach younger
  players. The size of these is described by a "conventional" fraction
  that has no mathematical significance. For example, a 7/8 violin has a
  scale of about 317 mm, a 3/4-size instrument a scale of 307 mm, a
  half-size one 287 mm, and a quarter-size one 267 mm. 1/8, 1/10, 1/16
  and 1/32 and even 1/64 violins also exist, becoming progressively
  smaller, but again in no proportional relationship. (A full-size
  instrument is described as 4/4.) - Wikipedia

While it doesn't have a math reason, it is more practical remember simple a fraction over a seemingly random number.
Answer: Try this. It's to do with volume. Most people know the volume of a box is length time width times height. Using your numbers, if each of those measurements is 0.8 of the full size then the volume 0.8x0.8x0.8 times the size, and 0.8x0.8x0.8 is 0.512 - pretty close to half size. I haven't checked the other fractions perhaps you could see if my hunch works.
Comment: Well… it's not: By your hypothesis, a 1/8 violin would be 50% the size of a 1/1, whereas it's actually 72%. (It took me 3 minutes to google and check the hypothesis)


Use postfix to relay mail based on sender

Question: I recieve mail from a server where I can specify one .forward mail where all mails get forwarded to. However, those mails have different senders, and one of them is important contact mail while the other is log mail. What I want to achieve is filter these messages and send them to two different domains.
In psuedo code:
if from == LOG_SENDER:
    forward_to("firstname.lastname@example.com")
else:
    forward_to("email@example.com")

Note that the original mal comes from outside my configuration reach. My current solution is having manual filters in thunderbird that just drop the logs in a seperate folder. But I would like to have the filtering as early as possible.
Is this possible with postfix?
My current setup is Postfix & Dovecot with SASL auth.
Comment: Have you looked at dovecot and sieve?
Comment: +1 for sieve suggestion
Comment: @NickW Could you create answer based on your comment?
Comment: I'm not sure how to do it with Sieve, but if can be easily done with `procmail(1)` iff that's used as MDA
Comment: @AndrzejA.Filip: I have added my own answer.
Answer: Okay, since @NickW seems to unavailable, I will explain what I did based on his suggestion: I used sieve (already using dovecot 2) to create the filter I needed.
I actually moved from forwarding to sorting into a specific folder but alterting that in case I ever need something different is easy.
In the protocol lda section I add a line to active Sieve:
protocol lda {
  ...
  mail_plugins = $mail_plugins sieve
}

Then set the path for sieve scripts:
plugin {
    sieve = /etc/dovecot/sieve-scripts/%u.sieve
}

And the final script for my user:
require ["fileinto"];

if address :is "from" "email@example.com" {
    fileinto "Logs";
}

With these settings, all my mail gets sent into the Logs folder if it is from firstname.lastname@example.com. Very easy to set up once you figured out how to activate sieve (I find the documentation on that a bit lacking).
Comment: Sorry, on the weekends I'm usually nowhere near a computer ;) Glad you got it going!


Implementing sigma in python/R with fewer loops

Question: I want to implement the following function in python:

I will write the code using 2-loops:
for i in range(5):
     for j in range(5):
          sum += f(i, j)

But the issue is that I have 20 such sigmas, so I will have to write 20 nested for loops. It makes the code unreadable. In my case, all i and j variables take same range (0 to 4). Is there some better of coding it?
Answer: You can use itertools.product to get cartesian product (of indexes for your cases):
>>> import itertools
>>> for i, j, k in itertools.product(range(1, 3), repeat=3):
...     print(i, j, k)
...
1 1 1
1 1 2
1 2 1
1 2 2
2 1 1
2 1 2
2 2 1
2 2 2

import itertools

total = 0
for indexes in itertools.product(range(5), repeat=20):
    total += f(*indexes)

You should use range(1,6) instead of range(5) to mean 1 to 5. (unless you meant indexes)
Do not use sum as a variable name, it shadows builtin function sum.
Answer: Create Arrays by using Numpy .
    import numpy as np

    i = np.asarray([i for i in range(5)])
    j = np.asarray([i for i in range(5)])
    res = np.sum(f(i,j))

so you can avoide all loops. Important to note is that the function f needs to be able to work with array (a so called ufunc). If your f is more complicated and i doesnt allow arrays you can use numpys  vectorize functions. Not as fast as a ufunc but better that nested loops :
    from numpy import vectorize

    f_vec = vectorize(f)

If you want to stay with plain python because you don't want arrays but lists or the types don't match for an array, there is always list comprehension which speeds up the loop. Say I and J are the iterable for i and j respectively then:
    ij = [f(i,j) for i in I for j in J ]
    res = sum(ij)


Read only permissions on some Linux logs

Question: I would like to limit a certain user (let's call it logger) to be able to only read some (not all) logfile (web, php framework, radius,etc).I am not sure how to do it the "best" way.
So far I have a chrooted sftp account for my user and I bind mount into his homedir (/home/logger) the required log folders, eg :

/var/log/nginx  /home/logger/logs/nginx none _netdev,bind,defaults 0 0

and here is the lgos dir permissions :

dr-xr--r-- 5 logger logger 4096 mars  12 10:09 logs

However I had to add this user to certain groups (www-data, freerad).

logger : logger www-data freerad sftp

I don't think this is the proper way to do it. Moreover, user can delete some files (the www-data group has r+w permissions on the logs from the symfony app).
Ideally, I wish my user to have the least possible privileges (which means RO, I believe), and still be able to review all the logs he requires access to.
Can you please give me some hints on how you would do such a thing?
Thanks in advance.
EDIT : Following Arribah answer I have tried to use ACL, eg:

getfacl radius/radius.log

# file: radius/radius.log
# owner: freerad
# group: freerad
user::r--
group::r--
group:logger:r--
mask::r--
other::---

logger user is inside logger group:

groups logger
logger : logger sftp

I created a radius dir (in /home/logger):

drwxr-xr-x 2 root   root   4096 mars  16 14:29 radius

Then I used some symbolic linking:

lrwxrwxrwx 1 root root 30 mars  16 14:29 radius/radius.log -> /var/log/freeradius/radius.log

Now I try to log via SFTP with logger to his chrooted homedir:
I can see files and folders and folders names, however if i try to get a file I have a "file not found" error trying to get that file radius/radius.log
I am really feeling stupid with this issue. :/
Answer: If you provide read permission for the user to the logs directory, this does not ensure that the user has read permission (or any other permission) to the files inside it. You need to provide read permission for this user to each log file separately.
Most probably, this is the reason you need to add the reader to the specified groups, it is because those groups have group permission to the log files in question. You can ensure that by running

ls -l

in the logs folder and check in which group each file belongs to.
In your scenario, the most correct way to achieve what you ask is by setting ACLs, which is the strongest unix tool for the job.
Have a look at "ACL: Using Access Control Lists on Linux", it is a big blog post but it describes all the steps perfectly and simply enough to get the feeling.
If you need a more quick-n-dirty solution (which I DO NOT recommend, unless you are not in a production environment), you can just take your user out of every group, and then set the 'Others' permission set to r--, (or xx4 for your chmod octal representation).
EDIT: I ignored the fact that you're trying to do this this on a chrooted environment. In this case, symlinks will not work with ftp (or sftp for that matter) due to the nature of symlinks themselves. A nice explanation lies here, although it seems that I tend to link only big articles.
Nevertheless, you can somewhat achieve the same behavior using mount --bind, which will make the log directory available inside the home dir of the logger user:
mount --bind /var/log /home/logger/logs/

And this will provide you with a logs directory containing everything found inside /var/log. From that point, you can allow the logger group read access only to the specific logs you want and nothing else, so that he won't be able to read e.g. /var/log/auth.log etc. Don't forget to add access to the respective parent folders, because otherwise your user will only be able to access the logs by typing in the full path, which can be sometimes frustrating.
Comment: Thanks a lot for you answer. Looks like ACL is what I am looking for. However I am trying to implement it without any luck yet and I edited my 1st post according to what i did.
Comment: What you are describing in your edited post is a totally different problem. You can't use symlinks for chrooted environments.
I am editing my original answer to explain it right now :)


A Study of Continuity of a given Function

Question: I am trying to figure out if the following function is in fact continuous:
given
$$f(x,y) = \left\{\begin{array}{cc} \frac{|y|-|x|}{y^2} & |x| < |y| \\
                                        0 & |x| \geq |y| \end{array}\right.$$
I am studying the continuity of the function
$$g(y) = \int_{-1}^1 f(x,y) dx, y \in [-1,1].$$
$x$ and $y$ take on the domain $[-1,1].$ I am wondering what is the most
reasonable way to begin exploring the continuity of this function, since it
seems to me that the many absolute values that make up this particular function
makes the splitting of the integral rather hectic. Any recommendations on how
one goes about dealing with integrals of absolute value functions?
Comment: The map $x \mapsto f(x,y)$ is even, hence you can write the integral as $2 \int_0^1$. Since $y \mapsto f(x,y)$ is even we see that $g$ is even, hence you only need to deal with $x,y \ge 0$ which should not be that 'hectic'.
Comment: Note: Let $a>0$. $|x| < a \iff -a < x < a$. Now set $a = |y|$. Since the integral is only over $x$, it's simple enough to see that it equals $\int_{-|y|}^{|y|} ...$. Now split this in the usual manner into integrals over which $x$ is positive and negative.
Answer: Regarding the the question about continuity, suppose you approach $0$ along the $y$ axis.  $f(x,y)$ gets large as $y$ approaches $0.$  Now approach along the $x$ axis.  $f(x,y) = 0$ the whole way in.  $f(x,y)$ is not continuous.
For the integral. $f(x,y)$ is an even function (for both x and y).  We can look at the 1st quadrant and quadruple the results.
$4\int_0^1\int_0^y \frac {y-x}{y^2} dx\, dy\\
4\int_0^1 \frac {y-\frac12 x^2}{y^2}|_0^y dy\\
4\int_0^1 \frac {y-\frac12 y^2}{y^2}dy\\
4\int_0^1 \frac 1y - \frac12 dy\\
4(\ln y - \frac 12 y)|_0^1$
which doesn't converge at $0$
Comment: wolframalpha says that $\int_{-1}^{1} \frac{|y| - |x|}{y^2} dx = \frac{2|y| - 1}{y^2}$. Well $\lim_ {y \to 0} \frac{2|y| - 1}{y^2} = - \infty$. I believe I interpret the question different from you.
Comment: Oh I see my where I went wrong, sorry. :)


ejabberd 2 user MUC vs. normal 1-to-1 chat

Question: I've been working with ejabberd for some time now, but due to some recent issues and requirements, I'm curious about something.
If I create a MUC room with 2 users in it, does it differ from normal 1-to-1 chat messaging (performance wise)?
What happens if I always use MUCs for all 1to1 chats?
Does it have any performance overheads or disadvantages?
Do my connections suffer from performance penalties, and does this generally consume more resources or impose any kind of restrictions or penalties?
Any help or insights would be much appreciated.
Comment: Cross-posts: http://superuser.com/q/898698/151741 & http://serverfault.com/q/680913/131794
Answer: I don't know how ejabberd implements XMPP, but from protocol perspective:

"Normal" one-to-one chats are stateless server-side. All context (message history etc) is maintained by client. Server just relays messages back and forth. On the other hand, Multi User Chats are maintained by server. Resources (participants list, room settings, message history) have to be stored somewhere, and that responsibility lies on server.
One to one messages are "ad-hoc". When one party wants to chat, they just send a message to recipient. MUC, on the other hand, has to be created, configured prior to starting conversation, and the other party has to be invited to join MUC room before conversation can begin. This adds complexity and/or time.
Multi User Chats give more features, but it is debatable whether they make sense in context of one-to-one conversations (eg. does kicking someone out of conversation make sense?). On the other hand, you probably have to properly configure chatrooms, so that they are not discoverable (one cannot see list of conversations), third parties cannot join them (unless invited to), that users cannot freely change nicknames etc.
Answer: Yes, MUC has an overhead which is the MUC process management itself.
Comment: Thank you for your response. I initially thought it would be a stupid idea to have many 2 user MUCs. But it is good to hear from the source.
Comment: I am not sure what you want to build, but you may want to look at option to convert one to one chat to MUC as defined in XEP-0045 specification.


Conditional Probability Question - Probability on Quiz

Question: I am having trouble with a problem involving conditional probability. The question is as follows:
A student is taking a history quiz, which consists of $6$ multiple choice questions and each multiple choice question has $5$ answer options (and only $1$ of these $5$ answer options are correct). Suppose that the student learned the material asked in question $n$ with probability $p_n$; where $n =1,2, \ldots,6$. If the student learned the material asked in the question, then the student is guaranteed to answer that question. If they did not learn the material in question $n$, then that student guesses the answer to that question at random.
[a] What is the probability that the student learned all of the material covered on the exam, if they got a perfect score.
[b] What is the probability that the student got a perfect score 6/6 and did not learn any material that was covered on the exam?
[c] If $p_n = 1/2$, for all $n =1,2, \ldots,6$, find and simply the answers found in [a] and [b] as much as possible.

When beginning the problem, I first defined the following:
A: student answered $n$-th question correctly
B: student learned the material for $n$-th question
\begin{align*}
P[A|B]& =1;\\
P[A|B^C]& =1/5;
\end{align*}
where student chooses randomly.
$$P[B]=P_n;$$ where $n = 1,2, \ldots,6$

For part [a], I have the following:
P[student learned the material | answered correctly]
\begin{align*}
P[B|A] & = \frac{P[A|B]P[B]}{P[A|B]P[B]+P[A|B^C]P[B^C]}\\
       & = \frac{P_n}{P_n +(1/5)(1-P_n)}
\end{align*}
Now, we assume that material for each question are different. So, each question is independent.
P[Student learned all material | answered all questions correctly]
$$\Pi_{n=1}^6 P[B|A]$$
$$\Pi_{n=1}^6 \frac{(P_n)}{P_n +(1/5)(1-P_n)}$$
For part [b], I have the following:
P[Student did not learn the material for nth question | they answered correctly]
$$=P[B^C\cap A]=P[A|B^C]P[B^C]$$
$$=P[B^C\cap A]=\frac{1}{5}(1-P_n)$$
P[Student did not learn any material | answered question correctly]
$$\Pi_{n=1}^6 \frac{1}{5}(1-P_n)$$
For part [c], I have the following:
[a] Becomes:
\begin{align*}
\Pi_{n=1}^6 \frac{.5}{.5+.2(1-.5)} & = \left(\frac{.5}{.5+.10}\right)^6\\
& =0.3349
\end{align*}
$$33.49\%$$
[b] Becomes:
$$\Pi_{n=1}^6 P_n = (\frac{1}{5}(1-P_n))^{6}=0.000001=0.0001\%$$

Any help or suggestions for this question and my answers would be greatly appreciated.
Comment: In addition to the errors in part b) noted in an answer below, there are algebra errors in the steps that follow. Of course this part of the answer had already gone wrong, but it might help in the future to look at how to be more accurate in transcribing results and how to avoid algebraic errors.
Comment: No need to apologize to **me** for the errors. I just worry that something similar could happen when it matters, for example on a test.
Answer: You misunderstood the question in part b). This is not a conditional probability like in part a). The "if" and "and" are bold for a reason; part a) asks for a conditional probability whereas part b) asks for the probability of the intersection of two events.
(Also, you seem to have made an error in copying the result for $P[B\mid A]$ from part a) to part b), but that's not relevant to the actual question in part b).


How do you tree walk JSON via Jackson 2 JsonNode?

Question: This was a bit of an exercise in frustration made worse by the fact that I couldn't find any answers to this question.  So I'm going to answer the question here.
What I find most difficult to understand was that JsonNode doesn't have any getName() or similar method which I was expecting given that JSON is a name:value data type.  Though I realised after working out this solution that arrays aren't name:value.
See answer below.
Answer: package treeWalker;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;

public class TreeWalker
{
    public JsonNode convertJSONToNode(String json) throws JsonProcessingException, IOException
    {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode jsonNode = mapper.readTree(json);

        return jsonNode;
    }

    public void walkTree(JsonNode root)
    {
        walker(null, root);
    }

    private void walker(String nodename, JsonNode node)
    {
        String nameToPrint = nodename != null ? nodename : "must_be_root";
        System.out.println("walker - node name: " + nameToPrint);
        if (node.isObject())
        {
            Iterator<Map.Entry<String, JsonNode>> iterator = node.fields();

            ArrayList<Map.Entry<String, JsonNode>> nodesList = Lists.newArrayList(iterator);
            System.out.println("Walk Tree - root:" + node + ", elements keys:" + nodesList);
            for (Map.Entry<String, JsonNode> nodEntry : nodesList)
            {
                String name = nodEntry.getKey();
                JsonNode newNode = nodEntry.getValue();

                // System.out.println("  entry - key: " + name + ", value:" + node);
                walker(name, newNode);
            }
        }
        else if (node.isArray())
        {
            Iterator<JsonNode> arrayItemsIterator = node.elements();
            ArrayList<JsonNode> arrayItemsList = Lists.newArrayList(arrayItemsIterator);
            for (JsonNode arrayNode : arrayItemsList)
            {
                walker("array item", arrayNode);
            }
        }
        else
        {
            if (node.isValueNode())
            {
                System.out.println("  valueNode: " + node.asText());
            }
            else
            {
                System.out.println("  node some other type");
            }
        }
    }
}

And a Unit test to exercise (with no asserts!  Sorry).
package treeWalker;

import java.io.IOException;

import org.junit.Test;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;

public class TreeWalkerTest
{
    TreeWalker treeWalker = new TreeWalker();

    private String getJSON()
    {
        String json = "{\"a\":\"val_a\",\"b\":\"val_b\",\"c\":[1,2,3]}";
        return json;
    }

    @Test
    public void testConvertJSONToNode() throws JsonProcessingException, IOException
    {
        String json = getJSON();

        JsonNode jNode = treeWalker.convertJSONToNode(json);

        System.out.println("jnode:" + jNode);

    }

    @Test
    public void testWalkTree() throws JsonProcessingException, IOException
    {
        JsonNode jNode = treeWalker.convertJSONToNode(getJSON());

        treeWalker.walkTree(jNode);
    }
}

Oh, and the build.gradle:
apply plugin: 'java'
apply plugin: 'eclipse'

repositories {
    mavenCentral()
}

dependencies {
    compile 'org.slf4j:slf4j-api:1.7.5'
    compile 'com.fasterxml.jackson.core:jackson-core:2.4.3'
    compile 'com.fasterxml.jackson.core:jackson-databind:2.4.3'
    compile 'com.fasterxml.jackson.core:jackson-annotations:2.4.3'
    compile 'com.google.guava:guava:18.0'

    testCompile "junit:junit:4.11"
}

Comment: Thanks!  I wish it wouldn't have used com.google.common.collect.Lists though.
Comment: This is already somewhat older, but it perfectly fits my needs for a piece of production code (and I couldn't be bothered to figure this out by myself, too much stress already).  Just changed the "walker" method name to "walk", and modified the "walkTree" method signature to taken an additional Action parameter. Your original authorship is mentioned in the sources!
Answer: This is just an updated variation on HankCa's excellent answer.  Under Java 8 and later, you can use Iterator.forEachRemaining() to loop through and you can externalize the consumer.  Here's an updated version:
package treeWalker;

import java.io.IOException;
import java.util.function.BiConsumer;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class TreeWalker
{
    public JsonNode convertJSONToNode(String json) throws JsonProcessingException, IOException
    {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode jsonNode = mapper.readTree(json);

        return jsonNode;
    }

    public void walkTree(JsonNode root, BiConsumer<String, String> consumer)
    {
        walker(null, root, consumer);
    }

    private void walker(String nodename, JsonNode node, BiConsumer<String, String> consumer)
    {
        String nameToPrint = nodename != null ? nodename : "must_be_root";
        if (node.isObject())
        {
            node.fields().forEachRemaining(e->walker(e.getKey(), e.getValue(), consumer));
        }
        else if (node.isArray())
        {
            node.elements().forEachRemaining(n->walker("array item of '" + nameToPrint + "'", n, consumer));
        }
        else
        {
            if (node.isValueNode())
            {
                consumer.accept(nameToPrint, node.asText());
            }
            else
            {
                throw new IllegalStateException("Node must be one of value, array or object.");
            }
        }
    }
}

Here's the unit test class (Now in Junit5):
package treeWalker;

import java.io.IOException;

import org.junit.jupiter.api.Test;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;

public class TreeWalkerTest
{
    TreeWalker treeWalker = new TreeWalker();

    private String getJSON()
    {
        String json = "{\"a\":\"val_a\",\"b\":\"val_b\",\"c\":[1,2,3]}";
        return json;
    }

    @Test
    public void testConvertJSONToNode() throws JsonProcessingException, IOException
    {
        String json = getJSON();

        JsonNode jNode = treeWalker.convertJSONToNode(json);

        System.out.println("jnode:" + jNode);

    }

    @Test
    public void testWalkTree() throws JsonProcessingException, IOException
    {
        JsonNode jNode = treeWalker.convertJSONToNode(getJSON());

        treeWalker.walkTree(jNode, (a,b)->System.out.println("name='" + a + "', value='" + b + "'."));
    }
}


String concat with conditional (Thymeleaf + SpringEL)

Question: I have the object product with type (string) and trade (boolean).
I want to append the product type and "trade" if trade is true.
The code is working:
th:classappend="${product.type}"

As well as:
th:classappend="${product.trade}? trade"

But I want to concat both and I'm failing at with.
Example of what I want but I didn't find how to.
th:classappend="${product.type} + ${product.trade}? trade"

Answer: Can you try this and tell me if this worked for you
th:classappend="${product.trade ? 'Trade'  +' '+ product.type : product.type}"

Comment: Awesome dude! It worked with an adjustment: ${product.trade ? 'Trade' +' '+ product.type : product.type}. Can you explain me the second part? "product.type : product.type" I don't understand this sintax, why can't we just use "product.type"? Thank you very much, so bad I don't have enough reputation to upvote, hope someone does!
Comment: Glad that my answer helped you. The expression that I wrote is in the form of "boolean statement ? result if true : result if false " , so if product.trade is true then have as classappend Trade and empty space and tha value of product.type otherwise have only the value of product.type. Hope it makes sense. Let me know if you need any more clarification
Comment: Yeah, I got it. For some reason I was understanding the boolean statement as ending after trade. But then after your explanation I realized that everything is part of the boolean statement and it was kinda obvious what's happening. Thank you again!
Answer:

or

or

      trade


Drupal site does not show well when SSL is enabled

Question: We have our site hosted on our Virtual Ubuntu 12.0 LTS. I am converting it to HTTPS. We are using Secure Login so that anonymous sessions are via HTTP or HTTPS and authenticated sessions only via HTTPS.
When I enable /var/etc/apache2/sites-available/site-ssl ->
On IE, I get this message "Only secure content is displayed" Click here to show all content for every page we navigate to. When I accept to show all content, the website renders on IE 11.
The CSS is not being picked up at all on a chrome browser ( Version 34.0.1847.116)

I have attached the screen of the site. You will see the menus are not in place. The flex slider images are one below the other.
Any ideas or help to fix this is appreciated !
Answer: You get this message from MSIE because the page has a mixture of secure and insecure content.
The culprit is usually inline/embedded content (images, iframes, javascript, css, etc.) that originate from a non-secure URL. Chrome just refuses to load it, causing the error you see To fix it, you need to locate those elements of the page, and replace them with secure versions.
To locate for these elements of the markup (unless they are obvious now that you know what to look for), use FireBug (requires that you use FireFox instead of MSIE/Chrome) or just press CTRL+uin MSIE to analyze the markup.  In the markup, search for inline/embedded content hyperlinked with URLs starting with http: (instead of https:).
If all your links are internal (i.e. pointing to stuff below the webroot of the same server), you can eliminate the problem by dropping the scheme element of the URL (as suggested in a comment below by @JohnathanElmore).
In other words: if your server is example.com and you currently have the following URL reference as part of your theme:
src="http://example.com/sites/all/modules/spamspan/spamspan.js?somequerystring"

you should replace it with the following:
src="//example.com/sites/all/modules/spamspan/spamspan.js?somequerystring"

or even:
src="/sites/all/modules/spamspan/spamspan.js?somequerystring"

I can't tell you exactly how to go about making these replacements without knowing what you can and cannot do on your site. (If it was my site, I would simply edit the theme templates and clear alll caches. But I've no way of knowing whether this option is available to you.)
Comment: I'd recommend replacing any http:// or https:// with simply ://, which will tell the browser to use whichever protocol the page was loaded with.
Comment: Err, instead of ://, just use //
http://stackoverflow.com/questions/550038/is-it-valid-to-replace-http-with-in-a-script-src-http
And yes, make sure the server you're linking to allows https...
Comment: The images were uploaded through a basic page.. upload image.
How should we replace these elements of the page, and replace them with secure versions?

Site was developed and content was updated and then the site was enabled with SSL.

When we analyze the markup... the CSS/modules/libraries are all pointing to http but not https

http://testsite.cs.stonybrook.edu/sites/all/themes/site/css/cdda.css
Comment: I really appreciate all your responses. The irony is that none of the template .tpl.php files have the server name src="http://testsite.cs.stonybeook.edu/sites/....
Comment: Could there be some settings, which I should look at?
Answer: Thank you all for all your responses. The issue was fixed by commenting on the base_url specified in the settings file.
Comment: Hello and welcome. Please post self-answers as neat explanations, something that will be easily usable by others with similar problem.


Create a View that Displays a group of Taxonomy Terms

Question: I have a proposed data structure like this:
Asset:

Title
Image
Description
Taxonomy term: Campaign

Campaign (taxonomy dictionary):

term
image
description

I am trying to make a view block that displays only the Campaign group, represented by the Campaign image.  The farthest I can get is defining a relationship to tax. terms on node, and displaying all Assets with that tag.  I can even Group them, which is really close to what I need.  How do I solve the problem of displaying "Campaigns" as groups of assets (not the list of assets tagged with this taxonomy).
I thought I could show a list of (non-duplicate) fields where that tax. image exists (which should be once per group/aka "Campaign"). But not so far..
How do I achieve this?   Have I overlooked something?  I am open to different approaches or ideas..
Answer: If you want to group Assets just by the Campaign (taxonomy) image, you can easily set the Grouping feature under Format to the Image field.
You have to add the Relationship for the taxonomy field first, as you have found out, then you get all the information related to the referenced taxonomy term into the Views. Without that Relationship you only have the Taxonomy term ID available, as the Taxonomy reference field only stores that info.
When you add the Relationship you can add the Taxonomy image field (Campaign image). Each Asset will then show its associated campaign image in its row.
That's when you can use Group by field and set it to the Campaign image. This will split the Asset results into Campaign groups with the image field as the "group header". You will still see the image displayed in each row, which you probably don't want, so you edit the Campaign field setting in Views and choose Exclude from display. This way the image will only display in the "group header" and won't display next to each Asset result.

If you need to display more info about the Taxonomy (Campaign) in the "group header", for example the name, image, and the description, you can add all those fields to your Views, Exclude them from display, and set them all to group by.
But sometimes the styling that comes out of this strategy isn't good enough, the HTML can be a bit unexpected. You can solve that by using Custom text field after all the Taxonomy fields where you enter your own HTML with the taxonomy field values printed out through tokens. And Group only by the Custom text field.

I've written an article about this if you need more detail: Grouping by multiple Fields in Drupal Views
Comment: Thanks, prkos.
I did actually go with a grouping solution


MYSQL Workbench Error while trying nested query

Question: I am using MySQL workbench 8.0 . I am trying to implement a nested query for the following query which is working. I am trying to avoid the create table command. However it is showing the error.( Select is not valid at this position for this server version, expecting '(', with )
The executable query is
create table recent as
select f.member_id,f.fill_date,f.insurancepaid,
p.member_first_name,p.member_last_name,d.drug_name,
row_number() over (partition by p.member_id order by f.fill_date desc) as flag
from fact_member_drug f
left join dimension_drug_name p
on f.member_id = p.member_id
left join dim_drugdetail_table d
on f.drug_ndc = d.drug_ndc;

select member_id,member_first_name,member_last_name,drug_name,fill_date,insurancepaid
from recent where flag = 1;

The query that I wrote is
select sub.member_id,sub.member_first_name,sub.member_last_name,sub.drug_name,sub.fill_date,sub.insurancepaid
from (
    select f.member_id,f.fill_date,f.insurancepaid,
    p.member_first_name,p.member_last_name,d.drug_name,
    row_number() over (partition by p.member_id order by f.fill_date desc) as flag
    from fact_member_drug f
    left join dimension_member p
    on f.member_id = p.member_id
    left join dimension_drug_name d
    on f.drug_ndc = d.drug_ndc;
) as sub
where sub.flag = 1;

Kindly help what am I doing wrong.
Thanks
Answer: you can try like below
   with cte as
   (
    select f.member_id,f.fill_date,f.insurancepaid,
    p.member_first_name,p.member_last_name,d.drug_name,
    row_number() over (partition by p.member_id order by f.fill_date desc) as flag
    from fact_member_drug f
    left join dimension_drug_name p
    on f.member_id = p.member_id
    left join dim_drugdetail_table d
    on f.drug_ndc = d.drug_ndc
 )  select * from cte where flag=1

from your query just remove semicolon
select sub.member_id,sub.member_first_name,sub.member_last_name,sub.drug_name,sub.fill_date,sub.insurancepaid
from (
    select f.member_id,f.fill_date,f.insurancepaid,
    p.member_first_name,p.member_last_name,d.drug_name,
    row_number() over (partition by p.member_id order by f.fill_date desc) as flag
    from fact_member_drug f
    left join dimension_member p
    on f.member_id = p.member_id
    left join dimension_drug_name d
    on f.drug_ndc = d.drug_ndc // just remove semicolon
) as sub
where sub.flag = 1