Intuitions for probability on countably infinite sample spaces

Question: I've learnt over the years that measure theory is subtle and counterintuitive, and many things that seem obvious actually have counterexamples. My intuition serves me well in the world of finite sample spaces, but if I step outside that I can't trust it.
However, I'm wondering if I can safely step into the world of infinite but countable sample spaces, such as the natural numbers.
I know that in this case there is no uniform distribution, which is a significant difference. Other than that, does anything substantial change when passing from probability distributions on finite sets to probability measures on countable sample spaces? I'm wondering in particular about basic intuitions like the following, which of course are wrong for general sample spaces but true in the finite case.

Unless you're doing something very weird the appropriate $\sigma$-algebra is always the power set.

Defining a probability measure is equivalent to assigning a probability to each outcome, such that they sum to 1.

If an outcome has probability 0, the appropriate intuitive interpretation is that it can't happen.

I ask partly because I know that the following definitely is wrong:

The expectation of a function $f\colon \mathbb{N}\to\mathbb{R}$ is always given by $\sum_{k\in\mathbb{N}}p(k)f(k)$.

In fact this is only true if the series is absolutely convergent, and the expectation is undefined otherwise. This makes me suspect that there might be important subtleties that I'm missing in my other bullet points as well, but it's surprisingly hard to find anything concise on this topic that doesn't gloss over this kind of point.
(Note: there are several related questions that are about finitely additive measures on countable sets. I'm not asking about that - I'm interested in the usual countably additive kind of measure here.)
Comment: There are no major subtleties.  Probability for finite or countably infinite sample spaces is largely the same.  You can indeed use the sigma algebra being the power set of the sample space, and the probability of any event is the sum of probability masses of outcomes in that event.
Comment: You can throw away all outcomes associated with a probability-zero event and it does not affect the probability measure. Of course, the same is true for uncountably infinite sample spaces.
Comment: @Michael thanks for the comments. Regarding the second one, I had written "event" but meant to write "outcome", the point being that "probability zero" is different from "impossible" in the continuous case, where one has to think about supports in order to formalise what "impossible" means.
Comment: You can have a sample space $\Omega = \{blue, red, green\}$ with $P[\{blue\}] = 1/2, P[\{red\}] = 1/2, P[\{green\}]=0$.  It is not really part of probability theory to decide if the green outcome is "impossible" if it is part of the sample space.
Comment: @Michael green is impossible in that case in that if you were to sample from that distribution and get green, then something must have gone wrong. On the other hand, if you sample from the uniform distribution on $[0,1]$ and get, say, 0.2, then that wasn't impossible but merely infinitely unlikely. (But if you got 1.2 then that really was impossible.) I'm not qualified to judge whether these facts are part of probability theory, but I believe it's possible to state them formally. (My intuition is that the notion of support is meant to capture this. I could be wrong I suppose.)
Comment: The terms "impossible" and "infinitely unlikely" are not defined in probability theory, but you can use them to talk intuitively and philosophically.
Comment: @Michael fine, that sounds good to me - that part of my question is about whether one can consider probability zero events to be impossible, intuitively/philosophically speaking, in the countable case.
Answer: Yes, if $\Omega$ is a finite or countably infinite sample space, we might as well use the sigma algebra of all subsets of $\Omega$. Then, specfiying a probability measure is equivalent to specifying probability masses for each outcome.

Probability masses:
Formally, suppose $\Omega$ is a nonempty set that is finite or countably infinite.  Suppose we have probability masses $p(\omega)$ for all $\omega \in \Omega$ such that
\begin{align}
&p(\omega) \geq 0  \quad \mbox{for all $\omega \in \Omega$} \\
&\sum_{\omega \in \Omega} p(\omega) = 1
\end{align}
Define $\mathcal{F}$ as the set of all subsets of $\Omega$. Define $P:\mathcal{F} \rightarrow\mathbb{R}$ by
$$ P[A] = \sum_{\omega \in A} p(\omega) \quad \forall A \subseteq \Omega$$
Then $(\Omega, \mathcal{F}, P)$ is a valid probability measure (it can be shown to satisfy the three axioms of probability).

Throwing away outcomes:
If $(\Omega, \mathcal{F}, P)$ is a triplet for a probability space (with $\Omega$ being either finite, countably infinite, or uncountably infinite) and if $A \in \mathcal{F}$ is such that $P[A]=0$, then we can throw away all outcomes in $A$ to produce a new probability space $(\tilde{\Omega}, \mathcal{\tilde{F}}, \tilde{P})$ where
\begin{align}
\tilde{\Omega} &= \{\omega \in \Omega : \omega \notin A\}\\
\tilde{\mathcal{F}} &= \{B \in \mathcal{F} : B\subseteq \tilde{\Omega}\} \\
\tilde{P}(B) &= P(B) \quad \forall B \in \tilde{\mathcal{F}}
\end{align}
The resulting space $(\tilde{\Omega}, \mathcal{\tilde{F}}, \tilde{P})$ is a valid probability space (it can be shown to satisfy the axioms of probability).  In particular, $\tilde{P}[\tilde{\Omega}]=1$ and none of the old probabilities change.
For example suppose $\Omega = \{blue, red, green\}$, $\mathcal{F}$ is the set of all subsets of $\Omega$,  and $P[\{blue\}] = 1/2, P[\{red\}] =1/2, P[\{green\}]=0$. We say that the outcome is surely in the set $\{blue, red, green\}$.  We also say that the outcome is
almost surely in the set $\{blue, red\}$.
We could throw away the green outcome since it has probability zero, without changing the other probability masses, to create a new probability space:
$\tilde{\Omega} = \{blue, red\}$, $\tilde{\mathcal{F}}$ is the set of all subsets of $\tilde{\Omega}$, $\tilde{P}[\{blue\}]=1/2$, $\tilde{P}[\{red\}]=1/2$. Here we can say the outcome is surely in the set $\{blue, red\}$ (so, unlike the previous case, green is not an outcome).
If the sample space is finite or countably infinite, you can always throw away all outcomes $\omega$ such that $P[\{\omega\}]=0$, without changing the probabilities of any of the remaining events.  So by reducing the sample space, you can assume all probability masses are positive.

On intuitive definitions of "possible":
Consider a probabilty space $\Omega = [0,1]$ with the standard Borel measure.  Define $X(\omega) = \omega$ so that
$$X \sim Uniform([0,1])$$
Define
\begin{align}
Y &= \left\{\begin{array}{cc}
0 & \mbox{ if $X \neq 0.2$} \\
8 & \mbox{ if $X = 0.2$}
\end{array}\right.\\
Z &= \left\{\begin{array}{cc}
X/2 & \mbox{ if $X \neq 0.2$} \\
8 & \mbox{ if $X = 0.2$}
\end{array}\right.
\end{align}
Then $Z \sim Uniform([0, 1/2])$, where $[0,1/2]$ is the support of the PDF of $Z$.

Is $X=0.2$ possible?
Is $Y=8$ possible?
Is $Z=8$ possible?

These three events are literally the same:
$$ \{X=0.2\} = \{Y=8\} = \{Z=8\} $$
So any intuitive definition of "possible" or "impossible" should be consistent for all three of these.
Note that $X(0.2) = 0.2$ and so there is an outcome in the sample space that leads to $X=0.2$. Of course, $P[X=0.2]=0$.
If you want, you can throw the outcome $\omega = 0.2$ away from the sample space to define a new sample space $\tilde{\Omega} = [0, 0.2) \cup (0.2, 1]$, without affecting the probabilities for the remaining events.  In that new space $(\tilde{\Omega}, \tilde{F}, \tilde{P})$ we can say that $X$ is surely not equal to $0.2$.
Comment: Just a minor note to emphasize part of this answer: while we can throw away any individual $\omega$ with $P(\{\omega\}) = 0$ in an uncountable sample space, we cannot throw away ALL $\omega$ with $P(\{\omega\}) = 0$.  It was stated (and is true) that we can do this for a finite or countable sample space, but I just wanted to emphasize that is no longer the case if $\Omega$ is uncountable.
Comment: +1, this is very helpful. I still think the discussion about impossibility is missing something. Consider this example: let $\Omega=[0,2]$, let $\mathcal{F}$ be its usual (Borel) $\sigma$-algebra, and let $P$ be generated by the pdf $$\rho(\omega)= \begin{cases}1&\text{if $\omega\le1$}\\0&\text{otherwise},\end{cases}$$ and let $X(\omega)=\omega$ as you did. Then consider the events $X=0.2$ and $X=1.2$. They both have probability 0 and can be thrown away without affecting the other probabilities, but on an intuitive level $X=0.2$ is a possible outcome of sampling from $X$, while $X=1.2$ is not.
Comment: I think the notion of [support of a measure](https://en.wikipedia.org/wiki/Support_(measure_theory)) is meant to capture this. Then we can say that 0.2 is "possible" (i.e. in the support of $P$) while 1.2 is not, because 0.2 has no open neighbourhood with zero measure while 1.2 does. This requires the sample space to be a topological space as well as a measurable space. After writing this, I guess the point is that for a countable space it makes sense to give it the discrete topology, and then the support is just the set of outcomes with positive probability mass, as in the finite case.
Comment: Your example seems similar to my example with variable $Z$. The support of $Z$ is $[0, 1/2]$.  So would you say "$Z=8$ is impossible" but "$X=0.2$" is possible," even though $\{Z=8\}=\{X=0.2\}$?
Comment: @Michael I see, I hadn't really understood the point of making 0.2 a special case. I would say it's intuitively "obvious" that $Z=8$ is possible while $Z=9$ is not, but I have no idea whether or how that can be formalised. (I think it's an interesting problem.)
Answer: To address your edit about expected values, I would say that is probably the only major difference between a finite sample space and a countable one: A finite random variable on a finite sample space always have a well-defined and finite expected value, while a finite random variable  on a countably infinite sample space may not have a well-defined expected value.
If we had $\Omega = \mathbb{N}$ for our sample space with probability measure $p$, the formula $\mathbb{E}[X] = \sum_{\omega \in \Omega} p(\omega)X(\omega)$ might still make intuitive sense for the expected value since there is a natural ordering for $\mathbb{N}$ that we could use to interpret the sum if it is not absolutely convergent, i.e. $$\sum_{\omega \in \Omega} p(\omega)X(\omega) = \sum_{\omega=1}^\infty p(\omega) X(\omega) = \lim_{N \rightarrow \infty} \sum_{\omega=1}^N p(\omega) X(\omega)$$ if that limit exists.  The problem is that, if the series is convergent but not absolutely convergent, then this definition is not stable under permutations: if we add the terms in a different order, we can get a different result.
This is more clearly a problem if the sample space is something a little more complex, like $\Omega = \mathbb{Q}$.  Let $p$ still be a probability measure on $\Omega$.  We define a random variable $X$ on $\Omega$ and want to compute $\mathbb{E}[X]$.  We still want $\mathbb{E}[X] = \sum_{\omega \in \Omega} p(\omega)X(\omega) = \sum_{\omega \in \mathbb{Q}} p(\omega)X(\omega),$ but now that sum is more difficult to interpret.  We can let $(q_n)_{n \in \mathbb{N}}$ be an enumeration of the rationals, so $$\mathbb{E}[X] = \sum_{\omega \in \mathbb{Q}} p(\omega)X(\omega) = \sum_{n=1}^\infty p(q_n)X(q_n) = \lim_{N \rightarrow \infty} \sum_{n=1}^N p(q_n)X(q_n)$$ if that limit exists.  The key thing is that we don't want this to depend on the enumeration of the rationals we chose.  This is why we require $\mathbb{E}[|X|] = \sum_{\omega \in \mathbb{Q}} p(\omega)|X(\omega)| < \infty$ in order to say $\mathbb{E}[X]$ is well-defined: absolute integrability implies that the expected value won't depend on our choice of enumeration $(q_n)$.  Note that if we know $X$ is non-negative (i.e. $X(\omega) \ge 0$ for all $\omega \in \Omega$) we can still define $\mathbb{E}[X]$; it just might be infinite.


Splitting a time-representing string and extracting value in seconds

Question: I am trying to write a function that would take time in a string like "mm:ss.sss" (e. g. 1:23.242) and return total seconds (in this case 83.242).
This is my attempt:
get_time <- function(str){
  minutes = strsplit(str,split=":")[0]
  seconds = strsplit(str,split=":")[1]
  return((60.0)*as.numeric(minutes)+as.numeric(seconds))
}

I figured there is some problem with strsplit function. I know it returns a list, but accessing the elements by [] doesn't seem to work, even though they say so in the tutorial.
What am I doing wrong?
Comment: Two things: (1) `strsplit` returns a list, so you could try using `unlist` as follows: `unlist(strsplit(str, split = ":"))` ... and (2) R is 1-indexed (not 0-indexed), so you will want `[1]` for minutes and `[2]` for seconds...putting both together you will have `minutes = unlist(strsplit(str,split=":"))[1]` and `seconds = unlist(strsplit(str,split=":"))[2]`...
Comment: Also, with regards to subsetting a list, would take a look at [this reference](https://adv-r.hadley.nz/subsetting.html). In your case, you could subset in a number of ways, without using `unlist`...such as `[[c(1,1)]]` for minutes and `[[c(1,2)]]` for seconds...
Comment: Thanks, it has solved the problem :)
Answer: There are functions in the lubridate package that will do a lot of this for you. Here is some sample code that uses the ms function which reads minutes and seconds.
library(lubridate)
timestring <- '1:23.242'
ms <- ms(timestring)
seconds <- as.numeric(as.duration(ms))
seconds
# [1] 83.242

Answer: Here is another way of doing it:
> as.numeric(unlist(str_split('1:23.56', ":"))) %*% c(60,1)
      [,1]
[1,] 83.56


Implementing Peterson's algorithm in chat

Question: I'm having a hard time understanding and implementing Peterson's algorithm for N processes (also known as Filter algorithm). I'm trying to make a chat in C using shared memory. I'm using the version of the algorithm that can be found in Wikipedia:
<code>// initialization
level[N] = { -1 };     // current level of processes 0...N-1
waiting[N-1] = { -1 }; // the waiting process of each level 0...N-2

// code for process #i
for(l = 0; l < N-1; ++l) {
    level[i] = l;
    waiting[l] = i;
    while(waiting[l] == i && (there exists k ≠ i, such that level[k] ≥ l)) {
        // busy wait
    }
}

// critical section

level[i] = -1; // exit section
</code>
I have a program called server.c and another called client.c, and I intend to use the algorithm so every client can access the shared memory at their own turn.
As I understand, my implementation of the algorithm should run inside every client. My question is: how do I know the amount of clients running (the value of N) if every client is a different instance of the program client.c? also, how do I know the value of i (i would be the number of the processes) if each new instance of client.c is unaware of how many instances have been run before?
Please let me know if my question is unclear, since English is not my native language.
Thanks a lot!
Comment: These structures are assumed to be in shared memory, so this will not work for separate program instances unless you flag the region the control variables are in as shared. Once you do that, though, you can have a counter that tells you how many concurrent users you have.
Comment: Thank you very much for your answer. Actually, I am using a part of the shared memory region for my control variables (I'm developing right now, so I don't know if it works yet). I'm worried though, because the control variables could be accessed concurrently by two or more different users at a given time - which is exactly the problem that the algorithm is trying to solve. So in order to use the algorithm to know how to access the shared memory region, I need to know the value of n in the shared memory region and viceversa... :S
Answer: <code>> How do I know the amount of clients running (the value of N)
> if every client is a different instance of the program client.c?
</code>
Peterson's solution requires that all participating processes, or threads, have access to a shared-memory resource.  That shared memory segment will contain level[] and waiting[] arrays, as well as the value of N.
<code>> also, how do I know the value of i (i would be the number of the process)
> if each new instance of client.c is unaware of how many instances have
> been run before?
</code>
In more primitive situations where there is a set number of participating processes, or threads, each is assigned it's 'i' value.  The only requirement is that they are unique, and that i >= 0, and i < N.  (Perhaps your implementation could assign 'i' from a command-line parameter?)
In more advanced implementations, each process might acquire (and then increment) 'i' in the shared memory segment.  Of course, such an implementation would have to assure that each participant is started in a way that there is no contention for i.
Comment: Thanks! What I'm trying right now is to implement the "primitive" situation, assigning values to the processes. Thanks to your answer, I now know that I'm heading to the right direction. :)


Frontpage slideshow not showing

Question: Here are the steps that I have taken:

Created a content type of "slide" with the following fields
Title
Body
Link
Image
Created 3 slides with "slide" content type.
Created a new view named "slideshow" using Views Slideshow (slideshow). The preview correctly displayed the slideshow.
Added the block "slideshow" in the theme's block "Featured"
Configured the block to show only slide content.
Saved the block.
Cleared the registry by typing "drush cr". Cleared.
Clicked Firefox refresh button.
Clicked the "Home". Only the "Welcome Text .." displayed. No slideshow.
Rechecked Views Slideshow to ensure that it is correctly displayed.
Update mariadb.
Refreshed. Still no slideshow.

Have I missed something?
Any help is greatly appreciated.
Thanks a lot.
M A Sani
Answer: Please clarify what you mean by "Configured the block to show only slide content."?
This seems off to me as you would instead configure the VIEW to only show slide content. When it comes down to block configuration, those settings are for visibility aka what urls and/or types of pages that block region will show that block.
If you wanted the block to be on the homepage only, you would add <front> in the Pages tab of the block visibility settings.
If you did indeed "configure the block to only show on slide content", then you told Drupal to show the block when you are actually viewing a slide node page aka "node/xx" where xx is a node id of a slide.

Frontpage slideshow not showing


How do i turn off django's plural notation in the admin page

Question: I have some tables that are presented as inlines of another class. I have altered the default title of these inline representations by adding an inner class to the respective tables.
class Meta:
        verbose_name = 'Binnengekomen punten'
I have only the verbose_name defined but it still adds an s to all the names. So 'Binnengekomen punten' is displayed as 'Binnengekomen puntens'
What i could do is define the plural of verbose_name verbose_name_plural the same as verbose_name. But is there a way to simply turn off the plural notation? I'd love to know thank you.
Answer: according to Django docs there isn't method to turn off plural notation.
If verbose_name_plural isn't given Django uses verbose_name + 's'
Comment: this is a nice simple solution to the original question, I think this should be the accepted answer
Answer: Adding a suffix is hardcoded, we can see this in the source code:
            if self.verbose_name_plural is None:
                self.verbose_name_plural = format_lazy('{}s', self.verbose_name)
It does not make much sense to write the verbose_name as 'binnengekomen punten' (incoming points), since that is plural and a verbose_name is supposed to be singular. You can however make a decorator that for example automatically defines the plural by adding 'en' to the verbose_name, like:
def add_plural(cls, suffix='en'):
    if not hasattr(cls, 'verbose_name_plural'):
        try:
            cls.verbose_name_plural = cls.verbose_name + suffix
        except AttributeError:
            pass
    return cls
We can then use the decorator like:
class IncomingPoint(models.Model):
    # ...
    @add_plural
    class Meta:
        verbose_name = 'Binnengekomen punt'
EDIT: You can turn of capitalization, by wrapping the items in a subclass of string, as is shown is in this ticket #18129:
class NoCap(str):
    def upper(self):
        return self
    def __getitem__(self, key):
        return self.__class__(super().__getitem__(key))
We can then wrap the verbose_name and verbose_name_plural into this:
def case_invariant_meta(cls, suffix='en'):
    try:
        cls.verbose_name = NoCap(cls.verbose_name)
    except AttributeError:
        pass
    try:
        cls.verbose_name_plural = NoCap(cls.verbose_name_plural)
    except AttributeError:
        pass
    return cls
We can then annotate the Meta class:
class IncomingPoint(models.Model):
    # ...
    @case_invariant_meta
    @add_plural
    class Meta:
        verbose_name = 'Binnengekomen punt'
Comment: I also noticed django capitalizes all table names on the admin page. Any chance this behaviour can be switched off?
Answer: I'm sure that it's possible, but can guarantee you that it would not be worth the effort. Just set the verbose_plural_name.
Comment: so there is no easy way to turn it off then?
Comment: You'd literally have to edit the source code for the `admin` app. So no.


where condicao incrementando

Question: Eu tenho uma table chamada usuários e quero pega alguns usuários conforme o id então estou fazendo assim:
select * from usuarios where id=2;

Só que eu gostaria de pegar vários usuários com ids diferentes, por exemplo pegar os usuários que tiver o id 2,8,10,11,20 de uma vez. Como eu poderia fazer isso em SQL? Se eu colocar o > where id=2 and id=3, não daria certo porque ele faz uma comparação. Então alguém saberia me dizer como fazer?
Comment: `select * from usuarios where id=2 OR id=3 OR id=4...`
Comment: da pra utilizar com `in` ex: `select * from usuarios where id in (2, 8, 10)` ou caso preferir, pode utilizar o comando `or` porém, deve envolver todas as condições entre parenteses. ex: `select * from usuarios where (id=2 or id=3 or id=4)`. pois desta maneira ainda podem ser colocadas mais condicoes "fora" dos parenteses. Ex: `select * from usuarios where (id=2 or id=3) and usuarios.nome is not null`.
Answer: Use o comando in, ele vai verificar se há ocorrências nos campos, e retornar o registro onde houve ocorrências, a finalidade dele é substituir varias clausulas, onde é usado o comando or.
Exemplo:
select * from usuarios where id in(2,8,10,11,20);

Veja mais a respeito dele: http://www.tutorialspoint.com/mysql/mysql-in-clause.htm
Comment: @JohnDiego Usa da mesma forma, veja a [documentação](https://msdn.microsoft.com/en-us/library/ms177682.aspx).
Comment: Massa Dener !! Sabe se existe semelhante ao in no sql server ?
Comment: Massa demais !! Brigadão

where condicao incrementando


Add headers to each grouped section in a view

Question: I've got some content (Employees) and I've got a View that is showing the content in a grid grouped by Department (i.e. it shows the title "Customer Support" and then a grid of Employees and then the title "Sales" and a grid of Employees, etc.)
I would like to include a paragraph of text before each section, preferably from a content node so that my users can modify the description before each section.
I've seen something online (although I'm having trouble finding it again) about being able to attach a view above another view. Is it possible to somehow display a DepartmentDescription node before each section of my grouped view?
Answer: You certainly can, if you use a Views relationship to load in those other Department nodes, add a field using that relationship showing the Department node body, set it to "exclude from display" (so it doesn't appear twice) and in Format: Settings set Grouping to use that specific field.
The key question then is - how does each Employee node know which is the Department node that corresponds to it? I'd suggest you use one of the node relationship/reference modules to link them together - I can vouch for relation which is good, powerful and (since a few months ago) works well with views. It isn't so easy to use and doesn't have a great interface yet, but learning to use it is time well spent, especially for the sort of site you seem to describe. If you think Relation is overkill (it is for many very simple sites), here's a guide which covers the many simpler alternatives.
With Relation, a step-by-step could be:

Create the relation type (say, "is in department" source>target, "has employee" target>source, valid source: employee, valid target: department)
Create a relation for each employee, linking it to its department
In the view, create a node-node Relation relationship using "is in department" from the 'source' endpoint
Add a content:body field, using this relationship. Set it to exclude from view
In View Format: Settings, choose this body field  to group the view


How to read a file from a specific line to another specific line?

Question: So I'm trying to make a file reader to read from x line to y line but when i execute the program it reads all the lines of the file and not the lines that should have started and ended, For example if i'm looking an ID in the file it should print de ID, The name of the holder(the next line of the ID Line), and his/her address(Next line of the name Line), but instead of print just that it prints all the ID'S, Names and Addresses of everyone in the file.
System.out.println("Escriba el ID Del Cliente");
         CL.setID(reader.next());
         String line2;
         int count = 0;
         try {
             BufferedReader input = new BufferedReader(new FileReader(file));
             Scanner input2 = new Scanner(file);
             PrintWriter output = new PrintWriter(new FileOutputStream(file, true));
             LineNumberReader readers = new LineNumberReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));

             while((line2 = input.readLine()) != null)
             {

                 if(line2.contains(CL.getID()))
                 {
                     while(((line2 = readers.readLine()) != null) && readers.getLineNumber() <= count + 3)
                     {
                         count++;
                         System.out.println(line2);

                     }

                     input.close();
                     input2.close();
                     output.close();
                     readers.close();
                     break;
                }

             }

         }catch(IOException ex)
         {
             System.out.println("ERRORR!!!!!!");
         }

Comment: It's because you're incrementing the `count` variable in every iteration. Just remove `count++` and it should work.
Comment: Hi, that fixed the bug of showing all the lines of the file, but now it just shows the first line of  the file and does not show the x line to y line i want the console to print
Answer: I've modified your code because the problem was at the count++ which will eventually led to reading all the lines from your files, and at the line2 = readers.readLine() which will read from the first line of the file again ( the program works half correct because it reads only 3 lines and only if line2 contains your ID ). Now, to make your program work correctly, you need to either use the BufferedReader or the LineNumberReader.
public static void main(String[] args) {
    System.out.println("Escriba el ID Del Cliente");
    String line2;
    File file = new File(yourpathhere);
    int lineCount = 0;
    try {
        PrintWriter output = new PrintWriter(new FileOutputStream(file, true));
        LineNumberReader readers = new LineNumberReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
        while ((line2 = readers.readLine()) != null) {
            lineCount++;
            if (line2.contains(CL.getId())) {
                while (line2 != null && readers.getLineNumber() <= lineCount + 3) {
                    System.out.println(line2);
                    line2 = readers.readLine();
                }
                output.close();
                readers.close();
                break;
            }
        }

    } catch (IOException ex) {
        System.out.println("ERRORR!!!!!!");
    }
    }

PS : pay attention for the getLineNumber() method because it increments the lines read until the moment you're calling it. It means that if we didn't had the lineCount and the ID we're trying to find was at the 6th line, the getLineNumber() value at the moment when line2.contains(CL.getId()) == true was 6, so the readers.getLineNumber() <= 3 will be FALSE and the program won't work correctly anymore. ( We need to keep track for the lines read until the moment we check for the id )
Answer: Assuming you have a file with 100 lines and you want to check and print out line 5 to 10 you could try this:
System.out.println("Escriba el ID Del Cliente");
CL.setID(reader.next());
String line;
int count = 0;
int xLine = 5;
int yLine = 10;
try (BufferedReader input = new BufferedReader(new FileReader(file)))
{
    while((line = input.readLine()) != null)
    {
        if(count < xLine)
        {
            // skip all lines lower then start
            continue;
        }
        else if(count >= xLine && count <= yLine && line.contains(CL.getID()))
        {
            // print line if line is between lines to read
            // and if line contains ID
            System.out.println(line);
        }
        else
        {
            // break if count is bigger then yLine
            break;
        }
        count++;
    }
}
catch(IOException ex)
{
    System.out.println("ERRORR!!!!!!");
}

You read all lines till the BufferedReader reaches null. You check if the line contains your ID. Then you check if the count is between the linenumbers you want to check / print. Then you increment the count for the lines processed.
I simplified the try-catch-Block with a try-with-ressources Statement. As for now I don't see what your plans with output and scanner were, so I removed them.


How To Setup Local Tunnel Through Windows Remote Desktop

Question: My local machine is using MacOSX/linux and am able to connect to a Windows Remote Desktop machine (using Windows Remote Desktop/Remote Desktop Connection).
The Windows Remote Desktop machine is able to connect to certain servers that I cannot connect to locally on my MAC.  For example, connection to database servers, specific web servers, etc.
How can I setup some kind of tunnel so that I can access the servers locally on my mac?
Answer: You can configure port forwarding on the Windows machine
<code>netsh interface portproxy add v4tov4 listenport=3390 listenaddress=192.168.1.111 connectport=3389 connectaddress=192.168.0.33
</code>
where 192.168.1.111 is IP of your Windows machine and 192.168.0.33 is destination server. From your Mac you will connect to Windows machine specifying port in RDP connection 192.168.1.111:3390 and you will be connected to the remote server. You have to provide credentials from the server, not your local Win machine. This configuration survive restarting Windows machine.
Comment: Thanks for the tip.  Is there any alternative if I'm not the administrator of the Windows machine?  Looks like it won't let me run the netsh command.
Comment: Don't you have Run as Administrator in context menu for cmd? Another option is to fake that your mac is the windows machine, by switching IP addressess, cloning MAC address - depends on how the access to remote servers is made.
Answer: Just install Igiko on your windows machine and then open it in web browser on your MacOSX. Igiko is acting like web-based RDP gateway, using it you will be able to open RDP console to any Windows machine in your network.


Redirect após update laravel

Question: Estou trabalhando num projeto com laravel e me deparei com um problema. Após o Update eu quero redirecionar o usuário para uma outra página específica. Na função de update do meu Controller eu tenho esse código:
public function update(Request $request, $id){

    try {
        $exame = $request->all();

        $id_exame = Tab_exames::findOrFail($id);
        $id_exame->update($exame);

        return redirect()->route('agenda_exames')->with('success','Os dados foram atualizados com sucesso.');

    } catch (Exception $ex) {

        return redirect('agenda_exames')->with('error', 'Ocorreu um erro ao tentar atualizar os dados!');
    }
}

Só que me retorna esse erro:

Se eu usar esse redirecionamento não ocorre erro:
return back()->with(['success' => 'Os dados foram atualizados com sucesso.']);

Minhas rotas estão assim:
Redirect
Route::get('/agenda_exames', 'AgendaExamesController@index')->name('agenda_exames');

Pega os dados para a edição
Route::get('/edita_exames/{id}', 'AgendaExamesController@edit')->name('edita_exames');

Atualiza os dados
Route::put('/edita_exame/{id}', 'AgendaExamesController@update')->name('edita_exame');

Como posso redirecionar o usuário para outra página após o update utilizando os métodos apresentados?
Answer: Informa a url pelo redirect:
return redirect('/agenda_exames)->with('success','Os dados foram atualizados com sucesso.');

Comment: Obrigado pelo feedback! Eu editei a pergunta, eu já possuo essa rota.
Comment: Alterei minha resposta. Qual versão do Laravel tas usando?
Comment: Estou utilizando Laravel 5.5. Testei com seu exemplo mas continua dando erro de rota.
Comment: Editei a resposta. Da uma olhada pra ver se vai redirecionar informando a url direto no redirect.
Comment: Deu certo! Muito obrigado.

Redirect após update laravel


directive does not work in the ons-toolbar

Question: I use Angularjs and OnsenUI and define a directive like this:
 module.directive('selectDIY',function(){
return{
    restrict: 'AE',
    template: "<select class=\"portNameList\" id=\"portfoliosId\"  ng-change=\"selectedPortfolioChanged( $index)\">"
                +"<option ng-repeat=\"portfolio in portfoliosPriceList track by $index\" value=\"{{portfolio.id}}\" >"
                +"{{portfolio.portname}}</option> </select>"
}

})
In the html like this:
 <ons-page ng-controller="portfoliosController">
    <ons-toolbar class="DCF"  fixed-style>

           <selectDIY></selectDIY>

    </ons-toolbar>

Anybody knows how to this?
Answer: If you name your directive selectDIY, you must refer to it by <select-d-i-y>, for example, in the DOM.
Or, if you want to refer to it by <selectDIY> in the DOM, you must define it as following. module.directive('selectdiy',function(){});
From the documentation:

Angular normalizes an element's tag and attribute name to determine
  which elements match which directives. We typically refer to
  directives by their case-sensitive camelCase normalized name (e.g.
  ngModel). However, since HTML is case-insensitive, we refer to
  directives in the DOM by lower-case forms, typically using
  dash-delimited attributes on DOM elements (e.g. ng-model).
The normalization process is as follows:

Strip x- and data- from the front of the element/attributes.
Convert the :, -, or _-delimited name to camelCase.
Comment: I believe in this case it would be best to do `module.directive('selectDiy', function() {});` in order to be able to write `` in the templates.


Windows Server 08 R2 file share File locking, OSX clients

Question: I've spent the last two weeks banging my head against this wall. I think I'm starting to understand the problem though. I manage a design company and they have 5 macs (OSX 10.5/.6/.7) connected over SMB to a Windows 2008 R2 file server, another machine functions as Domain Controller (that might not matter).
All the macs can connect ok, no issues finding the server or logging in. For the most part things are ok. The problem is files locking up. I thought it was a permissions issue at first but it seems to be file locking. The users open a file; .ind, .pdf etc the file opens, the software reads it and closes it. That's fine, but the folder above the folder locks, it can't be moved and it can't be renamed.
Eg:

/Working/Project01/Imagefiles/image.pdf
/Finished/

The user opens image.pdf, closes it and wants to move the whole Project01 folder into Finished. It gives a username/pass dialogue and then does nothing, no error, or just does nothing. Trying to rename gives a dialogue that says you don't have permission. It looks like it's looking for permission locally, which is why I spent about a week looking at that.
Eventually I found that Finder on the macs seems to be keeping the folders open. I can work around it by Killing finder, remounting the shared drive or closing the file through the server manager but this just proves the theory it's not a solution.
Has anyone dealt with this problem?
Comment: please pay more attention to your formatting. as originally written, your post was a single wall of text and completely unreadable. i've edited it to improve the readability.
Comment: We've just started getting this exact problem too. Looking into it now so I'll post back if I find a solution. At the moment the work around is copy the pdf onto the Desktop then open it from there, then we can move the folder.
Comment: I'm not sure if this is the issue or two separate issues but I found on Mountain Lion that MDWorker seems to be locking .DS_Store files within new or worked on directories. The users tend to copy in a template tree of directories when they start a new project, you can see MDWorker working away in the folders as soon as you drop them in and while it's working on one you can't move it or the ones above it.
Comment: For those finding this. I spent three months searching, configing, updating and never found a fix. Eventually we gave up on Windows Server's native support and bought ExtreamZ IP, it wasn't cheap.
Answer: Use Icon view instead of list view until Apple fix the bug.
Comment: What bug is this? This answer is exceedingly low on detail.


Como fazer uma consulta que retorne dados dos últimos 7 dias sem considerar domingo

Question: Preciso de alguma condição no SQL SERVER que retorne o resultado da lista de elementos levando em consideração os últimos 7 dias de criação do mesmos. Porém ele não pode considerar o Domingo como um dia válido na consulta.
Consulta:
Select SearchId, getdate() as CreateDate from Security.Search

Answer: Você não deu muitos detalhes, eu acho que o que você precisa é algo assim:
SELECT SearchId, getdate() as CreateDate FROM Security.Search
        WHERE DATEDIFF(DAY, CreateDate, GETDATE()) < 8 AND DATEPART(DW, CreateDate) != 7

Coloquei no GitHub para referência futura.
Isto pegará os últimos 7 dias mas desconsiderará o Domingo. Se quiser pegar 7 dias no total já desconsiderando o Domingo na conta, então mude a condição < 8 para <= 8.
A primeira parte da condição pega o número de dias que você quer (DATEDIFF e GETDATE) e a segunda parte filtra o Domingo, que é considerado o dia 7 da semana obtido pela função DATEPART.


Show the sum of probabilities is less than or equal to twice the probability of the union

Question: I can't solve this problem out of my class's textbook although it seemingly is very simple. Could someone solve this or point me in the correct direction please?
$Let(Ω,F,P)$ be a probability space and let $E_1,...,E_n ∈ F$ be mutually independent events. If $P(⋃^{n}_{i=1}E_i)≤1/2$, then
$$∑^{n}_{i=1}P(E_i)≤2P(⋃^{n}_{i=1}E_i)$$
This would be trivial if they were disjoint events, but unsure how to show this if they're only independent, although I can tell this is likely easy and I'm missing something terribly obvious.
My first thought was to use inclusion/exclusion but i cant get that to work.
Answer: This is easily proved by induction on $n$. For $n=2$ we have $P(E_1)+P(E_2)\leq P(E_1 \cup E_2)+P(E_1 \cup E_2)=2P(E_1 \cup E_2)$.
Suppose that result is true for $n$ independent events and consider $n+1$ independent events: $E_1,E_2,...,E_{n+1}$. We have $$ \sum\limits_{i=1}^{n+1} P(E_i)= \sum\limits_{i=1}^{n} P(E_i)+P(E_{n+1})$$ $$\leq P(\bigcup_{i \leq n} E_i)+P(E_{n+1})\leq 2P(\bigcup_{i \leq {n}} E_i)+P( E_{n+1}) \leq 2P(\bigcup_{i \leq {n+1}} E_i)$$ The last step follows from the folowing :
If $A$ and $B$ are independent and $P(A\cup B) \leq \frac 1  2$ then  $2P(A)+P(B) \leq 2P(A\cup B)$.  [Use the fact that $P(A\cup  B)=P(A)+P(B)-P(A)P(B)$].
Comment: This is clearly it. I was driving myself insane trying to factor in independence somehow.
Comment: @bof Thanks for the comment. The original proof was wrong, but induction does work. I have edited the answer.
Comment: @Ralph Actutally inclusion exclusion for two indepdent events is required. There was  a mistake in my answer and I haev corrected it.
Comment: Oh I see now, I decided to sleep on it before I came back to the problem, I didn't see your error at first but its clear looking at the edits. Thank you!


PHP if statement doesn't work properly (paradoxical)

Question: I've got a strange problem. I want to write a simple multiple image upload script in PHP.
So there is an if statement I need for checking if the image has got the correct image type, which doesn't work as expected. The image I try to upload is a .jpg image. The "jpg" information is stored in the variable $mediaFileType, which is being checked by the if statement. Normally it should execute the script in the else statement now, but it always does the opposite and states that "jpg" != "jpg" = true. And it's obviously not. So what am I missing here?
if($mediaFileType != 'jpg' && $mediaFileType != 'png' && $mediaFileType != 'jpeg')
 {

    echo 'Wrong Media Type
';
    echo $mediaFileType;
    exit();

} else {
    ....
}

The website simply says:
Wrong Media Type
jpg

Comment: Try `!in_array()`, it can sometimes make things a little easier than multiple ifs. `!in_array($mediaFileType, ['jpg', 'png', 'jpeg'])`. If that doesn't work, try trimming `$mediaFileType`, or `var_dump($mediaFileType)` to make sure there aren't any extra characters.
Comment: file extensions can't be the same for one file, you need to check using the "OR" operator. You might even want to post the html for this and the rest of the php
Comment: You want to read about operator precedence... http://php.net/manual/en/language.operators.php
Comment: Can you var_dump() mediaFileType instead of echoing it, please? The string is likely something with invisible white space characters.
Comment: try trimming $mediaFileType, `trim($mediaFileType)`
Comment: @Fred -ii- I guess its time for weekend! (With "OR" it would be the problem you describe)
Comment: @RolandStarke Partly. However, the OP failed to respond to [my comment](https://stackoverflow.com/questions/46849421/php-if-statement-doesnt-work-properly-paradoxical#comment80646162_46849421) so he can take it up with answers given. I'll have to just see what the outcome is and make me a bowl of popcorn ;-)
Answer: You can use:
if (!in_array(trim($mediaFileType), ['jpg', 'png', 'jpeg'])) {
    echo 'Wrong Media Type
';
    echo $mediaFileType;
    exit();
}

Answer: Your problem is probably a whitespace character
if (!in_array(trim($mediaFileType), ['jpg', 'png', 'jpeg']))
{
    echo 'Wrong Media Type
';
    var_dump($mediaFileType);
    exit();
}
...

Comment: All of you were right by saying it was a whitespace character. Thanks! :)


Preencher uma ListBox com dados vindos de checkBoxes

Question: Estou com problemas a preencher a minha Listbox, consigo preencher a Listbox com os valores da checkboxes das não com as Labels correspondentes.
Estou com falta de ideias como vou fazer isto.
A lista de checkBoxes é preenchida com jquery, da seguinda maneira:
 itensNomesCatequizandos.append(catequizando.Nome + '
');
 itensCheckBoxCatequizandos.append('<input type="checkbox" name="SelectedCatequizandos[]" value="' + catequizando.PessoaID + '">' + '
');

A minha ListBox preenche todos nomes numa só minha:

Onde recebo o texto para preencher a ListBox:

Answer: Fiz uma POC bem simples, espero que ajude:
HTML:
<input type="checkbox" value="1" /> Um
<input type="checkbox" value="2" /> Dois
<input type="checkbox" value="3" /> Tres

JQUERY:
$(function() {
    $('input[type=checkbox]').click(function(){
    var $lista = $('#lista');
    var value = $(this).val();
    var $item = $('
').attr('data-id', value).html(value);
        if(this.checked) {
        $item.appendTo($lista);
    } else {
      $lista.find('li[data-id='+ value +']').remove();
    }
    });
})

Teste no JsFiddle.
Comment: Não foi a minha solução mas também funciona.


How to show two points in $\mathbb{R}^3$ form a plane and determine equation?

Question: Given two arbitrary equidistant points in $\mathbb{R}^3$, ($p$ and $q$), how would one show that they form a plane and what would the equation of that plane be?
Defining two vectors in $\mathbb{R}^3$: $(p - 0)$ and $(q - 0)$, the span of these two vectors show form a plane, if I'm not mistaken.  But now, how can I come up with an equation for this plane?
Comment: "how would one show that they form a plane and what would the equation of that plane be?" It's not clear what you mean by two points *forming* a plane, but I can imagine some possibilities. (1.) The two *vectors* $OP$ and $OQ$ form a plane, where $P$ and $Q$ are the points with position vectors $p$ and $q$, and $O$ is the origin (assuming neither $P$ nor $Q$ is the same as $O$). This is the plane containing the three points $O$, $P$ and $Q$. (2.) The set of points $A$ equidistant from both $P$ and $Q$ is a plane perpendicular to the line $PQ$ and bisects the line segment $PQ$.
Comment: Sorry... how could two points *not* be equidistant (from each other)?!?!?
Comment: Equidistant to what? You know you always need three conditions to uniquely determine a plane...
Comment: Okay, you're talking about *three* points: $p$ and $q$ plus the origin (in which case $\|p\|=\|q\|$ isn't really relevant). Do you know what a cross product is?
Answer: The cross product of the two vectors $\vec{OP}$ and $\vec{OQ}$ is a vector perpendicular to your plane. Say it has coordinates $\vec{OP}\times \vec{OQ}=(a,b,c)$. Then the equation of the plane you are interested is $ax+by+cz=0$. This is because this represents the equation $(a,b,c)\cdot (x,y,z)=0$ which describes the set of all points whose position vector is perpendicular to $(a,b,c)$.
Answer: In general, a plane has an equation of the form $$ax+by+cz+d=0,$$ and you are trying to find the values of the coefficients, $a$, $b$, $c$, and $d$. You want the plane to go through the origin, $(0,0,0)$; plugging that point in, we get $d=0$, so now we have $$ax+by+cz=0.$$ Now you want your plane to go through ${\bf p}=(p_1,p_2,p_3)$ and ${\bf q}=(q_1,q_2,q_3)$, so that gives you two equations, $$ap_1+bp_2+cp_3=0,\qquad aq_1+bq_2+cq_3=0$$ to solve for the three unknowns $a$, $b$, $c$. Can you find a solution to a pair of linear equations in three unknowns?
Answer: It takes three non-colinear points to determine a plane.  It sounds like your plane is determined by the origin as well as $p$ and $q$.  What happens if $p=-q$?
A plane through the origin is determined by a normal vector.  How about $p \times q$?


Estimação Máxima verossimilhança usando nlm

Question: Estou interessado em estimar dois parâmetros de máxima verossimilhança usando a função nlm.
**-------- FUNÇÃO RBETAMIFI -------**

rbetamifi <- function(n,mi,fi){
p <- mi*fi
q <- (1-mi)*fi
return(rbeta(n,p,q))
}

**----------------------------------**

aqui estão meus dados:
amostra10 <- matrix(NA,3,10)
amostra10[1,] <- rbetamifi(10,0.4,13)
amostra10[2,] <- rbetamifi(10,0.4,13)
amostra10[3,] <- rbetamifi(10,0.4,13)

Estimando mi e phi de cada amostra pelo métodos dos momentos (que será usado para o chute inicial):
mi1 <- mean(amostra10[1,])
mi2 <- mean(amostra10[2,])
mi3 <- mean(amostra10[3,])

fi1 <- (mi1*(1-mi1)/var(amostra10[1,]))-1
fi2 <- (mi2*(1-mi2)/var(amostra10[2,]))-1
fi3 <- (mi3*(1-mi3)/var(amostra10[3,]))-1

Função de Verossimilhança:
menoslogV1 <- function(par){
          logV <- length(amostra10[1,])*log(gamma(par[2])/(gamma(par[1]*par[2])*gamma((1-par[1])*par[2])))+
            ((par[1]*par[2])-1)*sum(log(amostra10[1,]))+(((1-par[1])*par[2])-1)*sum(log(1-amostra10[1,]))
          return(-logV)
        }

menoslogV2 <- function(par){
          logV <- length(amostra10[2,])*log(gamma(par[2])/(gamma(par[1]*par[2])*gamma((1-par[1])*par[2])))+
            ((par[1]*par[2])-1)*sum(log(amostra10[2,]))+(((1-par[1])*par[2])-1)*sum(log(1-amostra10[2,]))
          return(-logV)
        }

menoslogV3 <- function(par){
          logV <- length(amostra10[3,])*log(gamma(par[2])/(gamma(par[1]*par[2])*gamma((1-par[1])*par[2])))+
            ((par[1]*par[2])-1)*sum(log(amostra10[3,]))+(((1-par[1])*par[2])-1)*sum(log(1-amostra10[3,]))
          return(-logV)
        }

Estimando:

es1 <- nlm(menoslogV1, par <- c(mi1,fi1), hessian=TRUE)
es2 <- nlm(menoslogV2, par <- c(mi2,fi2), hessian=TRUE)
es3 <- nlm(menoslogV3, par <- c(mi3,fi3), hessian=TRUE)

O problema é que quando vou estimar usando o NLM algumas vezes acontece esse erro:

Warning messages:
  1: In log(gamma(par[2])/(gamma(par[1] * par[2]) * gamma((1 - par[1]) *  :
    NaNs produced
  2: In nlm(menoslogV2, par <- c(mi3, fi3), hessian = TRUE) :
    NA/Inf substituido pelo máximo valor positivo

Ele estima, mas estou com medo de que esses warnings estejam influenciando, como resolver?
Comment: nlm não permite NA (Not Avaiable) e NaN (Not a Number), não sei se seus dados tem estes valores ou são gerados nas formulas e funções, princialmente pq tem log no meio. Mas vi que vc colocou amostra10 <- matrix(NA,3,10), tenta assim amostra10 <- matrix(numeric(0),3,10)
Comment: Não tinha Na, esse código com os NAS era so pra criar a matriz, logo embaixo eu preenchi ela com as amostras.
Comment: @GabrielIanhezPereira você pode colocar seu comentário como uma resposta
Comment: @CarlosCinelli feito, obg!
Answer: Meus professores descobriram o erro, era um erro numérico quando ele calculava o log(gamma), foi resolvido substituindo por uma função só que é a lgamma (que calcula direto o log da gamma):
menoslogV1 <- function(par){
  logV <- length(amostra10[1,])*(lgamma(par[2]) -
    lgamma(par[1]*par[2]) - lgamma((1-par[1])*par[2]))+
    ((par[1]*par[2])-1)*sum(log(amostra10[1,])) +
    (((1 - par[1])*par[2])-1)*sum(log(1-amostra10[1,]))
 return(-logV)
}


three.js ES6 how import only specific modules

Question: I've installed three.js library through NPM to get advantage of the new ES6 modular architecture which should let you to import just the modules you need, as explained here: Threejs - Import via modules.
I am using gulp, browserify and babel for bundling and transpiling, like so:
gulp.task("build_js", () => {

return browserify({
    entries: "./public/app/app.js",
    cache: {},
    dev: true
})
    .transform(babelify, {presets: ["env"], plugins: ["syntax-async-functions", "transform-async-to-generator"], sourceMaps: true})
    .bundle()
    .pipe(source("app.bundle.min.js"))
    .pipe(buffer())
    .pipe(sourcemaps.init({loadMaps: mode}))
    .pipe(uglify())
    .pipe(sourcemaps.write("./"))
    .pipe(gulp.dest(config.build.js))

});

I want to import only the modules I need and keep the bundle size small, but I noticed that the bundle generated by browserify has the same size regardless if I import all the modules or just one.
If in app.js I import all the modules I got a bundle size of about 500Kb:
// app.js

import * as THREE from 'three'; // about 500 Kb size

But if I try to import just a specific module using ES6 syntax I got the same bundle size (it is importing again all the modules):
// app.js

import { Vector3 } from 'three'; // about 500 Kb size, same as before example

I've also tried the following:
// app.js

import { Vector3 } from "three/build/three.module.js";

But I got the following error:
SyntaxError: 'import' and 'export' may only appear at the top level (45590:0) while parsing /Users/revy/proj001/node_modules/three/build/three.module.js

My question: how can I properly import only the modules I need and keep the bundle size small?
Comment: What happens if you try `import {Vector3} from 'three/src/math/Vector3`
Answer: You are missing the concept of Tree Shaking.
When you import a modules by name the other modules are not automatically removed from the bundle. The bundler always includes every module in the code and ignores what you have specified as import names.
The other unused modules, which you did not import, are considered dead code because they are in the bundle however they are not called by your code.
So to remove this unused code from the bundle and thus make the bundle smaller you need a minifier that supports dead code removal.
Check out this popular tree shaking plugin for browserify - it should get you started:
https://github.com/browserify/common-shakeify
Comment: I don't understand. When I import a module, I expect that only the code relevant to that module will be imported (and the modules required from that module in a transitive dependency path). This is not dead code, it is the code that I need in my application. The modules that are not in transitive dependency path should not be imported, or am I missing something?
Comment: The bundler always includes everything except if you use a tree shaking tool. Your assumption that only the code which you explicitly import is included is wrong.
Comment: i'm not an expert on this topic, but this does seem wrong. If you `import {Vector3} from './path/Vector3` you've **only imported `Vector3`** not everything else? How is it possible otherwise, what's the part that imports the rest of the modules?
Comment: Is it because of `... from 'three'`? ` from `path/wherever/ThreeClass` should work?
Comment: Yeah i guess this makes sense, `from 'three'` imports all and produces dead code, which can be tree shaken. However, directly importing from the module, shouldn't result in dead code?
Comment: pailhead you got it right and that is basically what my answer says
Comment: @pailhead I've tried to import from "../node_modules/three/src/math/Vector3" directly but it fails with error:
<<'import' and 'export' may only appear at the top level (45590:0) while parsing...>>.
I found that using something like https://github.com/nolanlawson/rollupify solves the issue but still I am bit confused about this new ES6 import/export system and which it is its purpose if I am forced to import all the modules if I just required one.
Answer: Solved using rollupify inside browserify transform. It will perform tree shaking and remove dead code:
gulp.task("build_js", () => {

return browserify({
    entries: "./public/app/app.js",
    cache: {},
    dev: true
})
    .transform(rollupify, {config: {}})    // <---
    .transform(babelify, {presets: ["env"], plugins: ["syntax-async-functions", "transform-async-to-generator"], sourceMaps: true})
    .bundle()
    .pipe(source("app.bundle.min.js"))
    .pipe(buffer())
    .pipe(sourcemaps.init({loadMaps: mode}))
    .pipe(uglify())
    .pipe(sourcemaps.write("./"))
    .pipe(gulp.dest(config.build.js))

});

}

Still I would appreciated an explanation on why ES6 module import works like this..


Invertibility of the square root of an operator

Question: Let $\mathcal{B}(F)$ the algebra of all bounded linear operators on a complex Hilbert space $F$. Let $M\in \mathcal{B}(F)^+$ (i.e. $\langle Mx\;, \;x\rangle\geq 0$ for all $x\in F$).

The square root of $M$ is defined to be the unique operator $N$ such that
$$N^2=M.$$
In this case we write $N=M^{1/2}$

If $M$ is an invertible operators, is $M^{1/2}$ invertible?
Answer: $N(x)=N(y)$ implies $M(x)=N^2(x)=N^2(y)=M(y)$ since $M$ is injective, we deduce that $N$ is injective.
For every $y$, $y=M(x)=N(N(x))$ implies that $N$ is surjective and open (open mapping theorem)
This implies that the inverse of $N$ is continuous $N$ and $N$ is invertible.
Answer: Note that $M$ is invertible if and only if there is $\epsilon>0$ such that
$$\sigma(M)\subset [\epsilon, \infty).$$ Thus $\sigma(M^{1/2})\subset [\epsilon^{1/2},\infty)$ and $M^{1/2}$ is invertible.
Comment: Thank you for the answer. Is your equivalence well known?
Comment: I think it is. It is in fact easier than it seems. Since $M\ge 0$, we know $\sigma(M)\subset [0,\infty)$. But if $M$ is invertible, we must have $\epsilon =\min \sigma(M) >0$. The other direction is true since $0\not\in \sigma(M)$ means $M$ is invertible.
Comment: According to our answer, the converse is also true. That is if $A^{1/2}$ is invertible, then $A$ is also invertible. Do you agree with me? Thanks.
Comment: Of course, I agree with you!
Comment: I think the equivalence is true only for positive operators. That is it is better to write:'' Let $M$ be a positive operator. Then $M$ is invertible if and only if there is $\epsilon>0$ such that
$$\sigma(M)\subset [\epsilon, \infty).$$ ''
Do you agree with me? Thanks
Comment: @Schüler Yes, you are right! It was implicitly assumed that $M\in \mathcal{B}(F)^+$, as mentioned in the OP.
Comment: I think also that if there is $\epsilon>0$ such that
$$\sigma(M)\subset [\epsilon, \infty).$$ Then $$\sigma(M)\subset [0, \infty).$$ So $M$ is positive.
Comment: @Schüler That is also true.


Proof check $f(x)=\frac{2x}{x-4}$ diverges as $x\to4$ using $\epsilon-\delta$

Question: My nephew asked me to consider  $\lim_\limits{x\to 4 }\left(\frac{2x}{x-4}\right)$ for a problem set he was doing.
I explained that it diverged by substituting $x=4+\delta$ and letting $\delta\to 0$.
I thought I'd try to do it formally using $\epsilon-\delta$ definition of divergence for practice as I haven't done one in years and I find them difficult.
Could someone please check the following as there's likely an error?
I used this definition:
$\forall M>0, \exists\delta >0:|x-a|<\delta\implies f(x)>M$
For the problem at hand:
$\lim_\limits{x\to 4 }\left(\frac{2x}{x-4}\right)$
We require:
$\forall M>0, \exists\delta >0:|x-4|<\delta\implies \frac{2x}{x-4}>M$
Some scratchwork is necessary
1st manipulate $\frac{2x}{x-4}>M$ as follows
$\left|\frac{2x}{x-4}\right|>|M|\implies \frac{|2x|}{|x-4|}>M$
Note that we may assume that $\delta\leq3\implies 1\leq x \leq7$
So $|2x|\geq2$
$\frac{|2x|}{|x-4|}\geq\frac{2}{|x-4|}>M$
So we may choose $\delta=\frac{2}{M}$
Proof:
$\forall M>0 \exists \delta=\frac{2}{M}:|x-4|<\delta=\frac{2}{M}\implies \frac{2x}{x-4}>M$
Thank you
Comment: Divergence just means no convergence. In your case, what you want to prove is called converge to $\infty$ and you should check the limits of both sides, replacing $f(x)>M$ by $|f(x)|>M$.
Comment: The $\delta$ conditions should also specify $0<|x-4|$
Answer: It is nearly fine. The only problems that I see are:

The final value for $\delta$ should be $\min\left\{\frac2M,3\right\}$, not just $\frac2M$.
What that actually proves is that $\lim_{x\to4^+}\frac{2x}{x-4}=\infty$. That is, what you actually proved is that, for any $M>0$, if you take the $\delta$ from above, then$$4<x<4+\delta\implies\frac{2x}{x-4}>M$$and that is enough to prove that that limit doesn't exist (in $\Bbb R$). But $\lim_{x\to4^-}\frac{2x}{x-4}=-\infty$.
Comment: Thank you I understand what you have done.
Answer: Your definition of divergence is wrong, so I didn't read any further.
To prove: $\lim_{x \to 4} \frac{2x}{x-4}$ does not exist.
In order to get the correct epsilon-delta definition of divergence, you must specify the correct epsilon-delta definition of convergence, and then negate the definition.
The epsilon-delta definition of convergence is:
There exists a limit $L$ such that:
$\forall \epsilon > 0 ~~\exists ~\delta > 0$ such that
when $0 < |x - 4| < \delta$, then $|f(x) - L| < \epsilon,$
where $f(x) = \frac{2x}{x-4}$.
In order to prove divergence, you must therefore prove that:
For any proposed limit $L$,
a specific $\epsilon > 0$ can be found such that
regardless of how small you make $\delta$, where $0 < \delta$,
you will be able to find at least one $x$ such that both
$0 < |x - 4| < \delta~$ and $~|f(x) - L| \geq \epsilon.$
It is sufficient to demonstrate that regardless of the proposed value of $L$, setting $\epsilon = 1$ will work.
With $L$ some fixed value, and $\epsilon = 1$, regardless of the  positive value of $\delta$ chosen, you can arbitrarily decide that you are going to look for a (positive) $\delta_1 < \delta$
and then choose $x = 4 + \delta_1.$
Then, you will have that the numerator of $f(x)$ will be
greater than $8$, and
the denominator of $f(x)$ will be $\delta_1$.
Therefore, $f(x)$ will be greater than $\frac{8}{\delta_1}.$
Since you can choose $\delta_1$ as small as you want, you can choose $\delta_1$ small enough
so that $[f(x) - L] > 1 = \epsilon.$
This means that regardless of your proposed value of $L$, and regardless of your choice of (positive) $\delta$, you will be able to find at least one $x$ such that $0 < |x - 4| < \delta$ and
$|f(x) - L| > 1.$
Comment: Thank you.  I see your point about negating the definition of convergence.  I will need to mull over the specific details to be sure I understand.


What are the advantages and disadvantages of the various virtual machine image formats?

Question: Xen and Virtualbox etc both support a range of different virtual machine image formats.
These are:
vmdk, vdi, qcow & qcow2, hdd & vhd.
Without any bias toward a particular product, I'm wanting to know what are the advantages and disadvantages of the various formats both from a features perspective, robustness and speed?
One piece of info I discovered in a forum post was this:

"The major difference is that VDI uses relatively large blocks (1MB)
  when growing an image, and thus has less overhead for block pointers
  etc. but isn't ultimately space efficient in the sense that if a
  single byte is non-zero in such a 1MB block the entire space is used.
      VMDK in contrast uses 64K blocks, and thus has more management overhead and generally a bit less disk space consumption
      What offsets this is that VDI is more efficient when it comes to snapshots."

You might be thinking, I want to know this because I want to know which format to choose?  Not exactly, I'm developing some software which utilises these formats and want to support one or more of them.  Simplicity, large disks and ease of development are my main drivers.
Comment: Application design decisions aren't generally within our purview as system administrators.
Comment: In that case, please see the FAQ.
Comment: @Michael - however, this is the best place to ask as most of you will have had experience with using the formats across a range of products.  I'm wanting to know what limitations, features each have.
Answer: Unless you have a reason to do otherwise always use the format native to the virtualisation product. If you are writing an application that interfaces with VM disk formats you should write it to work with all native formats for the virtualisation products you intend to support. Trying to use one format across all products is a bad idea, as not not all products will work with any one format very efficiently, resulting in less than optimal performance for those systems where the format is not native. Please don't force anyone to change formats just to support your application.
Comment: This site is simply not a good place for this question, unfortunately. The best place to get details on vendors' virtual hard drive formats are from their own specs/documentation.
Comment: This sounds like a good answer, but you've misunderstood my reasoning.  I'm not developing a tool.  I can't actually reveal any more.  A comparison between the formats is what I probably need.
Comment: I was hoping someone might point me to a feature matrix of the different formats.  I couldn't find one.  It looks like it doesn't exist (yet).
Comment: @Matt Largely because the formats move fast enough over their versions that such a matrix is only valid for a few months.
Comment: @sysadmin1138 - You're wrong about that.  Most formats haven't changed significantly for several years. VMDK has gone through 5 revisions (over several years), qcow has 2.  Not every few months.
Comment: @Matt, that's only two formats. There are many more and the matrix must change whenever there is a change to *any* format.


How do I enable breadcrumbs?

Question: I have a page showing a list of Article nodes, where I need to display breadcrumbs as Homepage / Tag title / Article title, instead of Homepage / Article title Drupal uses by default.
I installed the Menu Breadcrumbs module, but I don't understand how to display its breadcrumbs. Are they shown in a block?
Comment: Yeah normally you have a breadcrumb block and on the structure > blocks page you place it in a region where you want to show it (above content, below hero, whatever). Breacrumbs usually show the nested path of a page in the main menu. Which usually is also reflected in a page's URL alias. Like https://example.com/tag/article. Does https://example.com/tag exist on your site? And do both the tage page and article page exist in your main menu? The article item being a child of the tag item? I have made very good experience with https://www.drupal.org/project/easy_breadcrumb.
Answer: Breadcrumb block relies on URL aliases to build its content. To have your breacrumb display "Home > Tag title" when you are on your article page, you need your article URL alias to "include" the tag URL alias.
Example:

In /admin/structure/block, make sure that the Breadcrumbs block is enabled and displayed in a region of your theme,
Create a "Tag" taxomony term called "Test tag" with "/test-tag" URL alias
Create an "Article" with "/test-tag/my-article" URL alias
That's it! Now when you visit "/test-tag/my-article", your breadcrumb block should display "Home >> Test tag"

Now, for having your breadcrumbs block display the current page title as well (e.g. "Home >> Test tag >> My Article"), this is no default configuration and you have to rely either on custom code (see this thread) or a module (https://www.drupal.org/project/current_page_crumb for a simple solution or, as leymannx mentioned it, https://www.drupal.org/project/easy_breadcrumb for a more customizable solution).
Comment: @stckvrw – https://www.drupal.org/project/pathauto
Comment: @leymannx is right. Pathauto is the module you need. It allows you to set URL alias patterns for your website contents and it automatically creates these URL aliases when you create/save content.

How do I enable breadcrumbs?


Is it true that $\forall s \geq 2, \forall k \geq 2,\; R_k(s) \leq (R_{k-1}(s))^s$?

Question: Here we denote by $R_k(s)$ the least integer $n$ such that $k$-colouring $K_n$ yields a monochromatic $K_s$
In order to prove another result ($R_k(s) \leq 4^{s^{k-1}}$) I would like to prove the result in the title: $ R_k(s) \leq (R_{k-1}(s))^s$
However, I am not sure how I may begin to do this. My first thought is that:
$\forall k \geq 2, \; R_k(s) \geq R_2(s) $ so if we let $n = R_k(s)$ and consider 2-colouring $K_{n^s}$, then we know we get a monochromatic $K_s$. If we call the colours blue and yellow, with yellow representing $k-1$ colours other than blue, then we either get a blue $K_s$ or a yellow $K_s$.
If its a blue $K_s$ then we are done, so we consider what happens if we have a yellow $K_s$.
It is at this point that I realise that a $K_s$ is too small for my goal and that if I can instead claim that I have a monochromatic $K_n$ then I would be done. However, I do not know how I can justify that this is the case.
This would necessitate that $R_2(n) \leq n^s$. I have that $R_2(s) \leq 4^s$ and so $R_2(n) \leq 4^n$ but I can't see why it would be true, if at all, that $4^n \leq n^s$, i.e. $4^{R_k(s)} \leq {R_k(s)}^s$
At this point I am completely unsure of how to continue and would appreciate a hint in the right direction, or at least verification of whether or not what I'm thinking can actually yield the desired result in the title. If there is another way to prove the inequality mentioned at the start then that would also be appreciated, thank you in advance.
Comment: It never hurts to define your terms. My wild guess: $R_k(s)$ is your notation for the least number $m$ such that any edge-colouring of $K_m$ with $k$ colors contains a monochromatic $K_s.$ Did I guess right?
Comment: @bof Yes you are right, I will add in a definition at the start.
Answer: Consider a coloring $\chi$ of $K_N$ with $k$ colors and no $K_{s_i}$ in color $i$. Pick your favorite vertex $v\in V(K_N)$ and partition $V(K_N)\setminus\{v\}$ into $V_1,\dots,V_k$ where $V_i=\{u\in V(K_N):\chi(v,u)=i\}$. By assumption, we must have $|V_i|\leq R(s_1,\dots,s_{i-1},s_i-1,s_{i+1},\dots,s_k)-1$ (the off-diagonal multicolor Ramsey number). In particular, we have $$R(s_1,\dots,s_k)\leq\sum_{i=1}^k\bigl(R(s_1,\dots,s_{i-1},s_i-1,s_{i+1},\dots,s_k)-1\bigr)+1\leq \sum_{i=1}^kR(s_1,\dots,s_{i-1},s_i-1,s_{i+1},\dots,s_k).$$
Now, I want to claim that if we have non-negative integers $s_1,\dots,s_k$ with $s_1+\dots+s_k=n$ then $${n\choose s_1,\dots,s_k}=\sum_{i=1}^k{n-1\choose s_1,\dots,s_{i-1},s_i-1,s_{i+1},\dots,s_k}.$$ Indeed, this is a quick double-counting exercise.
We now prove that $R(s_1,\dots,s_k)\leq{\sum_i s_i\choose s_1,\dots,s_k}$. For a starting place, notice that, trivially, $R(1,1,\dots,1)=1={k\choose 1,1,\dots,1}$. By the previous remarks and induction $$R(s_1,\dots,s_k)\leq \sum_{i=1}^kR(s_1,\dots,s_{i-1},s_i-1,s_{i+1},\dots,s_k)\leq \sum_{i=1}^k{\bigl(\sum_i s_i\bigr)-1\choose s_1,\dots,s_{i-1},s_i-1,s_{i+1},\dots,s_k}={\sum_i s_i\choose s_1,\dots,s_k}.$$
In particular, we've shown that $R_k(s)\leq{ks\choose s,s,\dots,s}$. For the final (poor) bound, we find $${ks\choose s,s,\dots,s}\leq\sum_{r_1+\dots+r_k=ks}{ks\choose r_1,\dots,r_k}=k^{ks}=4^{sk\log_4 k},$$ which is better than you were hoping for.


Strange behaviour in GIT diff HEAD

Question: I am under Windows and using GIT strictly locally, as a backup system.
I have my whole Eclipse workspace in it.
Searching on the net, I find that I need to do this:
Display changes since last commit:
$ git diff HEAD

I am trying to understand what precisely some maven plugin goal is doing. So I commit all my changes. Then I run the maven command. Then I go in the project directory, which is under the workspace directory, and run
git diff HEAD

It then shows me changes for the whole workspace, when in fact nothing has changed except in this directory. If I redirect it to a file, the file is 157M big!
But if I go one directory up, back in the workspace, and do the same, then it only shows me the change in the project directory. Which is what I would expect.
So my questions are:
1) Why, if I go in a sub-directory, it shows me changes that happened in the parent directory?
2) When there really is only that one change, where does it get the 157M of changes?
Comment: please provide an output of `git status`
Comment: If I'm in workspace, it shows the modified files as expected. If I go down in any sub-directory, it shows *every file in workspace* as modified. It's like if it always compared the current directory to the root, instead of comparing it to the same directory in the repository.
Comment: what state does the files have? Maybe some stranges settings in you git config. Also please provide git version and OS
Answer: Calling git diff without a path argument anywhere inside a git repository will show you the differences for the whole repository, not just the current directory (this is different than Subversion's behavior).
If you're getting different output from git diff HEAD in different directories, it means that you're moving to a different repository (or you're not actually running the exact same command).
Comment: OK, now that make sense, but if I use "." as path, it still behaves exactly like when I don't give any path. If I use a directory name then it works as expected, in the root OR in a sub-directory, so it's only "." that is behaving strangely.
Comment: That's not my experience. `git diff HEAD` from anywhere does a diff of the whole repo, but `git diff HEAD .` limits the output to things contained in the current directory.
Comment: OK. Got it. I had GIT_DIR setup, so it always compared the CWD to GIT_DIR.

Strange behaviour in GIT diff HEAD


Microsoft Exchange group calendar for periodic events/alerts

Question: I have a user request to create a shared calendar resource containing events (not meetings) that may be of interest to a small subset of my users, e.g. deadlines, contract expirations, etc. This arrangement would need to be able to send or display reminders at some interval before the event (maybe one or two days prior). I can't seem to find clear information on how to create and maintain such a group. Most references online point to third-party utilities.
Our environment is Exchange 2010 with a mix of Outlook (2007/2010), Outlook Web Access, Apple Mail and Mozilla Thunderbird on the client side.
edit: Is there a recommended third-party utility to do this? I'm looking for reminders, not meeting invitations.
Comment: Is Sharepoint a better solution for this?
Answer: You could create a shared user for this purpose and all of the interested users rw or r/o access to that shared user's calendar. They could then schedule themselves for events as they see fit on that shared user's calendar. This assumes that all of your users are part of your Exchange server email system.
Comment: This is actually a pretty good idea.
Comment: This is a close match. I'll attempt this later today.
Comment: What is the best way to accomplish this? How can I provide a shared calendar? I'm reluctant to use Public Folders for the calendar sharing since this is a new installation and I constantly hear that public folders will not persist in newer versions of Exchange.
Comment: Create a new Exchange mailbox/user and then Delegate full control to the staff that needs to use this shared calendar
Answer: If it were me (and if I understand your issue correctly), I wouldn't use a third-party add on. I would try Google Calendar to setup events following these steps:
1. Use Google calendar events. Here is guide on how to add events in Google Calendar
2a. I would sync the event to the users outlook using this process.
-or-
2b. I would integrate Google Apps and Exchange for the calendar (in step 1) as proposed here.
I think this will satisfy your user's needs although may add to their learning curve a little.


Predictions and forecasting with mixed-effects models

Question: I am not sure I fully understand how mixed-effects models (such as mixed-effects PK/PD models) can be used for forecasting.
Some notations
Let $p \in \mathbb{N}$ with $p \geq 2$. We assume that for each individual $i \in \lbrace 1,\ldots,p \rbrace$, we have $k_i \in \mathbb{N}^{\ast}$ scalar observations $(y_{i,j})_{1 \leq j \leq k_i}$ obtained at times $(t_{i,j})_{1 \leq j \leq k_i}$. Therefore, for each individual, the observations are $\left( y_{i,j}, t_{i,j} \right)_{1 \leq j \leq k_i}$. We also assume the following model:
$$ y_{i,j} = f\left( t_{i,j}, b_i, \theta \right) + \varepsilon_{i,j} $$
where $\theta$ is a vector of parameters which contains fixed effects and variance-covariance parameters ; $b_i$ is a vector of individual random effects ; $f$ is sometimes called the structural model ; $\varepsilon_{i,j}$ is the observation noise. We assume that:
$$ b_i \sim \mathcal{N}\left( 0, \mathbf{D} \right), \quad \text{and} \quad \varepsilon_i = \begin{bmatrix} \varepsilon_{i,1} \\ \vdots \\ \varepsilon_{i, k_i} \end{bmatrix} \sim \mathcal{N}\left( 0, \mathbf{\Sigma} \right). $$
The individual random effects $b_i$ are assumed i.i.d. and independent from $\varepsilon_i$.
The question
Given $\left( y_{i,j}, t_{i,j} \right)_{\substack{1 \leq i \leq p \\ 1 \leq j \leq k_i}}$, one can obtain an estimate $\hat{\theta}$ of the model parameters $\theta$ (which contain the unique coefficients in $\mathbf{D}$ and $\mathbf{\Sigma}$) by maximizing the model likelihood. This can be done, for instance, using stochastic versions of the EM algorithm (see link above).
Assume that $\hat{\theta}$ is available.
If we are given some observations $y_{s}^{\mathrm{new}}$ for a new individual $s \notin \lbrace 1, \ldots, p \rbrace$, its individual random effects are estimated by:
$$ \widehat{b_s} = \mathop{\mathrm{argmax}} \limits_{b_s} p\left( b_s \mid y_{s}^{\mathrm{new}}, \hat{\theta} \right) $$
where $p\left( \cdot \mid y_{s}^{\mathrm{new}}, \hat{\theta} \right)$ is the posterior distribution of the random effects given the new observations $y_{s}^{\mathrm{new}}$ and the point estimate of the model parameters $\hat{\theta}$. Thanks to Bayes' theorem, this is equivalent to maximizing the product "likelihood $\times$ prior:
$$ \widehat{b_s} = \mathop{\mathrm{argmax}} \limits_{b_s} p\left( y_{s}^{\mathrm{new}} \mid b_{s}, \hat{\theta} \right) p\left( b_{s} \mid \hat{\theta} \right). $$
Now, if $t \, \longmapsto \, f(t, \cdot, \cdot)$ is a continuous function of time, we may call it a growth curve. It describes the evolution of the measurements with time. Let $i_{0} \in \lbrace 1, \ldots, p \rbrace$ and $t$ such that $t_{i_{0},1} < \ldots < t_{i_{0},k_i} < t$.

How can we use this mixed-effects model to predict the most likely value $y_{i_{0}}^{\ast}$ for individual $i_{0}$ at time $t$? This relates to forecasting since we want to predict the measurement value at a future time.

Naively, I would do as follows. Given $\left( y_{i,j}, t_{i,j} \right)_{\substack{1 \leq i \leq p \\ 1 \leq j \leq k_i}}$, I would estimate $\hat{\theta}$ (we estimate the model parameters using all the data including the past observations for individual $i_{0}$). Then I would estimate $\widehat{b_{i_{0}}}$ as described above. Eventually, I would say that:
$$ y_{i_{0}}^{\ast} = f\left( t, \widehat{b_{i_{0}}}, \hat{\theta} \right). $$
If this is right, I don't see how I would prove it mathematically. Still, I'm feeling like I'm missing something because this predicted value $y_{i_{0}}^{\ast}$ does not take into account the noise distribution. Also, I do not see how I would be able to estimate CIs for $y_{i_{0}}^{\ast}$ with this.
In a Bayesian setting (with a prior distribution on $\theta$), would I need to use the posterior predictive distribution (see this post and these notes)? From what I understand, if $y_{i_{0}}$ denotes the vector of the past observations for individual $i_{0}$, this posterior predictive distribution is given by:
$$ p\left( y_{i_{0}}^{\ast} \mid y_{i_{0}} \right) = \int_{\Theta} p\left( y_{i_{0}}^{\ast} \mid \theta, y_{i_{0}} \right) p\left( \theta \mid y_{i_{0}} \right) \, d\theta. $$
However, I'm not sure it applies here and I'm not sure where the random effects come in.
Any reference, explanation, hint,... is welcome ! :-)
Comment: +1! I was asking myself more or less the same question some time ago but I was unable to find relevant material (lecture notes, research papers) which deal with this topic (mixed-effects models + forecasting).
Answer: Indeed, the procedure you describe is what it is typically done in mixed-effects models. When you fit the models under maximum-likelihood you only get $\hat \theta$, and then using empirical Bayes you get an estimate of $\hat b_i(\hat \theta)$, which you plug-in the equation to obtain a prediction for a particular subject. In the context of linear mixed models, the resulting predictions are calls Best Linear Unbiased Predictions (BLUPs), and you can find more info, for example in, Searle, Casella and McCulloch (1992, Chapter 7) or in McLean, Sanders and Stroup (1991, The American Statistician 45, 54-64).
Calculating standard errors or a confidence interval is more tricky but could be done with a procedure that mimics the Bayesian approach. That is, you could repeat the following steps, say $M = 1000$ times:

Simulate $\theta^*$ from $\mathcal N\{\hat \theta, \mbox{var}(\hat\theta)\}$.
Simulate $b_i^*$ from the posterior distribution of the random effects, i.e., $[p(y_i \mid b; \theta^*) p(b; \theta^*)]$.
Calculate $y_{pred}^*(m) = f(t, \theta^*, b_i^*)$

The first step accounts for the uncertainty in the maximum likelihood estimates, and the second step accounts for the uncertainty in the random effects.
You can get as an estimate for standard error using the sample standard deviation of the $y_{pred}^*(1), \ldots, y_{pred}^*(M)$ values.


How can I parse string into Hiccup?

Question: How can I parse a string of Hiccup into a Hiccup node?
For example,
"[:b 'hello world']" into [:b "hello world"]
Answer: Use reader to convert string to data structures:
user=> (clojure.edn/read-string "[:b 'hello world']")
[:b 'hello world']

You should use " to denote string:
user=> (clojure.edn/read-string "[:b \"hello world\"]")
[:b "hello world"]

Comment: Thanks! For those using Clojurescript you'll want `[cljs.reader]`

How can I parse string into Hiccup?


Removing oldest file in directory with spaces in name

Question: Hi everyone I'm trying to remove a file in a directory that has spaces in the name I'm currently trying to do this
rm `ls -t1 | tail -1`

only problem I have is that I can't remove the oldest file if it has spaces in the name
Is there a work around this?
Thanks!
Comment: This question might be get better answers on [unix.se].
Answer: rm "$(ls -t|tail -1)"

(The 1 argument to ls isn't needed.)
Comment: Is that a filename or part of a date? My point was, say the subdir is `sub` and the file is `somefile`. The `ls` is giving you `somefile` but you need to `rm sub/somefile`. The path isn't included.
Comment: Hi thanks! I have a followup question to that what if I wanted to remove the oldest file in a subdirectory?  I tried rm "$(ls -t subdirectory | tail -1)" but it says no such file even though it shows it?
Comment: Change the `rm` to `echo` and you'll see that the path isn't included -- you're trying to remove it from the current directory. You could `cd` to the subdirectory first.
Comment: that's weird cause when i use echo it still shows the file i just can't rm it from the parent directory?  does it have something to do with the spaces in the file name?
Comment: here's what terminal is giving me: rm: cannot remove 'file Sun Jun 29' : no such file or directory


Rake aborted, Error while trying to load the gem 'uglifier'

Question: I'm following 'Getting Started with Ruby on Heroku', but when attempting to run the demo app locally with
$ bundle exec rake db:create db:migrate

I get
sam@samoliver:~/ruby-getting-started$ bundle exec rake db:create db:migrate --trace
rake aborted!
Bundler::GemRequireError: There was an error while trying to load the gem 'uglifier'.
/home/sam/.rvm/gems/ruby-2.2.3/gems/bundler-1.11.0/lib/bundler/runtime.rb:80:in `rescue in block (2 levels) in require'
/home/sam/.rvm/gems/ruby-2.2.3/gems/bundler-1.11.0/lib/bundler/runtime.rb:76:in `block (2 levels) in require'
/home/sam/.rvm/gems/ruby-2.2.3/gems/bundler-1.11.0/lib/bundler/runtime.rb:72:in `each'
/home/sam/.rvm/gems/ruby-2.2.3/gems/bundler-1.11.0/lib/bundler/runtime.rb:72:in `block in require'
/home/sam/.rvm/gems/ruby-2.2.3/gems/bundler-1.11.0/lib/bundler/runtime.rb:61:in `each'
/home/sam/.rvm/gems/ruby-2.2.3/gems/bundler-1.11.0/lib/bundler/runtime.rb:61:in `require'
/home/sam/.rvm/gems/ruby-2.2.3/gems/bundler-1.11.0/lib/bundler.rb:99:in `require'
/home/sam/ruby-getting-started/config/application.rb:7:in `<top (required)>'
/home/sam/ruby-getting-started/Rakefile:4:in `require'
/home/sam/ruby-getting-started/Rakefile:4:in `<top (required)>'
/home/sam/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rake/rake_module.rb:28:in `load'
/home/sam/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rake/rake_module.rb:28:in `load_rakefile'
/home/sam/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rake/application.rb:689:in `raw_load_rakefile'
/home/sam/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rake/application.rb:94:in `block in load_rakefile'
/home/sam/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rake/application.rb:176:in `standard_exception_handling'
/home/sam/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rake/application.rb:93:in `load_rakefile'
/home/sam/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rake/application.rb:77:in `block in run'
/home/sam/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rake/application.rb:176:in `standard_exception_handling'
/home/sam/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rake/application.rb:75:in `run'
/home/sam/.rvm/rubies/ruby-2.2.3/bin/rake:33:in `'
ExecJS::RuntimeUnavailable: Could not find a JavaScript runtime. See https://github.com/sstephenson/execjs for a list of available runtimes.
/home/sam/.rvm/gems/ruby-2.2.3/gems/execjs-2.2.2/lib/execjs/runtimes.rb:51:in `autodetect'
/home/sam/.rvm/gems/ruby-2.2.3/gems/execjs-2.2.2/lib/execjs.rb:5:in `<module:ExecJS>'
/home/sam/.rvm/gems/ruby-2.2.3/gems/execjs-2.2.2/lib/execjs.rb:4:in `<top (required)>'
/home/sam/.rvm/gems/ruby-2.2.3/gems/uglifier-2.5.3/lib/uglifier.rb:3:in `require'
/home/sam/.rvm/gems/ruby-2.2.3/gems/uglifier-2.5.3/lib/uglifier.rb:3:in `<top (required)>'
/home/sam/.rvm/gems/ruby-2.2.3/gems/bundler-1.11.0/lib/bundler/runtime.rb:77:in `require'
/home/sam/.rvm/gems/ruby-2.2.3/gems/bundler-1.11.0/lib/bundler/runtime.rb:77:in `block (2 levels) in require'
/home/sam/.rvm/gems/ruby-2.2.3/gems/bundler-1.11.0/lib/bundler/runtime.rb:72:in `each'
/home/sam/.rvm/gems/ruby-2.2.3/gems/bundler-1.11.0/lib/bundler/runtime.rb:72:in `block in require'
/home/sam/.rvm/gems/ruby-2.2.3/gems/bundler-1.11.0/lib/bundler/runtime.rb:61:in `each'
/home/sam/.rvm/gems/ruby-2.2.3/gems/bundler-1.11.0/lib/bundler/runtime.rb:61:in `require'
/home/sam/.rvm/gems/ruby-2.2.3/gems/bundler-1.11.0/lib/bundler.rb:99:in `require'
/home/sam/ruby-getting-started/config/application.rb:7:in `<top (required)>'
/home/sam/ruby-getting-started/Rakefile:4:in `require'
/home/sam/ruby-getting-started/Rakefile:4:in `<top (required)>'
/home/sam/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rake/rake_module.rb:28:in `load'
/home/sam/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rake/rake_module.rb:28:in `load_rakefile'
/home/sam/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rake/application.rb:689:in `raw_load_rakefile'
/home/sam/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rake/application.rb:94:in `block in load_rakefile'
/home/sam/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rake/application.rb:176:in `standard_exception_handling'
/home/sam/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rake/application.rb:93:in `load_rakefile'
/home/sam/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rake/application.rb:77:in `block in run'
/home/sam/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rake/application.rb:176:in `standard_exception_handling'
/home/sam/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rake/application.rb:75:in `run'
/home/sam/.rvm/rubies/ruby-2.2.3/bin/rake:33:in `'
sam@samoliver:~/ruby-getting-started$

I tried removing and adding 'uglifier' (2.5.3) again to no effect and I do have 'therubyracer'  installed, so I don't understand what is ExecJS complaining about.
Gemfile
source 'https://rubygems.org'
ruby '2.2.3'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.2.3'
# Use postgresql as the database for Active Record
gem 'pg'
gem 'rails_12factor', group: :production
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0.3'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .js.coffee assets and views
gem 'coffee-rails', '~> 4.0.0'
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer',  platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0',          group: :doc

# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring',        group: :development

# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

gem 'puma'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

# Use debugger
# gem 'debugger', group: [:development, :test]

Comment: Try install node.js. In Ubuntu: sudo apt-get install nodejs
Comment: Thank you, that did it. I got another error now, will try to figure out. Would you know why nodejs solved it, while therubyracer didn't?
Comment: I think therubyracer doesn't install any JS runtime.
Comment: Fair enough. Thanks again!
Comment: I had the same problem on an EC2 Ubuntu instance just today.  Thanks for the answer @AlexanderShlenchack!
Comment: Uncomment: `gem 'therubyracer',  platforms: :ruby`
Comment: @SamOliver That fixed it for me! You should maybe put it in as an answer so I could upvote it?
Answer: install nodejs
apt-get install nodejs

Answer: uncomment the line below in Gemfile
#gem 'therubyracer', platforms: :ruby

run in the terminal
bundle install

Comment: This one helped on FreeBSD, the accepted answer didn't!
Comment: @DenisMysenko I also use FreeBSD. I always need to use `therubyracer` in my Gemfile to make rails work. Even though I have `node` installed. How did you do it? Any PATH set in the application config?
Answer: Uglifier is JavaScript compressor, so it need javascript runtime try installing nodejs
Run this to install NodeJS in Ubuntu
sudo apt-get install nodejs

or
brew install nodejs

if you are on a OSX.
Answer: I was having the same problem. I had to go into my root folder (on ubuntu use
sudo su)

From there use apt-get install nodejs, then exit the root and run bundle install then you should be able to run rake db:migrate
Answer: Try this:
gem update --system 1.4.2

Comment: This answer could be improved by adding some descriptive information about what the command does and why it will help.  Were you able to reproduce the OP's issue and did this fix it?


What does html5 boilerplate stand for?

Question: Like its style.css has body <code>{background:transparent}</code>.
So am I supposed to keep the background transparent, so I always make a good html5 website?
Are these default ?
Should I override them as per my website ?
Answer: The idea of the boilerplate is to give a base set of code which you won't need to change - as these tags will always be used on every site. Of course there will be exceptions to this, as you may use a different javaScript library or not agree with how Paul Irish targets Internet Explorer (see his article and comments on this).
If you are starting to explore HTML5 and CSS3 then this is a fantastic starting point but you should always adapt (and ideally form your own boilerplate tailored to your sites and coding style) the core code as you learn and start to create HTML5 sites.
In the CSS, the code included is for a CSS reset, based on resets mentioned in the code comments. So where the body background is transparent this is to make sure it is the same in every browser. There is an empty section in the CSS for your own styles:

200. /* Primary Styles
201.    Author:
202. */

So if you wanted a specific background colour you can state it here, along with any other styles you add.
Answer:
So am i suppose to keep background
  transparent always to make good html5
  website ?

No.

Are these default ?

No.

Should i override them as per my
  website ?

Yes.
Boilerplate code definition from wikipedia (more eloquent than i would be), and an example and short description of a reset stylesheet.
Comment: Hey Nim...Thanks for your reply. Can u please elaborate a bit what exactly boilerplate is ? I mean what they mean by css reset ? And for example, what background:transparent means in style.css ?
Comment: ammended answer follow the links.

What does html5 boilerplate stand for?