Typewriter effect using TextView.postDelayed inside ScrollView in Android

Question: I am creating a runnable typewriter effect using a textview inside a scrollview.
this is what I did...
<code>    final ScrollView sv = new ScrollView(this);
    sv.setLayoutParams(new LinearLayout.LayoutParams((int)display.getWidth()/2, (int)((display.getHeight()/4))*3));
    sv.setPadding(0, px2DP(10), px2DP(10), px2DP(10));

    final CharSequence text = getResources().getText(R.string.longstring);

    final TextView content = new TextView(this);
    content.setBackgroundColor(getResources().getColor(R.color.Black));
    content.setTextColor(getResources().getColor(R.color.White));
    content.setTextSize(TypedValue.COMPLEX_UNIT_SP,20);
    content.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));

    sv.addView(content);

    content.postDelayed(new Runnable(){
        @Override
        public void run() {
            content.append(text.subSequence(0, index++));
            sv.fullScroll(View.FOCUS_DOWN);
        }

    },70);
</code>
I am only getting a black box and no text.
What am I doing wrong? Please help.
PS. I already found the solution!
Comment: Do you add the ScrollView to the main view? Also, what if you do a `sv.invalidate()` in the Runnable?
Comment: Yeah, test to make sure everything is setup correctly. Try adding before your `content.postDelayed(...);`: `content.setText("Testing")` just to make sure the simple case displays correctly.
Comment: Also, note that postDelayed runs the Runnable only once. http://developer.android.com/reference/android/view/View.html#postDelayed(java.lang.Runnable,+long)
Comment: @Jonas yes the scroll view is within the onCreate of the main view. I did what you told me about invalidate(), I tried adding it before content.append -- nothing happened,

before sv.fullscroll() //even tried after fullScroll -- still nothing happened.

(Kabuko) I tried what you recommended. The text fully displays when it is outside the Runnable -- and will get a fullScroll after that.

if the Runnable only runs once.. is there a way to iterate it?
Answer: Solution found. I am using the handler-runnable concept wrong. Based on what Jonas pointed out, Runnable only runs once. Therefore a loop is necessary.
As suggested on this link:
How to run a Runnable thread in Android?
The answer is something similar to recursion.
Anyway thanks guys! Android is so cool.


SQL 5.6 Foreign key statement error

Question: i am new to SQL and i am trying out some simple create table statement but i am facing some problem with the foreign key at EMPLOYEEGROUP table. Below is a part of my create table statement
<code>   CREATE TABLE `User` (
`Userid` int(11) NOT NULL AUTO_INCREMENT,
`Username` VARCHAR(15) NOT NULL,
`Password` VARCHAR(15) NOT NULL,
PRIMARY KEY (Userid)
);

CREATE TABLE `Group` (
`GroupID` int(11) NOT NULL AUTO_INCREMENT,
`GroupName` VARCHAR(15) NOT NULL,
PRIMARY KEY (GroupID)
);

CREATE TABLE `EMPLOYEEGROUP` (
`EmployeeID` int(11) NOT NULL,
`AssignedGrp` int(11) NOT NULL,
CONSTRAINT EMPLOYEEGROUP_FK1 FOREIGN KEY (EmployeeID) REFERENCES User (Userid),
CONSTRAINT EMPLOYEEGROUP_FK2 FOREIGN KEY (AssignedGrp) REFERENCES Group (GroupID)
);
</code>
There is some issue with my EMPLOYEEGROUP_FK2 statement which i can't seem to solve it. any help would be appreciated. Thank you
Answer: In mysql GROUP is a reserved keyword. and you used group as table name
. but in table name you write group with `` . and when you take reference of group table you write group without ``. simple add `` in group name
Try blow query. it execute in my system hopfully execute also your system
<code>  CREATE TABLE `User` (
`Userid` int(11) NOT NULL AUTO_INCREMENT,
`Username` VARCHAR(15) NOT NULL,
`Password` VARCHAR(15) NOT NULL,
PRIMARY KEY (Userid)
);

CREATE TABLE `Group` (
`GroupID` int(11) NOT NULL AUTO_INCREMENT,
`GroupName` VARCHAR(15) NOT NULL,
PRIMARY KEY (GroupID)
);

CREATE TABLE `EMPLOYEEGROUP` (
`EmployeeID` int(11) NOT NULL,
`AssignedGrp` int(11) NOT NULL,
CONSTRAINT EMPLOYEEGROUP_FK1 FOREIGN KEY (EmployeeID) REFERENCES User (Userid),
CONSTRAINT EMPLOYEEGROUP_FK2 FOREIGN KEY (AssignedGrp) REFERENCES `Group` (GroupID)
);
</code>
Comment: Thank you! I been trying this for the past few hour and it did not occur to me its the naming problem.

SQL 5.6 Foreign key statement error


Extending the concept of distribution function to any totally or partially ordered measurable space

Question: Let $(\Omega,\mathcal A, P)$ be a probability space. Let $(Y,\Sigma)$ be a measurable space. Let $X:(\Omega,\mathcal A) \to (Y, \Sigma)$ be a random variable. Then $X$ has probability measure $\mu_X = P \circ X^{-1}$, also called the distribution of $X$, in the probability space, also called the distribution space, $(Y, \Sigma, \mu_X)$.
In Wikipedia and other Google search, the concept of a distribution function $F_X: Y \to [0,1]$ in measure theory and probability theory seems to be limited to the case where $Y = \Re$, where
$$F_X(t) = P(\{\omega \in \Omega : X(\omega) \leq t\})$$
For example this Wikipedia definition of distribution function is limited to $Y= \Re$:

Let $ \mu $ be a measure on the real numbers, equipped with the Borel
$\sigma$-algebra. Then the function $$ F_\mu \colon \Re \to \Re \cup \{ +\infty, - \infty \} $$ defined by $$ F_\mu(t)= \begin{cases} \mu((0,t]) & \text{if } t\geq 0 \\ -\mu((t,0]) & \text{if } t < 0\end{cases}$$ is called the (right continuous) distribution function
of the measure $ \mu $.

Similarly, in these lecture notes on measure theory, the concept of a distribution function $F: Y \to [0,1]$ is limited to domain $\Re$:

Definition 4. A map $F:\Re\to[0,1]$ is said to be a distribution function if it is increasing, right continuous and $F(-\infty) = 0 = 1-F(\infty)$.

even though the concept of a distribution $\mu: \Sigma \to [0,1]$ is stated more generally:

Definition 7. Let $Y$ be a metric space. A $Y$-valued random variable on a probability space $(X,\Sigma,p)$ induces a Borel probability measure on $Y$ as follows:  $$p_x(S) = p(x^{-1}(S))$$ for every $S \in B(Y)$.  This is the distribution of $x$.  If $Y =\Re$, then we call this the distribution function of $x$.

Q. Can the restriction of $Y$ to $\Re$ be lifted in case $Y$ has a total or partial order?  This is exactly the point I am trying to generalize.  In place of "If $Y=\Re$" I want to say "If $Y$ is totally ordered" or "If $Y$ is partially ordered" or something of this nature which indicates that $Y$ has enough order to define a distribution function as opposed to a distribution.  This is the essence of the question, no more no less.  The above definition seems to work fine for any totally ordered $Y$.  Actually, since only $\leq$ is involved, it seems that we really only need $Y$ to be partially ordered.
Comment: With the level of abstraction given, in a purely mathematical context (i.e. without considering an application domain like game theory), can you give the conditions on measurable space $(S,\Sigma)$ such that $F_X(t) = P(\{\omega \in \Omega : X(\omega) \leq t\})$ is a cumulative distribution function, for $t \in S$, so $F_X: S \to [0,1]$?
Comment: To my understanding, I can construct a probability space $(\Omega,\mathcal F,\mathbb P)$ and random variable $X: \Omega\to S$, where $(S,\Sigma)$ is some measurable space, which has $\mu\mathbb P$ but not $F_X$.  The definition $F_X(u) = \mathbb P[X \leq u]$ depends on a relation $\leq$ being defined on the range $S$ of $X: \Omega\to S$.  It doesn't have to be, and $F_X$ doesn't have to exist.  So the question is, if $S$ happens to have an ordering relation $\leq$, does it have to be a total order or can it be a partial order, for $F_X$ to be a CDF.
Comment: What do you mean? For any probability space $(\Omega,\mathscr{F},\mathbb{P})$ and any measure space $(S,\Sigma)$, as long as  there is a function $X:\Omega\rightarrow S$ that is $\mathscr{F}$-$\Sigma$ measurable (i.e. $X^{-1}(V)=\{\omega\in\Omega:X(\omega)\in V\}\in\mathscr{F}$ for all $V\in\Sigma$), the set function $\mathbb{P}_X$ defined on $\Sigma$ as $\mathbb{P}_X(A)=\mathbb{P}(X^{-1}(A))$ is a probability measure on $(S,\Sigma)$. I only pointed out that the is interest in considering $(S,\Sigma)$ as totally order space comes from problems in decision theory and economics.
Comment: The predicate $X(\omega) \leq t$ requires at least a partial order.  This is for a distribution function $F_X: S \to [0,1]$, which is distinct from a distribution $\mu_X: \Sigma \to [0,1]$.
Comment: Thanks for the paper!  I am looking for the conditions to define the distribution function. Suppose $\Omega=\{a,b\}$ and $X(\omega)=\omega$ is my random variable, and $P[\{a\}]=P[\{b\}] = \frac{1}{2}$. There is no order defined on $\Omega$ so I can't form the sets $\{x : x < t\}$.  I need $\Omega$ to be provided with an order relation $<$.  Otherwise this is a case where I have a probability space with a distribution but without a distribution function.  So the question is (a) Do I need an order $<$ to define a CDF? (I think Yes).  (b) Can it be partial? (I guess No, it has to be total.)
Comment: I'm not trying to impose order.  I'm just saying that in the usual presentation of CDF, it is assumed that random variable $X: \Omega \to \Re$.  $\Re$ is ordered.  This allows to define the CDF which is $F: \Re \to [0,1]$.  CDF depends on the presence of an order, it's in the definition.  I'm not asking a deep question or trying to impose anything on anything.  I'm just asking what I need to have when I want to extend the idea of a CDF to other $S$ other than $\Re$.  It's really a simple question.
Comment: It just so happens that the distribution (by that I mean the push-fowrard of $\mathbb{P}$ by $X$, $\mu\mathbb{P}(A)=\mathbb{P}(X^{-1}(A))$  of a real valued random variable $X$ is completely determined by the function $F_X(u)=\mathbb{P}[X\leq u]$, $u\in\mathbb{R}$,  known as the cumulative distribution function (cdf) of $X$. That is the extent to which one considers cdf's.  That does not mean that any probability space $(\Omega,\mathscr{F},\mathbb{P})$ is related to an order (partial or total) on $\Omega$ that is somehow compatible to the structure in $\mathscr{F}$.
Comment: I would think that total order together with separability assumptions would be necessary. As for sufficiency, you may try to mimic the construction of the Lebesgue-Stieltjes measure on $\mathbb{R}$ starting from a "CDF" and see for yourself if that can be done. See the construction in Cohn's Measure theory for instance (Proposition 1.3.9 on page 19). The CDF should be right continuous. This is why separability would be required.
Comment: I'm surprised  this is not in a book as a standard generalization of the idea of a CDF.  To give a sense of where I'm coming from: For my idea of random variable I am referring to Remark 1 on page 8 of http://www.columbia.edu/~md3405/DT_Risk_2_15.pdf.  He defines the usual CDF in Definition 4 on page 6.  He defines a general distribution in Definition 7 page 9.  Only in case $Y=\Re$ does he call it a distribution function. This is the spot where I think restricting to the case of $\Re$ is too specific and $Y$ could be any metric space with something like "total order with separability".
Comment: Closing in on it, this comment seems evocative: "In Wheeden and Zygmund, the "distribution function" is defined for finite measure spaces $(\Omega,\mathcal F,\mu)$ as $\mu(\{f > \lambda\})$. https://www.google.com/books/edition/An_Introduction_to_Measure_and_Probabili/jiMRBwAAQBAJ?hl=en&gbpv=1&bsq=distribution%20
Comment: In WZ (and in many books on Analysis) $f\geq0$ and the measure induced by $f$ on $[0,\infty)$, when $f$ is integrable with respect to $\mu$ is fully characterize by the map $\lambda\mapsto\mu(f>\lambda)$, similar as to what happens in probability with CDFs. It seems you are too worked up with the word distribution.
Comment: I will add some examples in the problem statement to show the point I am trying to generalize.  In any event though it's likely to be in Chapter 4 of this book: https://www.google.com/books/edition/Probabilistic_Metric_Spaces/8LUd6Txuu5sC?hl=en&gbpv=1&bsq=distribution%20functions
Comment: As for Remark 1 on p.8, which refers to measurability, hidden is the fact that the collection of intervals $(-\infty,a]$ generate the whole Borel $\sigma$-algebra in $\mathbb{R}$. That is possible because of separability. There is nothing restrictive with working with $\mathbb{R}$. In a precious bounty of yours, I mentioned to you a deep theorem that established the "measurable" equivalence between $\mathbb{R}$ (or $(0,1)$) and complete separable metric spaces. That is why $\mathbb{R}$, for the most part, is enough.
Comment: Thank you.  I will look at that reference.  The bounty question led to this question because I am still trying to separate out the idea of probability space as an indexing space for a domain of interest (some measurable space) from the measurable space which is the "real world" domain of some experiment (for example a pair of dice).  Part of getting my head around that separation is this question of generalizing the concept of distribution function to non-$\Re$ domains. The bounty was difficult to award because all answers were great, so I went with the one that responded in form Q1/Q2/Q3.
Comment: CDFs are defined only for $\mathbb{R}$ (even for $\mathbb{R}^n)$ and are used for convenience. The push-forward is of a measure $\mu$ by a Radom variable $X:(\Omega,\mathscr{F},\mu)\rightarrow(S,\Sigma)$, $\mu_X(A):=\mu(X\in A)$ is the object of interest and it is as general as it can be, since $(S,\Sigma)$ has no structure other than being a measurable space.
Comment: I've clarified the question by quoting the specific texts I am looking at.  If the CDF concept can't be generalized to a domain other than $\Re$ that has an order $\leq$, please answer the question in the negative.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/111447/discussion-between-oliver-diaz-and-lars-ericson).
Answer: Straw man answer. This question isn't attracting answers, so I'll do the best I can.  If you downvote this answer, please give your rationale in the comments or provide a better answer.
Let

$(Y, d)$ be a metric space
$(X, \Sigma, P)$ be a probability space
$V: (X, \Sigma) \to (Y,d)$ be a $Y$-valued random variable
$V^{-1}(E) = \{x \in X: V(x) \in E\}$ be the generalized inverse of $V$
$\mu_V(E) = P(V^{-1}(E))$ be the distribution
$F_V(E) = P(\{x \in X: V(x) \leq e\})$ be the distribution function

Clearly $F_V(E)$ is well defined for any metric space $(Y,d)$ provided with a relation $a \leq b$ for all $a,b \in Y$.
From this question:

All metric spaces can be totally ordered.
Not all metric spaces have a total order which is "compatible with the ring structure".  (So: not sensible or useful in that specific sense.)  For example, the complex numbers $\mathbb C$.

So in the strict sense that all metric spaces can be totally ordered, the distribution function always exists, but it may be "uninteresting".
So to be "obviously useful", it is only necessary to stipulate that the metric space $(Y,d)$ is an "obviously useful" ordered metric space.  Here we have range of possible more or less useful orderings:

$Y$ is a partially ordered set
$Y$ has a partial order compatible with the ring structure
$Y$ is a totally ordered set
$Y$ is a Complete metric space

Following this discussion in Zulip, for random variable whose codomain is a a measurable space with a preorder, the generalized distribution function can be constructed in Lean as follows:
<code>import measure_theory.lebesgue_measure
import tactic

noncomputable theory

open measure_theory

class probability_space (α : Type*) extends measure_space α :=
(is_probability_measure :  probability_measure volume)

namespace probability_space
variables {α : Type*} [probability_space α]

lemma volume_univ : volume (set.univ : set α) = 1 :=
is_probability_measure.measure_univ

lemma volume_le_one (S : set α) : volume S ≤ 1 :=
by rw ← @volume_univ α; exact measure_mono (set.subset_univ _)

def prob (S : set α) : ℝ := (volume S).to_real

def nnprob (S : set α) : nnreal := (volume S).to_nnreal

theorem volume_eq_nnprob (S : set α) : volume S = nnprob S :=
(ennreal.coe_to_nnreal $ ne_top_of_le_ne_top (by rintro ⟨⟩) (volume_le_one S)).symm

theorem prob_eq_nnprob (S : set α) : prob S = nnprob S := rfl

theorem nnprob_le_one (S : set α) : nnprob S ≤ 1 :=
ennreal.coe_le_coe.1 $ by rw ← volume_eq_nnprob; exact volume_le_one S

theorem prob_le_one (S : set α) : prob S ≤ 1 := nnprob_le_one _

theorem zero_le_prob (S : set α) : 0 ≤ prob S := nnreal.zero_le_coe

theorem nnprob_mono {S T : set α} (h : S ⊆ T) : nnprob S ≤ nnprob T :=
ennreal.coe_le_coe.1 $ by simpa only [← volume_eq_nnprob] using measure_mono h

theorem prob_mono {S T : set α} (h : S ⊆ T) : prob S ≤ prob T :=
nnreal.coe_le_coe.2 $ nnprob_mono h

end probability_space

theorem measurable.map_probability_measure {α β} [probability_space α] [measurable_space β]
  {f : α → β} (hf : measurable f) :
  probability_measure (measure.map f volume) :=
⟨by rw measure_theory.measure.map_apply hf is_measurable.univ;
    exact probability_space.volume_univ⟩

structure random_variable (α β : Type*) [probability_space α] [measurable_space β] :=
(outcome : α → β)
(is_measurable_outcome : measurable outcome)

variables {α β : Type*} [probability_space α] [measurable_space β]

namespace random_variable
instance : has_coe_to_fun (random_variable α β) := ⟨_,outcome⟩
variable (X : random_variable α β)
lemma measurable : measurable X := X.is_measurable_outcome

-- distribution of X
def induced (X : random_variable α β) : probability_space β :=
{ volume := measure.map X volume,
  is_probability_measure := X.measurable.map_probability_measure }

variables [preorder β]

-- distribution function of X
def CDF (x : β) :
  ℝ := @probability_space.prob _ X.induced {c | c ≤ x}

lemma prob_eq_CDF (x : β) : X.CDF x = @probability_space.prob β X.induced {c | c ≤ x} := rfl

theorem zero_le_CDF (x : β) : 0 ≤ X.CDF x :=
begin
  rw prob_eq_CDF,
  exact (@probability_space.zero_le_prob β X.induced {c : β | c ≤ x}),
end

theorem CDF_le_one (x : β) : X.CDF x ≤ 1 :=
begin
  rw prob_eq_CDF,
  exact (@probability_space.prob_le_one β X.induced {c : β | c ≤ x}),
end

-- distribution function of X with codomain correctly restricted to [0,1]
def CDF_in_01 (x: β) : set.Icc (0 : ℝ) 1 := ⟨ X.CDF x, X.zero_le_CDF x, X.CDF_le_one x⟩

-- Example of a measurable codomain

variables [topological_space β] [order_closed_topology β] [opens_measurable_space β]

example (b : β) : is_measurable {c | c ≤ b} := is_closed.is_measurable is_closed_Iic

end random_variable

</code>
Comment: Every set can even be well ordered (Axiom of choice kind of stuff) but the ordered may not be compatible with the measurable structure. In your answer the assumption that ithe  metric space $Y$ is already ordered ( in defining $F_V$) is implicit. That is not the case in general. Also, for $F_V$ to be a useful thing, that is one can generate the $\mu_V$ from $F_V$ more structure is required (separability for instance).  In general one does have an order on $(Y,d)$.
Comment: If $(Y,d)$ is s Borel space (a Polish space for instance) then it is measurable isomorphic to $(0,1)$ and one can define an order in $Y$. The isomorphism however is not explicit, it is based on constructions that use the axiom of choice. That should not deter anybody to do probability on $(Y,d)$, one does not need order not cumulative distribution functions in this setting.


Spherical coordinates and rotations of axes

Question:
Let $P_o$ denote the position with the coordinates $(1,0,0)$ in the Descartes coordinate system $(x,y,z)$.
The point $P_o$ is rotated about the z-axis so that the line $OP_o$ turns directly towards the positive y-axis through an angle $\phi$. The position of the point after this rotation is denoted by $P_1$
$P_1$ is then rotated about the line in the x-y plane perpendicular to $OP_1$ so that the line $OP_1$ turns directly towards the positive z-axis through an angle $\lambda$, giving $P_2$. Find the coordinates of $P_2$

Initially I approached this question using the spherical coordinates:
$$x=rsin(\theta)cos(\phi), y=rsin(\theta)sin(\phi), z=rcos(\theta) \tag{1}$$
where $\theta$ is the polar angle and $\phi$ the azimuthal angle.
Setting $\theta=\frac{\pi}{2}-\lambda$ and $\phi=\phi$ gave me the correct the answer:
$$P_2=(cos(\phi)cos(\lambda),sin(\phi)cos(\lambda),sin(\lambda))\tag{2}$$

However, I then tried an alternative method by rotating the coordinate axes and an incorrect answer was obtained:
I rotated the coordinate axes $(x,y,z)$ by the angle $\phi$ anticlockwise about the z-axis. Denoting the new coordinate axes by  $(\bar{x},\bar{y},\bar{z})$, we have
$$x=\bar{x}cos(\phi)-\bar{y}sin(\phi)$$
$$y=\bar{x}sin(\phi)+\bar{y}cos(\phi)$$
$$z=\bar{z} \tag{3}$$
since $$ \left(\begin{matrix} x\\y\\z \end{matrix} \right)=\left(\begin{matrix} cos{(\phi)}&-sin(\phi)&0 \\ sin(\phi)&cos(\phi)&0\\0&0&1\end{matrix}\right) \left(\begin{matrix} \bar{x}\\ \bar{y} \\ \bar{z} \end{matrix}\right) \tag{4}$$
Now in the $(\bar{x},\bar{y},\bar{z})$ coordinate system, $P_1$ has the coordinates $(1,0,0)$.
Rotating $P_1$ through the angle $\lambda$ anticlockwise about $\bar{y}$ gives $P_2$
$$\left(\begin{matrix} cos(\lambda)&0&sin(\lambda)\\0&1&0\\-sin{(\lambda)}&0&cos(\lambda) \end{matrix}\right) \left( \begin{matrix}1\\0\\0 \end{matrix}\right)=\left(\begin{matrix}cos(\lambda)\\0\\-sin(\lambda) \end{matrix}\right)=\left(\begin{matrix}\bar{x}\\\bar{y}\\\bar{z}\end{matrix}\right) \tag{5}$$
Solving for $x,y$ and $z$ via $(3)$ in the original coordinate system yields
$$P_2=(cos(\phi)cos(\lambda),sin(\phi)cos(\lambda),-sin(\lambda))\tag{6}$$
which is not the correct the answer and the problem seems to originate from the $z$ component which has an extra minus sign in front of it.
What conceptual errors are present in my working?
Comment: In  : ''so that the line $$ turns directly towards the positive z-axis'' I suppose it must be $OP_1$: correct?
Comment: @ Emilio Novati Yes, I will add this into my edits, thanks for pointing out.
Answer: The second rotation must be:
$$\left(\begin{matrix} cos(\lambda)&0&-sin(\lambda)\\0&1&0\\sin{(\lambda)}&0&cos(\lambda) \end{matrix}\right)
$$
because the angle $\lambda$ is from the $\bar x$ axis to the $\bar z$ axis
Comment: Doesn't the second rotation matrix $(5)$ (i.e. the conventional rotation matrix about y R(y)) already take into account that the y-axis points into the page when looking at the Z-X plane (i.e. a clockwise rotation about y)?


SEM warning message "WARNING: some estimated lv variances are negative" (Latent growth curve model)

Question: When running a quadratic latent growth curve model (model_6 below) I get the following warning message: "lavaan WARNING: some estimated lv variances are negative".
What does this mean, am I getting the warning because the quadratic model is not a good fit for the data?
For context: I am using latent growth curve models to model cognitive scores over 4 timepoints. I am in the process of deciding if a linear or quadratic fitted line is most appropriate.
I have included my linear (model_4) and quadratic (model_6) models below. The RMSEA for the linear model is 0.055, whereas the RMSEA for the quadratic model is 0.039.

model_4 = '
    # Intercept
    i =~ 1*Score.baseline + 1*Score.wave1 + 1*Score.wave2 + 1*Score.wave3

    # Slope
    s =~ 0*Score.baseline + 1*Score.wave1 + 2*Score.wave2 + 3*Score.wave3

    # Set the residual variances to all the same
    Score.baseline ~~ r*Score.baseline
    Score.wave1 ~~ r*Score.wave1
    Score.wave2 ~~ r*Score.wave2
    Score.wave3 ~~ r*Score.wave3
'

lgcm_model_4 <- growth(model_4, data=Data_wide, missing = "fiml")

model_6 <- '
    # Intercept
    i =~ 1*Score.baseline + 1*Score.wave1 + 1*Score.wave2 + 1*Score.wave3

    # Slope 1
    s1 =~ 0*Score.baseline + 1*Score.wave1 + 2*Score.wave2 + 3*Score.wave3

    # Slope 2
    s2 =~ 0*Score.baseline + 1*Score.wave1 + 4*Score.wave2 + 9*Score.wave3
'

lgcm_model_6 <- growth(model_6, data=Data_wide, missing = "fiml")

Below I've also included two plots. The first shows the mean score across the 4 timepoints (waves).

The second plot shows the fitted lines for the linear model (red) and the quadratic model (blue).
Comment: Were the variances estimated with the Cramer-Rao bound? If so, what is the condition number of your Fisher information matrix?
Comment: What optimization strategy did you use?
Comment: Why have you manually set some of the parameters? Example: `9 * Score.wave3`.
Answer: This warning means that your model is wrong.
The parameter estimates that are most consistent with the data require negative variances, which cannot exist.
Another way to think of it: There's not enough covariance between the measured variables to provide enough variance for three latent variables.
Comment: Thanks, Jeremy. To confirm, does this mean that the model has been set up correctly, but is wrong based on the data it is applied to?
Comment: Well, could be either. But assuming it was set up correctly, it doesn't match the data. There is not enough non-linearity to require s2.
Comment: Hi Jeremy, a follow-up question - the above warning does not occur when missing = "listwise", could you explain why this is? Thanks
Comment: Whether you get this warning from the specified model depends on the data that you analyze. When you specify 'missing = "listwise"' you're using different data. It could easily have gone the the other way - you get the warning with listwise, not with fiml. (And if you made me guess, I'd say it was more likely with listwise).


The Monotone Convergence Theorem for General Measure Spaces

Question: Let $(X, A,μ)$ be a complete measure space and let $(f_n(x))_{n=1}^{\infty}$ be a sequence of nonnegative measurable functions defined on a measurable set $E$ such that:
1) $0≤f_1(x)≤f_2(x)≤...≤f_n(x)≤...≤f(x)$ on $E$.
2) $(f_n(x))_{n=1}^{\infty}$ converges pointwise to $f(x)$ on $E$.
Then $\lim_\limits{n→∞}∫_{E}f_n(x)dμ=∫_{E}f(x)dμ$.

Proof from a website.) Since for each $n\in\mathbb{N}$, $0\leq f_n(x)≤f(x), ∫_{E}f_n(x)dμ\leq∫_{E}f(x)dμ$ and
  $\lim_\limits{n→∞}∫_{E}f_n(x)dμ\leq∫_{E}f(x)dμ$. We also note that $(∫_{E}f_n(x)dμ)_{n=1}^{\infty}$ is an increasing sequence of nonnegative real numbers that is bounded above, and hence converges, so $\lim_\limits{n→∞}∫_{E}f_n(x)dμ$ converges.
Question.) Can we always assume $∫_{E}f(x)dμ<\infty$? I think if
  $∫_{E}f(x)dμ=\infty$, $(∫_{E}f_n(x)dμ)_{n=1}^{\infty}$ may not be a
  bounded sequence.
Comment: You don't need to assume that $f\in L_1$.
Comment: Indeed, this proof seems to be covering only the case where $\int_E f\,d\mu < \infty$.  The MCT is still true when $\int_E f\,d\mu = \infty$, in which case it asserts that $\int_E f_n\,d\mu$ increases without bound, but that case would need to be proved separately.
Comment: The underlying idea is that if $A_n \uparrow A$ then $\mu A_n \to \mu A$.
Comment: I see. By the answer below that was deleted just now, if $∫_{E}f(x)dμ=\infty$, $\lim_\limits{n→∞}∫_{E}f_n(x)dμ=∫_{E}f(x)dμ=\infty$ by Fatou's Lemma. Thank you very much!
Answer: I suppose this is not really an answer to the specific question about what appears on that website; including a link to said site might have been a good idea. (Speaking of good ideas, using Fatou's lemma here may not be one, since FL is typically proved as a corollary to MCT...)
It is an answer to the related question "How do I prove  MCT?".  The standard proof is very simple, and works regardless of whether $\int f$ is finite. Simple enough that I should be able to reproduce it, having the idea in my head; let's see:
We may as well assume $E=X$. Suppose $\phi$ is a simple function with $0\le\phi\le f$. Say $$\phi=\sum_{j=1}^Na_j\chi_{E_j},$$where $a_j>0$ and the $E_j$ are disjoint.
Fix $\lambda\in(0,1)$. Let $$E_{j,n}=\{x\in E_j:f_n(x)>\lambda\phi(x)\}.$$Since $\lambda\phi(x)<f(x)$ for $x\in E_j$ we have $$E_j=\bigcup_nE_{j,n},$$so, since $E_{j,n}\subset E_{j,n+1}$ we have $$\lim_n\mu(E_{j,n})=\mu(E_j).$$But $\int f_n\ge\sum_j\lambda a_j\mu(E_{j,n})$, so $$\lim_n\int f_n\ge\lim_n\sum_j\lambda a_j\mu(E_j)=\lambda\int\phi.$$Hence $$\lim_n\int f_n\ge\sup_{\lambda\in(0,1)}\lambda\int\phi=\int\phi,$$so the definition of $\int f$ shows that $$\lim_n\int f_n\ge\sup_\phi\int\phi=\int f.$$


C++/GLFW - The right way to use Mutex objects?

Question: I'm working on a simulation that uses multithreading extensively. The thing is that, until now i've never used any mutex objects to protect my data. And the result, is that i'm getting bunch of segmentation faults..
I'm trying to lock/unlock with mutex while : reading/writing but that causes me another segfault :
#0 77D27DD2 ntdll!RtlEnumerateGenericTableLikeADirectory() (C:\Windows\system32\ntdll.dll:??)
#1 00000000 ??() (??:??)

Of course, I created a test project where I applied the lock/unlock thing for a basic situation and it worked, here is a basic example that shows how to deal with Mutex objects using GLFW :
#include <GL/glfw.h>
#include <iostream>
#include <vector>

using namespace std;

vector<int> table;
GLFWmutex th_mutex;
void GLFWCALL Thread_1(void* arg) {

    glfwLockMutex(th_mutex);
    table.pop_back();
    glfwUnlockMutex(th_mutex);
}

void GLFWCALL Thread_2(void* arg) {

    glfwLockMutex(th_mutex);
    table.erase(table.begin());
    glfwUnlockMutex(th_mutex);

}

int main()
{

    bool    running = true;
    GLFWthread th_1, th_2;

    glfwInit();

    if( !glfwOpenWindow( 512, 512, 0, 0, 0, 0, 0, 0, GLFW_WINDOW ) )
    {
        glfwTerminate();
        return 0;
    }

    glfwSetWindowTitle("GLFW Application");

    for(int i = 0;i < 10; i++) {
        table.push_back(i);
    }

    th_mutex = glfwCreateMutex();
    th_1 = glfwCreateThread(Thread_1, NULL);
    th_2 = glfwCreateThread(Thread_2, NULL);

    while(running)
    {

        // exit if ESC was pressed or window was closed
        running = !glfwGetKey(GLFW_KEY_ESC) && glfwGetWindowParam( GLFW_OPENED);
    }

    glfwTerminate();

    return 0;
}

The project, i'm working is bigger, i have 5 threads running on it, and a lot of vectors, maps, queues are accessed in the same time. Somewhere in the code, i tried to do something like :
void GLFWCALL CreateVehicleThread(void* arg) {

     int index = (*static_cast<PulseStateByEntrance*>(arg)).index;
     double t_initial = (*static_cast<PulseStateByEntrance*>(arg)).initial_time;
     double t_final = (*static_cast<PulseStateByEntrance*>(arg)).final_time;
     int pulse = (*static_cast<PulseStateByEntrance*>(arg)).pulse;
     int nb_entrance = (*static_cast<PulseStateByEntrance*>(arg)).nb_entrance;
     int min_time_creation = static_cast<int>(ceil(3600 / pulse));

     while((glfwGetTime() - (*static_cast<PulseStateByEntrance*>(arg)).initial_time)
     < ((*static_cast<PulseStateByEntrance*>(arg)).final_time - (*static_cast<PulseStateByEntrance*>(arg)).initial_time)) {

           double t_elapsed = glfwGetTime() - t_initial;

           if(t_elapsed > min_time_creation) {

                 **int nb_vehicle_per_cycle = static_cast<int>((t_elapsed * pulse)/3600);
                 glfwLockMutex(th_mutex);
                 VehicleManager::CreateVehicles(nb_vehicle_per_cycle, nb_entrance);
                 glfwUnlockMutex(th_mutex);**
                 t_initial = glfwGetTime();

           }

    }

}

The reason why, i'm putting my VehicleManager:CreateVehicles() method between lock/unlock is because in this method there is this line :
VehicleManager::vehicles_.push_back(vehicle);

So i wanted to protect the vector : vehicles_. But, as a result i got that segfault above. And even with :
glfwLockMutex(th_mutex);
VehicleManager::vechicles_.push_back(vehicle);
glfwUnlockMutex(th_mutex);

i got the same segfault.
I hope, i've made my self clear enough for you to understand the nature of my problem. I suppose, not all of you have worked with GLFW that's why i gave you the first basic example so you can understand how mutexes work with this library.
Thanks !
Answer: There is not enough information. But as a guess it looks like mutex was not created correctly (looks like a NULL reference). Find the point where you call  glfwCreateMutex() and make sure that a valid value is returned.
Not related to your problem so a side note:
don't do this:
glfwLockMutex(th_mutex);
<ACTION>
glfwUnlockMutex(th_mutex);

This is C style and as a result not exception safe.
You should set up a class so that the lock is called in the constructor and the unlock is called in the destructor. Then have a lock object of this class. Thus the lock and unlock happen normally as part of the object creation derstruction, thus in the presence of exceptions the lock will be correctly released.
The princeiple is RAII and their are a lot of articles on the subject here.
Example:
class MutexLocker
{
    public:
    MutexLocker(GLFWmutex& mutex)
        :m_mutex(mutex)
    {
        glfwLockMutex(m_mutex);
    }
    ~MutexLocker()
    {
        glfwUnlockMutex(m_mutex);
    }
    private:
        GLFWmutex& m_mutex;
};

void myAction()
{
    MutexLocker   lock(th_mutex);

    // Do stuff here:
}

Answer: You could wrap your containers which will make your code easier to understand:
template<typename T>
class MultithreadedVector
{
public:
    void pushback( T data )
    {
        glfwLockMutex(m_mutex);
        m_container.push_back( data );
        glfwUnlockMutex(m_mutex);
    }
//then similar for erase etc
private:
    std::vector<T> m_container;
    GLFWmutex m_mutex;
};

Comment: I find it elegant, will try it! Thanks !


D3 Map not showing up in browser on local server

Question: I'm working on a D3 map that shows the provinces of China. I've tried a mix of several different tutorials, but I have been unsuccessful in making the map appear in browser, which uses the python local server.
I can see that the information of the map has been correctly enter into the g element, and that the GeoJSON file does include 32 provinces. I must be doing something wrong displaying it then?
Please see here for my code: https://github.com/claiye/map/blob/master/index.html
It's quite messy because I've tried several different tutorials that don't work for what I am aiming for.
Please point out what stupid mistake I must be making. Your help is most kindly appreciated. Thanks in advance! :)
Comment: Can you check console log and paste the error here?
Comment: @srkushwaha There is no error in the console log at all. :(
Comment: And you mentioned you are using localserver. Are you referring to localhost i.e. 127.0.0.1 ?
Comment: @srkushwaha Yup! Using the Python local server thing... There is definitely no cross reference issue as far as I can see.
Answer: The issue was that the path created was not within the svg and g tag. Please check my two comments. I have verified below code is working.
<code><!DOCTYPE html>
<meta charset="utf-8">
<title>Map Testing</title>
<style>
    .province{
        fill:#ccc;
    }
</style>
<body>
<script type="text/javascript" src="d3/d3.v3.js"></script>
<script src="http://d3js.org/topojson.v1.min.js"></script>
<script type="text/javascript">

    var width = 960;
        height = 500;

    var svg = d3.select("body").append("svg").attr("width", width).attr("height",height);

    // Removed the slash before provinces.geojson
    d3.json("provinces.geojson", function(error, provinces) {
        if (error) return console.error(error);

        svg.append("g")
            .selectAll("path")
            .data(provinces.features)
            .enter()
            .append("path")
            .attr("class","province")
            .attr("d", d3.geo.path().projection(d3.geo.mercator().center([0,5]).scale(200).rotate([-180,0]))); // Added center and rotate here
});
</script>
</body>
<html
</code>
Comment: Thank you SO SO SO SO SO SO SO MUCH!!
Comment: Please mark it as "Answer", so that if somebody else faces same issue, he/she can use the solution.


How long should it take for my Floyd Rose to go back in tune? Also, does the bridge need to be 100% parallel?

Question: I just started using my new Charvel with a FR 1000 Series; love it! The tuning is epic, until I do a dive; immediately after, my Korg CA-40 says its out of tune. A few mins later, doing nothing, it's back in tune again. What's going on here and is this normal?
Is this normal? Also, it looks like my bridge is at about 1-3 degrees vs the body; as in parallel being 0. Is this OK?
Comment: If you wait about 20 seconds after you do a dive, is the instrument back in tune again? If not, is it more in tune than just after the dive?
Answer: A properly set up Floyd Rose type bridge should almost immediately return to in-tune. With a standard set up the bridge is usually parallel or nearly parallel to the body.  It sounds like you need to have a set up done on the bridge to get it aligned correctly, and to check that there isn't anything mechanically wrong with the unit.


Epi, mono but not an isomorphism

Question: In category theorie there exists the notion of mono, epi and iso.
In the category Ab of abelian groups we have 'mono $\Leftrightarrow$ injective' and 'epi $\Leftrightarrow$ surjective'.
We have the full subcategory of Ab of divisible group ie. an abelian group $A$ such that for any $a\in A$ and $n\in\mathbb{Z}_{\ge 0}$ there is a $b\in A$ with $nb=a.$
Of course $\mathbb{Q}$ and $\mathbb{Q}/\mathbb{Z}$ are divisible. So we have the morphism (canonical projection) $$p:\mathbb{Q}\rightarrow\mathbb{Q}/\mathbb{Z}$$ in the category of divisible groups.
The claim is that this is mono, epi but not an isomorphism (in the category of divisible groups).

mono. Let $D$ be a divisible group and $g,g':D\rightarrow\mathbb{Q}$ morphisms such that $p\circ g=p\circ g'.$ We need to get $g=g'$. We have $0=p(g(d))-p(g'(d))=p(g(d)-g'(d))\Rightarrow g(d)-g'(d)\in\mathbb{Z}$, so $g(d)-g'(d)=n$ for some $n$. How can we conclude $g(d)-g'(d)=0$? For $|n|\ge 0$ I find an $d'\in D$ with $|n|d'=d$. That is $|n|g(d')-|n|g'(d')=n.$
epi. Again $D$ a divisible group and $g,g':\mathbb{Q}/\mathbb{Z}\rightarrow D$ morphisms such that $g\circ p=g'\circ p.$ Let $p(q)=[q]\in\mathbb{Q}/\mathbb{Z}$. We have $g([q])=g(p(q))=g'(p(q))=g'([q])$, so $g=g'$.
not isom. Assume there is an inverse morphism $f:\mathbb{Q}/\mathbb{Z}\rightarrow\mathbb{Q}$ of $p$. What is then the problem?
Comment: But if you read the definition of being a monomorphism, then you should note that it has something about "for all..." and part of that "all" involves objects (seeing as it is a "for all morphisms" and these come with a domain and codomain which need not be divisible).
Comment: For part $3$, it's easy: $\mathbb{Q}/\mathbb{Z}$ has torsion elements, whereas $\mathbb{Q}$ doesn't.
Comment: Why do you think it being a full subcategory implies that it retains those properties?
Comment: Well I guessed that this would be the problem. My thought was: Let $f$ be a morphism in divisible groups. Then $f$ is a morphism in Ab thus 'mono $\Leftrightarrow$ injective'.
Comment: Thanks, I added some ideas in the question. Maybe you have a hint?
Comment: For part $2$, you should note that surjective always implies epi (this is a good exercise). And being an iso is indeed preserved and reflected when going to a full subcategory (again, a good exercise). So it is mainly that you need to somehow use that the only possible domains for the morphisms in the first part are divisible in order to show that the map is mono.
Comment: I added some ideas to 1. I can't conclude the claim. For iso: If there were an inverse map $f$ in the category of divisible groups then this is a map in Ab. $p$ is also a map in Ab. So $p$ is invertible in Ab that means that $p$ is mono $\Leftrightarrow$ injective. But the kernel is not trivial.
Comment: Why did you jump from talking about the existence of an inverse to something about mono and injective?
Comment: If $f:A\rightarrow B$ has an inverse $g:B\rightarrow A$, then $f$ is mono: for functions $h,h':U\rightarrow A$ with $f\circ h= f\circ h'$ we have $g\circ f\circ h=g\circ f\circ h'\Rightarrow id\circ h=id\circ h'\Rightarrow h=h'$.
Comment: @Andrei.B So where is the problem?
Comment: They can't be isomorphic. Let's say $x=\dfrac{1}{2} \ mod\ \mathbb Z\neq 0$ and you have $f$ your isomorphism. So you have $2f(x)=f(x)+f(x)=f(x+x)=f(1)=0$ but in $\mathbb Q$ if $2f(x)=0$ it implies $f(x)=0$ so it can't be injective. A divisible group ismorphism is an abelian group isomorphism, so it should be injective, but it is not.
Comment: Thanks! So indeed only #1 is left. You have an idea? I also feel not very confortable with: Why is a mono of divisible groups not injective since is holds for Ab? I thought I got it but no...
Answer: So here's my proof for $p$ being a mono:
So assume you have $f, g$ such that $p\circ f=p\circ g$ where $D$ is their domain, a divisible group. So for every $x\in D$ you have $f(x)-g(x)\in \mathbb{Z}$.
Now take $x\in D$ and suppose $n=f(x)-g(x)\neq 0$. Now take $p$ a prime which doesn't divide $n$ and $y\in D$ such that $py=x$. You get:
$$n=p(f(y)-g(y))$$
since $f(y)-g(y)\in \mathbb Z$ it would imply that $p$ divides $n$ which is a contradiction.
Comment: Super! Where du you need $n>0$?
Comment: Well, my defintion of divisible group is with $n>0$, but I don't think it's that important.
Comment: Yes, but you use this definition for $p$, not for $n$. And $p$ is always $>0$ as it is a prime.
Comment: Well, seems I'm doing mistake severywhere today. I edited it out. Indeed you don't need it.
Comment: Haha, not it is perfect. Maybe you have an answer to the 'Why is a mono of divisible groups not injective since is holds for Ab?' question?
Comment: I don't quite understand the question. If you consider $Id:\mathbb{Q}\rightarrow\mathbb{Q}$, it is an injective morphism of divisible groups, but injective implies mono, no?
Comment: But your map Id is mono isn't it?
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/48405/discussion-between-andrei-b-and-user114179).

Epi, mono but not an isomorphism


Breaking on the code in the last executed method

Question: I have an ASP.NET web app which is small yet has a fair amount of C# behind it.
I am trying to run some code, which is dependent on a class library/.dll I have produced (containing business logic). When I debug, after I bind to datasource property, I get an object reference not set to an instance object.
I know how to fix these errors as I have done more than my fair show when I lacked experience, but the trouble I have is I cannot find the last method to execute (which will in turn help me find the variable at fault) until this exception. Is there a way I can make the code break when it reaches the line of code causing this exception (or the line of code matching the last method called in the stacktrace)? I will probably do a find for that method signature but I don't really like this approach. Is this something for windbg?
I guess this is what they mean by unmaintainable code.
Answer: Look at the stack trace that is most likely printed out with the error.
Also try breaking on exceptions - Debug Menu -> Exceptions, Choose CLR Exceptions
Comment: Ah yes, this was the option I was after. I read about this a few weeks ago too. I want the code to break and go back into VS and with the popup in the .cs file to blame.
Comment: I'm glad that's what you were looking for :) Thanks for the accept - not enough people seem willing to do that!
Answer: VS should highlight the line from which the exception was thrown. If it doesn't, you can enable it in Debug > Exceptions. If you put a breakpoint on or before this line (or if it doesn't give you a line, on or before the code you suspect of throwing it), and then "Step In" repeatedly, you will eventually reach the code where the exception is thrown.
Comment: I forgot to write, after the line where I bind to the datasource, the exception occurs but there is no other line of code executed (well not hit while stepping through).


Solve $P(X_1 = k |X_1 + X_2 = n)$ poisson distribution

Question: Find distribution of $X_1$ by solving $P(X_1 = k |X_1 + X_2 = n)$ where $X_1, X_2$ are independent Poisson variables with parameters $\lambda_1, \lambda_2$ and given $X_1 + X_2 = n$
Solution:
$$P(X_1 = k |X_1 + X_2 = n) = \frac{P(X_1 = k, X_1 + X_2 = n)}{P(X_1 + X_2 = n )}$$
$$= \frac{P(X_1 = k)P(X_2 = n - k)}{P(X_1 + X_2 = n)}$$
$$= \frac{\frac{\lambda_1^ke^{-\lambda_1}}{k!}\frac{\lambda_2^ke^{-\lambda_2}}{(n-k)!}}{e^{-(\lambda_1+\lambda_2)}(\lambda_1 + \lambda_2)^n/n!}$$
$$=\frac{n!}{k!(n-k!)}\left(\frac{\lambda_1}{\lambda_1+\lambda_2} \right)^k\left(\frac{\lambda_2}{\lambda_1 + \lambda_2} \right)^{n-k}$$
This is binomial theorem.

I don't understand the last step.
This part
$$\left(\frac{\lambda_1}{\lambda_1+\lambda_2} \right)^k\left(\frac{\lambda_2}{\lambda_1 + \lambda_2} \right)^{n-k}$$
What I get while trying this was
$$\left(\frac{\lambda_1^k}{(\lambda_1+\lambda_2)^n} \right)\left(\frac{\lambda_2^{n-k}}{(\lambda_1 + \lambda_2)^n} \right)$$
Which is what it equals to I'm not sure how the $n$ was replaced with $k$ and $(n-k)$.
Also on the second step
$$\frac{P(X_1 = k, X_1 + X_2 = n)}{P(X_1 + X_2 = n )} = \frac{P(X_1 = k)P(X_2 = n - k)}{P(X_1 + X_2 = n)}$$
Couldn't they cancell the denominator in the same way ? What property lets them split the AND part of P like $P(A, B) = P(A)P(B)$
Answer: $(X_1=k,X_1+X_2=n)=(X_1=k, X_2=n-k)$ and the events $(X_1=k),( X_2=n-k)$ are independent. His justifies the second step.
In line three you have mis-typed $\lambda_2^{k}$ for $\lambda_2^{n-k}$.
In the denominator they have split $(\lambda_1+\lambda_2)^{n}$ as $ (\lambda_1+\lambda_2)^{k}(\lambda_1+\lambda_2)^{n-k}$.


Is it possible to set an Object to be null from within itself?

Question: I know that this = null is illegal.
I'm wondering if there's some other way to have an object clean itself up.
my desire is to be able to do something like this:
A a = new A();

a.doStuffAndDisappear();

if(a == null){
     //this is true after my doStuffAndDisappear() method.
}

I suspect there's no way to make this happen, but thought it would be worth asking.
Comment: @Dr.Dredel You are using "it" to refer to two very different things, an object and a specific reference to the object. In order to make the object available for GC you would need to change every reference to it that exists to null, not just the reference that was used in a specific call.
Comment: `this`, to the extent that is should be regarded as a reference, is merely one of the references. Even if you could stop an object from referring to itself, if any active thread has access to any reference that points to the object, it remains reachable and unavailable for GC.
Comment: The answer is "no," but it's a good question regardless.
Comment: @MarcinOrlowski: There are objects which, having done X, are no longer useful for anything.
Comment: @MarcinOrlowski, It's a little arrogant of you to declare this is "bad code" since there is no "code" just an idea!  You might argue that such an approach might be entirely useless... I'd disagree.  I have a self contained Widget that would be improved considerably if it could just make itself null after doing what it needs to do. Thus letting the GC clean it up and not leaving the Widget's user to have to set it to null manually.  Feels more OO to me, but as I said, we can differ on this.
Comment: @PatriciaShanahan, that's PRECISELY my point! I want ALL references to this object to be null(able) in one place from within the object itself. And you're mistaken, `this` is very much a reference to the instance (assuming it's not static). You can have 9 instances and each one's `this` will point to those specific instances.  So, `this = null` makes perfect sense vis-a-vis memory allocation. It's just that the language doesn't allow for it.
Comment: Nope, not that I know of.
Answer: No, because a is a reference (not an object as in this question's title) and no method can modify the value of a reference except the method in which it is defined (I assume from the code context that a is a local variable).
Since Java doesn't have pass-by-reference, what you ask cannot be done: there's no way to collect addresses-of references in order to manage the addresses pointed to. You might use a wrapper object, but not sure what'd be the point.
Answer: As everyone else has said, this simply isn't possible. If it's cleaning up resources you're after, then you might consider using a pattern such as:
class A {

    private boolean cleanedUp;

    public void cleanUp() {
        // clean up any resources
        cleanedUp = true;
    }

    public boolean isCleanedUp() {
        return cleanedUp;
    }
}

And then using it like so:
A a = new A();
a.cleanUp();
if (a.isCleanedUp()) {
    ...
}

A better solution might be to implement the java.io.Closeable or java.lang.AutoCloseable interfaces depending on your circumstance:
class B implements AutoCloseable {

    private boolean closed;

    public boolean isClosed() {
        return closed;
    }

    @Override public void close() throws Exception {
        // clean up any resources
        closed = true;
    }
}

In which case you can use a try-with-resources statement:
try (B b = new B()) {
    // do stuff
} catch (Exception ex) {
    // oh crap...
}

Or you could even combine the two and do it that way, whichever you prefer.
Or lastly you could do it the way William Morrison explained (though I'd probably cheat and just use java.util.concurrent.atomic.AtomicReference instead of making my own class, and it comes with the added benefit of being a generified type), which, depending on your circumstance, may really be unnecessary. After all, you could always just do (even though it might seem a little odd):
A a = new A();

a.doStuffAndDisappear();
a = null;

if(a == null){
     //...
}

Answer: I might be missing something but, since you mention that:

I'm wondering if there's some other way to have an object clean itself
  up.

And:

I have a self contained Widget that would be improved considerably if
  it could just make itself null after doing what it needs to do. Thus
  letting the GC clean it up and not leaving the Widget's user to have
  to set it to null manually.

How about, not keeping a reference to the object at all?
new A().doStuffAndDisappear();
// no reference, instance of A is eligible to GC

Update
Since this is not what the OP is looking for, let me expand @Perce solution:
interface AHolder
{
    void setA(A a);
}

class AParent implements AHolder {

    private A a;

    public AParent() {
        a = new A();
    }

    public void doSomething() {
        a.doStuffAndDisappear(this);
        if(a == null)
        {
            System.out.println("It is true!");
        }
    }

    public void setA(A a) {
        this.a = a;
    }
}

class A
{
    void doStuffAndDisappear(AHolder parent) {
        parent.setA(null);
    }
}

Now you don't need to know the type of the parent or the field that holds A.
Working Example.

If you want to make A null its reference at every parent, just change A to hold a list of parents (List<AParent> parents), and implement a method to track parents:
void addParent(AParent parent)
{
    parents.add(parent);
}

Plus a void cleanUp() which iterate over its parents setting null:
void cleanUp()
{
    for (AParent parent : parents)
    {
        parent.setA(null);
    }
    parents.clear();
}

Notice how this solution looks a lot like JavaBeans Bound Properties... This is not by coincidence; we are, in a way, creating a simple Event / Listener architecture to that A can notify its parents to get ride of their reference to it.
Comment: ha. Not applicable in my case, but very true in other cases.
Answer: Yes, it is possible if you reimplement GC in your applications. My answer is inspired by your discussion with Patricia, where you said you want to have all references to that object set to null. GC example:
class MyGC {
   byte[100000] myMemory;
   int nextFreeCell;
   myNew (int value) { }
   get (int myCell) { }
}

This way you can control that there are no other refernces to your class. Your class must also contain the refernces to your GC memory only. Your example:
int cell = MyGC.new(A.class)

MyGC.get(cell).doSomething();

if (MyGC.get(cell) == null)
   --- true -----

Answer: This neat question is technically interesting. However, considering your intent: You are attempting to force the condition of all references being null so that you can guard against the invalid use of an otherwise expired instance.
It is bad practice to assign any meaning to null.
Instead, modify (or facade if you can't modify) your A object so that some other flag is available. For example public boolean isClosed() ...
Answer: That is not possible, I would think. If a is an instance variable of some object x, doStuffAndDisappear somehow could get a reference to x and call a setter to set a to null. Better not to go that route as it is totally counter intuitive.
Best would be to clean up in doStuffAndDisappear (well, cant make is disappear) and make sure that no one else is referring is to a. GC should take care of rest.
Answer: You can't have an object set another object's reference to null like this without having them both aware of one another. Doing what you want is impossible without some legwork. I advise against the following example.
public class A{
    A other;
    public A(A a){
        this.other = a;
        if(a!=null)
            a.other = this;
    }
    public void doSomethingAndDisappear(){
        a.other = null;
    }
}

This will cause one value's reference to a second reference to vanish as a second reference is setting the first reference's reference to null.


Solving $\ln(\frac{ 2x}{ x-1}) > 0$

Question: I'm trying to solve this inequation: $\ln\left(\dfrac{ 2x}{ x-1}\right) > 0$. The problem is, $2$ different ways that seem valid to me, give me different answers.
First option:
turn $0$ to $\ln(1)$, so we have $\ln\left(\dfrac{ 2x}{x-1}\right) > \ln(1) \to \dfrac{2x}{x-1} > 1$ and multiply both sides by $(x-1)^2$ gives me $x > 1$ or $x < -1$.
Second option:
$\ln\left(\dfrac{ 2x}{x-1}\right)$ is actually $\ln(2x) - \ln(x-1)$, so $\ln(2x) - \ln(x-1) > 0 \Rightarrow \ln(2x) > \ln(x-1)$ so $2x > x-1$, or  \Rightarrow x > -1$.
I'm guessing the second option is the invalid one, but why?
Thanks!
Comment: Look at a [picture](https://www.desmos.com/calculator/8ponnfksaq)
Comment: @AlexanderGeldhof I think the function is defined for values in $[-1, 0)$.
Comment: @user170231 because $(x-1)^2$ is always positive and doesn't mess up the inequality
Comment: In the first method: why multiply by $(x-1)^2$, and not just $x-1$?
Comment: Solution obtained by software is: $1<x<\frac{e}{e-2}$ - Chart: https://www.desmos.com/calculator/9uwkfzkqli
Answer: The first method is correct and the second one is wrong.
At first note that we require
$$\frac{2x}{x-1}>0 \iff x<0 \quad \land \quad x>1$$
then we obtain
$$\log\left(\frac{2x}{x-1}\right)>\log 1\iff \frac{2x}{x-1}>1 \iff \frac{2x}{x-1}-1>0\iff  \frac{x+1}{x-1}>0$$
that is
$$x\in(-\infty, -1)\cup(1,\infty)$$
which is the solution.
The second method leads to a inequality which is not equivalent since
$$\log(2x)-\log(x-1)>0$$
requires that
$$x>0\quad \land \quad x-1>0 \iff x>1$$
The reason for the second method to fail is that
$$\log \frac A B= \log A-\log B$$
only holds when $A$ and $B$ are both positive.
To obtain a correct solution, we can also use the second method considering all the cases as follows

for $x<0$

$$\log\left(\frac{2x}{x-1}\right)>0 \iff \log(-2x)-\log(1-x)>0$$

for $0<x<1$

$$\log\left(\frac{2x}{x-1}\right)>0 \iff \log(2x)-\log(1-x)>0$$

for $x>1$

$$\log\left(\frac{2x}{x-1}\right)>0 \iff \log(2x)-\log(x-1)>0$$
which is a less effective way to proceed.
Comment: @Stars I've added some more detail to explain why the second method leads to a different inequality. In general observe that $\log \frac A B= \log A-\log B$ only holds when $A$ and $B$ are both positive. That's the origin of the issue with the second method.
Comment: @NoChance You are welcome! Bye
Comment: I am not sure it is clear how you reached the conclusion in the last line from the one before. Thanks.
Comment: just consider the sign for numerator and denominator
Comment: That's for the existence of log expression.
Comment: Thank you for your answer, I need to spend sometime to understand this one.
Comment: Thanks for your answer. I too don't see how the last line is a conclusion of the line before it. Nevertheless, we agree that the two options are not equivalent and give different answers. I'm wondering how could that be, since all the actions were legit and according to logarithms rules. I think the real question here is how could it be that for y=ln(2x/x-1), x=-10 (for example) is valid, but for y=ln(2x)-ln(x-1), which supposed to be the same according to logarithms rules, x=-10 is invalid.
Comment: For the ratio $\frac{x+1}{x-1}$ we have that the numerator is positive for $x>1$ and negative for $x<1$ while the denominator  is positive for $x>-1$ and negative for $x<-1$ therefore the ratio is positive for $x<-1$ or $x>1$.
Comment: @user Thanks for the detailed response!
Comment: Thanks for the detail.
Comment: @Stars You are welcome! Bye

Solving $\ln(\frac{ 2x}{ x-1}) > 0$


Find element in xml-tree

Question: I want to find in a XML file only the tree with for example code = "7041".
Here is a part of the XML file:
<lens>
    7041
    <names>
        <name language="en">
            <long>synchrony SV Curves HDC 1.5 PH Brn</long>
        </name>

</lens>

Here is my code:

   for elem in tree.findall('lenses/lens/code/[@text="7041"]'):
        print (elem.tag, elem.text)

This code does not work, I do not find "7041". What is wrong?
How can I select only the part in the file were code="7041"?
Answer: @ is for attributes; for a text node test, use text(),
//lens/code/[@text()="7041"]
             ^

and also remove the spurious / ahead of the predicate:
//lens/code/[text()="7041"]
           ^

to get this XPath expression,
//lens/code[text()="7041"]

will select all of the code element children of lens elements, provided the code element has a text() text node child with a string value of "7041".
You could also test the string value of code,
//lens/code[.="7041"]

If you actually want to select lens elements, elevate the predicate:
//lens[code="7041"]

See also

Testing text() nodes vs string values in XPath

Thanks to Mads Hansen for correcting a glaring mistake in a previous version of this answer.

Find element in xml-tree


JavaScript - Pontuação

Question: Sou iniciante.
Como fazer os pontos(placar) fique na posição verde e na mesma tela.
estou com problemas de na hora atualizar os pontos ele mostra na tela seguinte.
Exite algo a se fazer, estou usando o document.write('texto');

<canvas width="1200" height="800"></canvas>

Answer: Use innerHTML ao invés de document.write, que no caso, reescreve todo o documento, por isto some.
Assim:
document.getElementById('pontos').innerHTML = 'Pontos: ' + pontos;

Quanto a ficar no lado verde, precisaria mudar o CSS e o HTML.

<canvas width="1200" height="800"></canvas>

Answer: Basta você utilizar as propriedades e método abaixo:

fillStyle para definir a cor do texto (Caso contrário o texto ficará verde;
font para definir o tamanho, tipo e estilo da fonte (opcional); e
fillText para escrever algo na tela. Neste método você pode controlar a posição X e Y do elemento.

Exemplo:
pincel.fillStyle = "blue"
pincel.font = "bold 16px Arial";
pincel.fillText(`Pontuação: ${pontos}`, 1000, 700)

Exemplo Completo:

<canvas width="1200" height="800"></canvas>

Caso você queira adicionar um texto abaixo do canvas — abaixo do elemento verde —, você poderá utilizar a propriedade textContent de um elemento HTML (div, p, span etc) e um pouco de CSS, por exemplo:
document.querySelector("#pontuacao")
        .textContent = `Pontuação: ${pontos}`;

Exemplo:

#pontuacao {
  text-align:right;
  width: 1100px;
}
<canvas width="1200" height="800"></canvas>

Pontuação: 0

JavaScript - Pontuação


local variable 'subprocess' referenced before assignment

Question: Here is it my code, I'm trying to perform command in commandline and get output, but I got error. Please help me
import telebot
import subprocess

token = ''
bot = telebot.TeleBot(token)

@bot.message_handler(commands=['echo'])
def changeWall(message, res=True):
    subprocess = subprocess.Popen("echo Hello World", shell=True, stdout=subprocess.PIPE)
    subprocess_return = subprocess.stdout.read()
    print(subprocess_return)
    bot.reply_to(message, subprocess_return)

Error:
local variable 'subprocess' referenced before assignment

Comment: Might be related to your variable name, you have override the reference to the `subprocess` module. Try renaming your variable (first line in your function). Also, please include the full traceback of your exception, we can't know which line caused the error
Comment: change the variable `subprocess` to any other name.
Answer: You need to change the name of the subprocess variable.
You can read more here: Python: function and variable with the same name
Also I recommend that you remove the token from the code.
Comment: Thanks bro, I forgot about token ahahah


Can my lack of piano practice affect my creativity in song composing & arranging?

Question: I would like to firstly apologize for this lengthy post. I just want to give a background to my question.
I am not, by any means, a professional pianist. I do not have a Music Degree to boast of, all I have is 8 years of piano lessons under my belt when I was younger. Currently, I am a musician at our church and a fledgling songwriter & arranger. I'm taking online lessons for it, and I have to say, I find a lot of things very hard to understand but oh so worth the time and effort to learn.
I've been a pianist/ accompanist in my church for 16 years now ( I started when I was 14 years old). Around 5 years ago, my pastor told me to try my hand at creating orchestral arrangements for choir songs. I still do up to this day, hence the need for lessons.
I've just noticed that I've been having a hard time being creative in composing & arranging, ever since my Music Director told me not to accompany our singers and/or the congregation anymore during church service. Even during choir and orchestra rehearsals, I am not allowed to accompany them anymore. The reason she said was, "... so you can focus more on arranging, and not be tired from rehearsals."
I do not have a piano or keyboard at home anymore, since it was donated. So, the only place I could practice or play piano was at my church. But ever since she "banned" me from playing, even for practice or just a simple personal jamming session, I have not had the opportunity to actually play the piano for several months now.
And now, I've been constantly suffering from creativity block. Arranging songs used to be exciting, I always looked forward to applying the new things I learned. But now I feel frustrated and pressured because I have to release arrangements weekly for the choir. And I've just felt more burnt-out then before when I still used to play for the choir/ congregation. Sure, it was tiring but I always felt happy and inspired after.
So does my lack of piano playing have anything to do with my creativity block? I've tried asking this to other musicians I know, but they just said to heed what my Music Director says. Or maybe I've just been asking the wrong people..
I hope someone can shed light on this and provide both subjective and objective answers. Thank you so much and God bless us all!
Comment: I have a strong feeling that Interpersonal is a better place for this question: https://interpersonal.stackexchange.com So, you feel pressure, the joy and inspiration from creativity has gone, other people are telling you what you must do, how to do it, and that you can't have an instrument at home etc.? I'm sure everyone has had good intentions though. Based on your short text I'd recommend you to find a way to make at least some music that _you_ enjoy without having to think about making other people happy.
Comment: Reading between the lines: wonder what the real reason was the MD stopped you playing. Has someone else taken your place, or do they sing acapella? Not playing is affecting you adversely, so I'd be inclined to speak with MD saying it's both or neither. Maybe he's trying to discourage you altogether, I don't know, but if so, you'll have the answer. All or nothing!
Comment: "...I do not have a piano or keyboard at home anymore, since it was donated...." the wording of that comment is kind of unclear. Who donated? Donated to who? The crux of your problem is the piano is gone. If you owned it, why would you give it away? Of course that will present a serious problem for a pianist.
Comment: I suppose this may be closed so I'll write a comment. 1-Can you explain to the director that you need to use the keyboard for composing, arranging, exploring musical ideas and getting inspired? 2-Also, I suggest you buy a melodica (don't tell your boss). 3-Is there some other instrument you're interested in playing in addition to keyboard? This might open up new facets of your creativity, and give you an outlet for piano unavailability frustrations. 4-Look for a piano to play elsewhere (public school after 3 pm, local college, some other church, community center, nursing home, music store).
Comment: 5-Consider joining a community concert band as percussionist and/or pianist.  Bass drum, crash cymbal, chimes, celeste, for example, will be easy for you to get started with. 6-Consider using existing arrangements sometimes, to ease up the pressure on yourself to crank out the arrangements. // Question.  Your church has an actual orchestra?
Comment: @MichaelCurtis - I think the decision to donate the piano may have been made by someone else, other than OP.  Unfortunately not everyone gets to be involved in making decisions in some families.
Comment: Maybe you need to centre your life a little less on this church?
Answer: First, the most important thing to be a good arranger is to listen. Listen to orchestral arrangements of songs that you know. For example, you can check out this Christmas concert here. Listen particularly to the counterplay between the strings and the vocals. The choir is always singing basically whatever is in the hymnal while the orchestra gives extra support and leads the congregation into the next verse/chorus. Also in between whole notes the choir may be singing, the orchestra plays some sort of melodic line that helps the transition.
So what I would suggest in your situation to boost your creativity in arranging is to start with a basic form. You can have the choir sing whatever is in the hymnal and have the orchestra support the choir. Then you can start adding transitional phrases in the orchestra and maybe have an orchestral intro. Then you can start experimenting with other ideas such as a cappella, vocal interplay (bass/alto sing a couple of notes, then tenor/soprano echo that), have certain voices have solos, interesting reharmonizations, key changes, orchestral melody with the choir singing harmony, and much more. Really the only thing that can limit what you can do is not trying ideas out.
That is why I HIGHLY recommend you buy a piano. Whether it just be a keyboard or a grand piano. Buy a piano. This can help you figure out how you might voice phrases or orchestral parts.
Hope that helps


Which is better: Independent sample t-test or another method?

Question: One hundred people were recruited in two sessions and randomly assigned to one of two groups. Some information about the design and analysis:

In Session 1, participants were given gum to chew whilst doing a series of tasks to complete.

In Session 2, participants were not given gum to chew and did the same tasks in the same order as the first session.

A series of independent sample t tests were carried out, one for each task, and were then compared across the two sessions.

My question is this: Is an independent sample t-test correct in this scenario as a testing method? Or should it be a multiple paired sample t test, whereby the test is done within subjects?
Answer: For the experiment described in the first paragraph, a two-sample t-test is indeed appropriate, as the participants are independent. For the crossover experiment you describe next, the paired t-test is indeed most appropriate. Both setups and analysis methods are correct and will give you unbiased estimation of the effect of gum.
Yet the crossover setup has the advantage of conditioning on the participant, eliminating variability between participants and thus giving you better power and more precise estimation. Yet it hinges on the assumption that there is no effect of having chewed gum in the first session on the concentration on the second session, where the participants do not get to chew gum.
Comment: so would you suggest that doing a multiple paired sample t test might be a better option for this experiment?
Comment: The test you do should correspond to the design. And it seems like the paired design is indeed the best choice here.


Consulta XML python não retona

Question: Quero fazer uma consulta que me retorna o valor ['1961'], no caso na "CONSULTA 2".
Como o arquivo possui várias linhas, eu especifiquei um pedaço do arquivo XML.
Uso essa mesma consulta "CONSULTA 2" em outros arquivos que funciona perfeitamente, mas nesse arquivo a consulta retorna erro.
O "CONSULTA 1" funciona perfeitamente mas não serve pois retorna todos os valores, especifiquei somente para mostrar que ele retorna os valores
Quero saber onde que está o erro.
Trecho do XML:
<?xml version="1.0"?>
<Documento xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Documentos />
  <CompanhiaAberta>
    <NumeroSequencial>1961</NumeroSequencial>

# CONSULTA 1
NumeroSequencial1 = []
for infos in root.iter('NumeroSequencial'):
    NumeroSequencial1.append(infos.text)
print(NumeroSequencial1)
['1961']

# CONSULTA 2
NumeroSequencial2 = []
for infoss in root:
    NumeroSequencial2.append(infoss.find('CompanhiaAberta/NumeroSequencial').text)
print(NumeroSequencial2)

Erro:
AttributeError                            Traceback (most recent call last)
<ipython-input-86-55318317991e> in <module>
      6 NumeroSequencial2 = []
      7 for infoss in root:
----> 8     NumeroSequencial2.append(infoss.find('CompanhiaAberta/NumeroSequencial').text)
      9 print(NumeroSequencial2)

AttributeError: 'NoneType' object has no attribute 'text'

Solução
Utilizei o Element Objects: .iterfind('path').
Segundo documentação do xml.etree.ElementTree: Encontra todos os subelementos correspondentes, por nome de tag ou caminho. Retorna um iterável que produz todos os elementos correspondentes na ordem do documento.
# CONSULTA 2
NumeroSequencial2 = []
for infoss in root.iterfind('CompanhiaAberta/NumeroSequencial'):
    NumeroSequencial2.append(infoss.text)
print(NumeroSequencial2)

Comment: Lucas, reescrevi a pergunta, espero que seja compreendida, obrigado. o find ele deveria retorna o valor 1961, através da sequencia de tag, Esse mesmo tipo de consulta eu uso em outros arquivos e funciona, mas nesse caso, não entendo o motivo de não funcionar
Comment: @Saulo Como você conseguiu resolver o problema, o ideal é colocar a solução numa resposta, não editar a pergunta com a solução
Comment: Não está claro o que você está querendo dizer. Recomendo reescrever o início da pergunta usando o ponto final para separar as setenças. Está bem confuso. De todo modo, para sair desse erro, você precisa entender pq `infoss.find('CompanhiaAberta/NumeroSequencial')` está retornando um objeto vazio. O que vc esperava que esse comando retornasse?
Comment: Saulo, aplicando regex como em uma das respostas da pergunta que linko abaixo vc obtém `['1961']`. Apenas mude o regex para `xml=re.findall(r'[0-9]+\.?[0-9]+?',xml)`. Se quiser uma resposta usando o módulo `xml.etree.ElementTree` (como parece ser o caso do seu código), favor postar o XML completo e o código com as importações. Link para a pergunta: https://pt.stackoverflow.com/questions/485705/retirar-linha-de-arquivo-xml-usando-python-e-criar-arquivo-txt-com-resultado?noredirect=1&lq=1
Comment: Obrigado Lucas pela dicas
Answer: Erro:
AttributeError                            Traceback (most recent call last)
<ipython-input-86-55318317991e> in <module>
      6 NumeroSequencial2 = []
      7 for infoss in root:
----> 8     NumeroSequencial2.append(infoss.find('CompanhiaAberta/NumeroSequencial').text)
      9 print(NumeroSequencial2)

AttributeError: 'NoneType' object has no attribute 'text'

Solução
Utilizei o Element Objects: .iterfind('path'). Segundo documentação do xml.etree.ElementTree: Encontra todos os subelementos correspondentes, por nome de tag ou caminho. Retorna um iterável que produz todos os elementos correspondentes na ordem do documento.
# CONSULTA 2
NumeroSequencial2 = []
for infoss in root.iterfind('CompanhiaAberta/NumeroSequencial'):
    NumeroSequencial2.append(infoss.text)
print(NumeroSequencial2)

Consulta XML python não retona


Deciding to make a C# class static

Question: If I have a Utilities.cs class in C#, which contains only static methods
e.g.
public static string DoSomething()
{
    return "something";
}

Should I make the class itself static?
public static Utilities()
{
    ...

Does making the class static have any advantages?
Answer: Yes you should. It stops people from instantiating the class when they shouldn't, and makes the purpose of the class clearer. Have a read of the MSDN page for more information.
You also need to mark the class as static if you want to add Extension Methods
You should think carefully about utility classes. Think whether the methods truly belong there, or if there's a more OO way of doing it.
Also look at this question and the answer by Jon Skeet.
Comment: Thanks, the extension methods wasn't something I'd considered
Answer: The main advantage is that it makes your design intent clearer, and enforces those intents. For instance you cannot inherit from a static class (i.e. specialize it), and you cannot make an instance of it (it is in effect a singleton). These would both be design intents of your utilities class.
However, static classes and methods should be used with caution, as it makes it difficult to vary behaviour of your program. Static classes and methods are very concrete and cannot be (easily) substituted, as would be the case if you used interfaces and constructor injection. Static classes and members can however be useful, but rarely. Overuse of statics make your software less flexible, and more difficult to test.
Comment: Yes the Utilities class sounds like it should be a singleton and so should be static (concerns with this approach noted too).
Answer: Yes, you should make it static. Making it static prevents it from being instanced. It's primarily designed to tell the person using the class that it only contains static methods, which helps readability.
Answer: Only that static class can not contain non-static members, so preventing you from accidentally adding them. Also as mentioned in Ray's answer, it will make your code clearer.

Deciding to make a C# class static


Find the value of $ \int_0^{\infty} \frac{2x^2-1}{4x^4+1}\,{dx} $

Question:
Find $ \displaystyle \int_0^{\infty} \frac{2x^2-1}{4x^4+1}\,{dx}
 $

I can find the primitive, but the fact that the answer is $0$ made me suspect there might be a way of getting answer without finding the primitive. I tried letting $x = 1/y$ but it didn't get me anywhere.
Comment: The indefinite integral evaluates to $\frac{1}{4} \log{ \frac{2x^2-2x +1}{2x^2 + 2x + 1}}$ which can now be seen to zero when evaluated at the limits
Answer: Instead of substituting $x = \dfrac{1}{y}$, try substituting $x = \dfrac{1}{2y}$.
This gives you:
\begin{align*}I &= \displaystyle\int_{0}^{\infty}\dfrac{2x^2-1}{4x^4+1}\,dx \\ &= \displaystyle\int_{\infty}^{0}\dfrac{\tfrac{1}{2y^2}-1}{\tfrac{1}{4y^4}+1} \cdot -\dfrac{1}{2y^2}\,dy \\ &= \displaystyle\int_{0}^{\infty}\dfrac{\tfrac{1}{2y^2}-1}{\tfrac{1}{4y^4}+1} \cdot \dfrac{2y^2}{4y^4}\,dy \\ &= \displaystyle\int_{0}^{\infty}\dfrac{1-2y^2}{4y^4+1}\,dy \\ &= -\displaystyle\int_{0}^{\infty}\dfrac{2y^2-1}{4y^4+1}\,dy \\ &= -I.\end{align*}
Since $I = -I$, we have $I = 0$.
Comment: May be $x = \frac{1}{\sqrt 2 y}$
Answer: Hint:
$4x^4+1=(2x^2)^2+1^2=(2x^2+1)^2-(2x)^2=?$
Now use partial fraction decomposition


Deontic Logic DD Axiom & Serial Relation of Accessibility

Question: I'm working my way through College Publications's Handbook of Deontic Logic and Normative Systems and I've run into a bit of trouble. I'm wondering if somebody could help explain why DD specifically, say, as opposed to KD necessitates that we regard R as a serial relation...
Comment: I interpreted the "as opposed to KD" part as asking the following question: "are there non-serial relations that ensure the validity of the KD axiom?" Is my interpretation correct?

(I have expanded my answer to include an answer to this question.)
Comment: @Z.A.K. Yes that's exactly what I meant. Thanks so much!
Comment: Is there some question that I left unanswered? If not, please consider accepting my answer :)
Comment: No you answered perfectly :) sorry about that
Answer: If a model validates the axiom DD, then for any "world" $w$ we have $w \Vdash \mathrm{OB}p \rightarrow \neg \mathrm{OB} \neg p$. We know that $w \Vdash \mathrm{OB}p \rightarrow \neg \mathrm{OB} \neg p$ holds precisely if $w \not\Vdash \mathrm{OB}p \vee w \Vdash \neg \mathrm{OB} \neg p$.
Assume that the first clause of the disjunction holds, so $\neg (w \Vdash \mathrm{OB}p)$. Expanding the definition of the satisfaction relation, we get $\neg (\forall v. Rwv \rightarrow v \Vdash p)$. By De Morgan's laws, this is equivalent to $\exists v. Rwv \wedge v \not\Vdash p$, so in this case we have $\exists v. Rwv$.
Now assume that the second clause holds, so $w \Vdash \neg \mathrm{OB} \neg p$. This means that $\neg (w \Vdash \mathrm{OB} \neg p)$ holds, and expanding the definition of Kripke satisfaction as in the previous case, we obtain $\neg (\forall v. Rwv \rightarrow v \Vdash \neg p)$. By De Morgan's laws, we have $\exists v. Rwv \wedge (v \not\Vdash \neg p)$, so again $\exists v. Rwv$.
In both cases we have at least $\exists v. Rwv$. Since this holds for any world, we must have $\forall w. \exists v. Rwv$. So to ensure the validity of the axiom DD, we must regard $R$ as a serial relation.

With respect to your second question: there are non-serial relations that validate KD (it is the usual axiom K of modal logic, which requires no frame conditions). In fact, even the empty relation validates KD.
By expanding the definition of satisfaction, we see that $w \Vdash \mathrm{OB}q$ is a sufficient condition for $w \Vdash \mathrm{OB}(p \rightarrow q) \rightarrow (\mathrm{OB}p \rightarrow \mathrm{OB}q)$.
Recall that $w \Vdash \mathrm{OB}q$ abbreviates $\forall v. Rwv \rightarrow v \Vdash q$. Notice that if $R$ is the empty relation, then $Rwv$ never holds, so the implication $Rwv \rightarrow v \Vdash q$ always holds. So the empty relation validates KD, but the empty relation is clearly not serial.


How to Generate Adjacent Indecies w/ NumPy

Question: So I'm trying to generate a list of possible adjacent movements within a 3d array (preferebly n-dimensional).
What I have works as it's supposed to, but I was wondering if there's a more numpythonic way to do so.
def adjacents(loc, bounds):
    adj = []
    bounds = np.array(bounds) - 1

    if loc[0] > 0:
        adj.append((-1, 0, 0))
    if loc[1] > 0:
        adj.append((0, -1, 0))
    if loc[2] > 0:
        adj.append((0, 0, -1))

    if loc[0] < bounds[0]:
        adj.append((1, 0, 0))
    if loc[1] < bounds[1]:
        adj.append((0, 1, 0))
    if loc[2] < bounds[2]:
        adj.append((0, 0, 1))

    return np.array(adj)

Here are some example outputs:
adjacents((0, 0, 0), (10, 10, 10))

= [[1 0 0]
   [0 1 0]
   [0 0 1]]

adjacents((9, 9, 9), (10, 10, 10))

= [[-1  0  0]
   [ 0 -1  0]
   [ 0  0 -1]]

adjacents((5, 5, 5), (10, 10, 10))

= [[-1  0  0]
   [ 0 -1  0]
   [ 0  0 -1]
   [ 1  0  0]
   [ 0  1  0]
   [ 0  0  1]]

Answer: Here's an alternative which is vectorized and uses a constant, prepopulated array:
# all possible moves
_moves = np.array([
        [-1, 0, 0],
        [ 0,-1, 0],
        [ 0, 0,-1],
        [ 1, 0, 0],
        [ 0, 1, 0],
        [ 0, 0, 1]])

def adjacents(loc, bounds):
    loc = np.asarray(loc)
    bounds = np.asarray(bounds)
    mask = np.concatenate((loc > 0, loc < bounds - 1))
    return _moves[mask]

This uses asarray() instead of array() because it avoids copying if the input happens to be an array already.  Then mask is constructed as an array of six bools corresponding to the original six if conditions.  Finally, the appropriate rows of the constant data _moves are returned.
But what about performance?
The vectorized approach above, while it will appeal to some, actually runs only half as fast as the original.  If it's performance you're after, the best simple change you can make is to remove the line bounds = np.array(bounds) - 1 and subtract 1 inside each of the last three if conditions.  That gives you a 2x speedup (because it avoids creating an unnecessary array).


Too many players on the basketball court

Question: After making substitutions, we accidentally had 6 players on the court (5th grade girls).  I called a timeout when I saw it (after maybe 5 seconds elapsed), and was granted the timeout. The refs did not realize we had 6 players until after allowing me the timeout when somebody from the stands yelled out.
I was then given a technical and still charged me with the timeout. Should I still have been assessed the technical foul?  Should I still have been charged the Timeout? While I acknowledge this was a fault on my part, it seems unfair that I got charged with both the technical and the timeout.
Comment: What rules are you playing under? NFHS?
Comment: Why do you think you shouldn't be pinged for the obvious technical breach simply because you were quicker to see it?
Comment: A charge is over once the player has broken physical contact and their opponent has hit the ground. That doesn't mean that the referees can't call the infraction.
Answer: Assuming NFHS, Rule 10-1 says it's a Team Technical, which indirectly affects the coach; the timeout doesn't negate that it happened, so technically the ref's were correct in the administration. They should have still allowed you the timeout before the free-throws were administered.
Now, personally, as a former official, I think it was tacky that they enforced it. I called a lot of Jr. High boys and girls and half the time the coaches were trying to teach the kids how to play. Rule 3-3-3 says the ref's are to administer the substitutions, so it's their fault for allowing it to happen. If you were in a huddle and broke with 6, and then called a timeout before the ball went into play, I think they could have let it slide.
But, technically, they were correct.


Right Click MainMenu

Question: Having problems with making so when you use right click on mainmenu or Form1 it works and open the specific submenu with Forest,Sea,Clouds and ignores the Pictures ,Exit Menu.
Here you cans see the MainMenu:

<code>unit Unit1;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls,
  Menus;

type

  { TForm1 }

  TForm1 = class(TForm)
    Image1: TImage;
    MainMenu1: TMainMenu;
    MenuItem1: TMenuItem;
    MenuItem2: TMenuItem;
    MenuItem3: TMenuItem;
    MenuItem4: TMenuItem;
    MenuItem5: TMenuItem;
    MenuItem6: TMenuItem;
    MenuItem7: TMenuItem;
    OpenDialog1: TOpenDialog;
    Panel1: TPanel;
    procedure FormCreate(Sender: TObject);
    procedure Image1Click(Sender: TObject);
    procedure MenuItem1Click(Sender: TObject);
    procedure MenuItem2Click(Sender: TObject);
    procedure MenuItem4Click(Sender: TObject);
    procedure MenuItem5Click(Sender: TObject);
    procedure MenuItem6Click(Sender: TObject);
    procedure MenuItem7Click(Sender: TObject);
    procedure Panel1Click(Sender: TObject);
  private
    { private declarations }
  public
    { public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.lfm}

{ TForm1 }

procedure TForm1.FormCreate(Sender: TObject);
begin

end;

procedure TForm1.Image1Click(Sender: TObject);
begin

end;

procedure TForm1.MenuItem1Click(Sender: TObject);
begin

end;

procedure TForm1.MenuItem2Click(Sender: TObject);
begin
  close;
end;

procedure TForm1.MenuItem4Click(Sender: TObject);
begin
  close;
end;

procedure TForm1.MenuItem5Click(Sender: TObject);
begin
  Image1.Picture.LoadFromFile('jura.jpg');
end;

procedure TForm1.MenuItem6Click(Sender: TObject);
begin
    Image1.Picture.LoadFromFile('forest.jpg');
end;

procedure TForm1.MenuItem7Click(Sender: TObject);
begin
       Image1.Picture.LoadFromFile('clouds.jpg');
end;

procedure TForm1.Panel1Click(Sender: TObject);
begin

end;

end.
</code>
Answer: Fixed my problem by adding popupmenu now everything works.

Right Click MainMenu


Problema Update Banco "literal de string extenso demais"

Question: Estou com um problema na hora de fazer o Update de um conteúdo para o banco de dados, abaixo o código usado para o Update
public function atualizar_conteudo_manual() {
    $dadosmanual_update = array ("id_processo_manual"=>$this->id,
    "conteudo"=>$this->conteudo);
    $this->db->where('id_processo_manual', $dadosmanual_update['id_processo_manual']);
    $this->db->set('conteudo', $dadosmanual_update['conteudo']);
    $this->db->update('tb_processos_manuais',$dadosmanual_update);
}

Pois bem, eu consigo fazer o Update do conteúdo, porém quando ele é extenso demais ocorre o seguinte erro:

Message: "oci_execute(): ORA-01704: literal de string extenso demais"

Gostaria de saber se é possível uma conversão para outro tipo de dado antes do Update, para este problema não ocorrer. De preferência a conversão para o tipo Blob.
Comment: invert o set com o where
Comment: ok invertido, mas a questão não é essa
Comment: Que eu me lembro isso já resolveria seu problema, não funcionou?
Comment: Você ta usando qual banco de dados?
Comment: Estou usando o Oracle Database
Comment: Tira o set para testar.
Comment: Tirei, o erro permanece com uma quantidade grande de dados, com pouco ele funciona mesmo sem o set
Answer: Problema do Update de Conteúdo extenso demais para o banco, resolvido com comandos OCI para comunicação com o banco Oracle, segue o código:

public function atualizar_conteudo_manual(){
        $sql = "UPDATE tb_processos_manuais SET conteudo = ' ' , titulo = :titulo, chave_amigavel = :chave_amigavel WHERE id_processo_manual = :id RETURNING conteudo into :conteudo";
        $stmt = oci_parse($this->db->conn_id, $sql);
        $lob = oci_new_descriptor($this->db->conn_id, OCI_D_LOB);
        oci_bind_by_name($stmt, ':conteudo', $lob, -1, OCI_B_CLOB);
        oci_bind_by_name($stmt, ':titulo', $this->titulo,50);
        oci_bind_by_name($stmt, ':chave_amigavel', $this->chave_amigavel,50);
        oci_bind_by_name($stmt, ':id', $this->id,5);
        oci_execute($stmt, OCI_NO_AUTO_COMMIT);
        $lob->save($this->conteudo);
        oci_commit($this->db->conn_id);
        oci_free_statement($stmt);
        $lob->free();
    }


How to choose such self-adjoint operators here.

Question: I'm reading Filmore's paper On sums of projections. In this paper Filmore made the following remark (on page 151, last paragraph):

By elementary spectral theory any self-adjoint operator with spectrum is $[-2, 2]$ can be written as the sum of two self-adjoint operator each having spectrum in $[-2, 2]$ and large null space (i.e. dimension of the null space is equal to the dim of the underlying separable Hilbert space).

The version of spectral theorem I know is:

Spectral Theorem. For any normal operator $A$ there is a projection valued measure $E$ on $\sigma(A)$ such that
$$A = \int_{\sigma(A)} z dE(z)$$

If we choose $P=E([-2, 0))$ and $Q=E([0, 2))$ then $A = AP + AQ$ but $AP$ may not have large null space!
Any help is appreciated. Thanks.
Answer: If $\sigma(A)$ is a finite set then there is an eigenvalue $\lambda$ such that $\mathcal{H}_\lambda:=\dim\ker (A-\lambda I)=\infty.$ We can decompose $\mathcal{H}_\lambda=\mathcal{H}_{\lambda,1}+\mathcal{H}_{\lambda,2}$ such that $\mathcal{H}_{\lambda,1}\perp \mathcal{H}_{\lambda,2}$ and $\dim\mathcal{H}_{\lambda_1}=\dim\mathcal{H}_{\lambda_2}=\infty.$   Then $$A=AP_{\mathcal{H}_{\lambda,1}}+A(I-P_{\mathcal{H}_{\lambda,1}})$$ have large null spaces, as the first summand vanishes on $\mathcal{H}_{\lambda_2},$ while the second on $\mathcal{H}_{\lambda_1}.$
Assume $\sigma(A)$ is infinite. Then it contains
a strictly monotonic sequence sequence $\lambda_n.$ Assume $\lambda_n$ is strictly increasing. Then for $\delta_n={1\over 2}\min\{\lambda_{n+1}-\lambda_n,\lambda_n-\lambda_{n-1}\}$ the projections
$P_n:=E_{(\lambda_n-\delta_n,\lambda_n+\delta_n)}$ are nontrivial and mutually orthogonal.
Let $$P=\sum_{n=1}^\infty P_{2n}$$  Then $P$ is an  orthogonal projection commuting with $A.$ Let
$$A=AP+A(I-P)$$
Then both operators are self-adjoint, with norm less than or equal $2.$ They admit  large null spaces. Namely the first summand vanishes on the range of $\sum_{n=1}^\infty P_{2n+1}$ while the second on the range of $\sum_{n=1}^\infty P_{2n}.$
When the sequence $\lambda_n$ is strictly decreasing, we consider $-A,$ decompose it according to the  method described above, and multiply the decomposition by $-1.$
Comment: I have two doubts: (1). Why does $P_n =E((\lambda_n-\delta_n, \lambda_n+\delta_n))\ne 0$? Since $\lambda_n \in (\lambda_n-\delta_n, \lambda_n+\delta_n)$ then in case $\lambda_n$ is an eigenvalue then I understand.
Comment: (2). Why is $\dim P(\mathcal{H})=\dim \mathcal{H}$? $P:=\sum P_{2n}$.
Comment: $P_n\neq 0,$ because $\lambda_n\in \sigma(A).$ The range of $P$ is the orthogonal sum of the ranges of $P_{2n}.$
Comment: Is it true that for any $\lambda \in \sigma(A)$ the spectral measure $E(\{\lambda\}) \ne 0$? I thought you used this to conclude $P_n\ne 0$.
Comment: But why the sum of ranges of $P_{2n}$ has the same dim as $\mathcal{H}$? Here $\lambda_n$'s are any increasing sequence it could be, say, inside $[-1, 1]$.
Comment: It does not matter where the sequence is located. The point is each $P_{2n}$ is nontrivial, they are pairwise orthogonal. So the sum has infinite dimension
Comment: If $\lambda \in \sigma(A)$ then $E(\lambda)-\delta, \lambda +\delta)$ is nontrivial.
 $E(\{\lambda\})$ may be trivial
Comment: Okay I see. $(\lambda-\delta, \lambda+ \delta)$ is nontrivial open set intersecting $\sigma(A)$. Thanks. The Hilbert space has countable dimensions so a sum of infinitely many orthogonal projections must have (countable) infinite dimension. Thank you so much .


What do referees do during halftime?

Question: This question largely pertains to basketball and American football. I've seen footage from the team locker rooms during halftime where the coaches and players go over issues from the first half that need to be addressed, key statistics, etc.
I've often wondered what the referees do during the halftime break (other than get a breather).  Do they go over replays where they botched calls?  If so, do they have someone whose job it is to create the "highlight reel" of missed calls, e.g. a coach for the referees?
Comment: No clue what pro's do, but high school officials will usually spend some time recovering from the first half (grab some water, maybe a protein bar) and chat up the scorer's table.
Answer: Especially in this age of 'on demand' media, NBA referees will take this time to analyze specific plays, fouls, flopping and potential arguments that might carry over to second half between two opposing players or between a particular referee and coach/player. The head referee will also critique his crew and make adjustments for second half. And as mentioned above its an opportunity to 'relax' and rehydrate.
Here's a good behind the scenes of NBA referee's halftime routines (around 2min mark): http://www.nba.com/video/channels/nba_tv/2013/04/17/20130416-monty-mccutchen-feat.nba/index.html
Comment: thank you for the link. It would be interesting if someone did a reality show and followed referees around for a while so you can see what they do.
Comment: That's an awesome video that perfectly answers what I was wondering.
Comment: @bob I'd definitely watch that
Answer: Most referees use this time to reflect on how the first half went. They discuss the game with their Assistant Referee's and are scanning for pointers. Some do this in order to hear from the Assistant Referee's how well they are refreeing. Others will use reasoning to justify the mistakes they made or even cover their butts by making excuses.
Comment: I assume this is what they do, but do you have any reference, referee interview, etc that discusses this?
Comment: This link may help you.
http://www.scrrs.net/articles/what-should-a-referee-do-at-half-time/
Comment: that's an interesting article, especially where it points out not to look at film from the first half.  However, this is for a minor league rugby league, where stakes might not be so high.  I'm specifically looking for NBA and/or NFL.

What do referees do during halftime?