I input an integer into a function expecting an integer out, I receive "None" as output

Question: This program checks if a function is truly random by having a 50% chance for each outcome and returning the number of times that it got "tails" in a row.
A problem is my throw() function returns None.
import random

# The number that will be used to check if a function is random
tails_in_a_row = 0

# This function will check if a library provides truly random numbers
def heads_tails():

    outcomes = ("heads", "tails")
    outcome = random.choice(outcomes)

    return outcome

# The function that throws the sum and then returns it
def throw(num):
    outcome = heads_tails()

    if outcome == "tails":
        num += 1
        throw(num)
    else:
            return num

for i in range(10):
    outcome = throw(tails_in_a_row)
    print(outcome)

I tried to change the else statement into elif and if. I tried creating local variables inside 'throw()'.
I am expecting that when I call return num I will get an integer.
If I call print(type(num)) before I call return num it shows that num is of type integer, but when I called return type(num) it returned type None.
Comment: If you want to keep throwing and return only when you get heads, it's better to use a `while` loop rather than recursion.
Comment: you forgot to return
Comment: `return throw(num)`
Comment: Why use a `while` loop rather than recursion as suggested above? (1) easier to code and maintain, more Pythonic and (2) there's no chance of blowing the stack and crashing the program if you have an unlucky run of more than 1k recursive calls. O(1) memory! Also, there's no need for `tails_in_a_row` to be a parameter, nor a global. Return results _up_ the call stack, not down.
Comment: Python indentation matters, here it is bad.
Comment: Debug questions require a [mre]--cut & paste & runnable code including initialization; desired & actual output (including verbatim error messages); tags & versions; clear specification & explanation. For debug that includes the least code you can give that is code that you show is OK extended by code that you show is not OK. [ask] [Help] When you get a result you don't expect, find the first point in the execution where the value of a variable or subexpression is not what you expect & say what you expected & why, justified by documentation. (Debugging fundamental.)
Answer: Your function throw() is recursive, but you don't return the value from the recursive path. You can just add return like this:
# The function that throws the sum and then returns it
def throw(num):
    outcome = heads_tails()

    if outcome == "tails":
        num += 1
        return throw(num)

    else:
        return num

This fixes the problem with seeing None in your output, but I'm not sure that it does what you want.


ConcurrentModificationException (Java)

Question: Exception in thread "main" java.util.ConcurrentModificationException
Squash the PC dirties the room Violet. The room's state is now dirty
Lily the animal growls
The Animal Lily left the room and goes to Green through the west door.
        at java.util.HashMap$HashIterator.nextEntry(HashMap.java:793)
        at java.util.HashMap$KeyIterator.next(HashMap.java:828)
        at homework5.Room.critReactRoomStateChange(Room.java:76)
        at homework5.PC.play(PC.java:121)
        at homework5.Main.main(Main.java:41)
Java Result: 1

That is the error I receive.
My method looks like
public void critReactRoomStateChange(String command, PC pc) {
    Creature temp = null;
    Iterator iterator = getCreatures().keySet().iterator();
    while (iterator.hasNext()) {
        String names = iterator.next().toString();
        if (!(getCreatures().get(names) instanceof PC)) {
            temp = getCreatures().get(names);
            if (temp != null) {
                temp.reactStateChange(command, pc);
                temp.checkNewRoom();
            }
        }
    }
}

So what I understand is this means I'm changing the size of the iterator before it is finished and this is the error you get.  This is true as one of the reactStateChange is for an object to be removed out of the hashMap.  How do I do this safely so that when I remove something it lets the Iterator know ahead of time so I can avoid this error.  Thanks in advance.  If more details are needed I'd be glad to meet your requests.
Comment: as a comment on the side: the calls to `getCreatures().get(...)` are not necessary. you already have the object you get. it is what `iterator.next()` returns...
Comment: Possible duplicate of [Iterating through a Collection, avoiding ConcurrentModificationException when removing in loop](http://stackoverflow.com/questions/223918/iterating-through-a-collection-avoiding-concurrentmodificationexception-when-re)
Answer: The only safe way to remove an element from an underlying collection and continue the iteration is to use the remove() method of the Iterator. This removes the last element returned by the next() method of the Iterator.
In your case, it appears that this would require passing the Iterator to the method that performs the modification (or make it an instance field, like the Map object is already).
Comment: Ah, as I was waiting for the answer I got the idea to look up Iterator in the API and found what you just told me.  I feel a little silly for asking now.  Thanks as you did help me because I was putting the remove after instead of before and I was still getting the error. lol tyty
Answer: You remove it using iterator.remove().
Answer: Another option is to use ConcurrentHashMap which doesn't have this issue. You can use this as a drop in replacement and you don't need to change the rest of the code.
Comment: nvm I found it it's import java.util.concurrent.ConcurrentHashMap;
Comment: Hey I'm looking at this but it wont let me create it.  says cannot find symbol I tried importing but it maybe I'm using the wrong one?

ConcurrentModificationException (Java)


Non stationarity and forecasting

Question: Let's assume we have estimated a linear regression model on a dataset from 2000 to 2017.
The data were stationary.
What happens if the data are no longer stationary in the next years? Do the forecasts stop being valid and should not be taken into account? What should a model developer do in this case?
And a related question: regressing non stationary time series automatically leads to spurious regressions?
Answer: Normally, if data were stationary and is with new data not stationary anymore one does not come to the conclusion that it will be so forever in the future. It may be that your time series may get back to its original stationary process, but only after a certain time (lag) that would lead to a model correction factor. The question is, what model/method did you use to forecast?

a VAR in levels would become a VECM for example in the above case.
a LSTM would adapt its weights and wont bother so much about the old things. That process is the same as a normal retraining of a NN. It may be that predictors which were good for prediction in the past are no longer. In that case a NN would use the new weights and wouldnt bother about old data anymore.

If data really is no longer stationary, you should try to wait until you have enough data and try to model a new one ( as stated a NN would atuomatically use new and transformed data). But I believe a stationary process observed over such a period (2000-2017), which were already stationary only got a very strong shock, and it will need more time to get back for it.
In summary: look at the amount of data points that are not statioanry, if they are enough to make a second model than do it. If the situation is unclear, wait and see if the time series gets back to its original state. That would lead to a new method but results and equation will only be correct by a certain factor.
Regressing non stationary time series without prior transformation is not advised. I wouldnt say it leads 'automatically' to a spurious regression as we should have a look at it, even a granger causality could be a spurious regression if both time series has nothing to do with each other: look here at this post: The fallacy of correlating some time series values with specific time points: is there a specific name for it or are there references?, but there are papers dealing with that and they state it is exactly as you say:
https://www.tandfonline.com/doi/abs/10.1080/03610920601041499
Comment: I suspect if it changed from stationary to non-stationary data you would have a structural break. There is a formal test for this, a chow test I believe.
Comment: That depends on the data and the field of research I guess. Must have a been a tremendous break. You may be right, but this is something he has to observe, if it still regenerates after some time. But you are right chow test is for structural changes: https://www.youtube.com/watch?v=uUxJk4UGXOg&t=3s

Non stationarity and forecasting


Solving Trigonometry Equation with powers

Question: I am having difficulty understanding how to solve $3\tan^2{\theta} - 1 = 0$
Putting $ t = \tan\theta $, I get $ t = \pm \frac{1}{\sqrt3} $. Is that done ? How to find angle $\theta$ now?
Any help would be much appreciated.
Thank you in advance.
Comment: @Narasimham Adding work which the OP has not expressed falls afoul of the "don't change the meaning of posts when editing" rule. Please refrain from making such edits.
Comment: @epimorphic. OK thanks, I am prepared to restore to s.q.a. It was not moving  forward, so thought may be it would help.
Answer: Hint:
$$3\tan^2\theta-1=0 \iff \left(\tan \theta - \frac1{\sqrt3}\right)\left(\tan \theta + \frac1{\sqrt3}\right)=0$$
Answer: You can split it this way
$$3\tan(o)^2-1=(\sqrt3\tan(o)-1)(\sqrt3\tan(o)+1)=0$$
so you have to solve both $$\sqrt3\tan(o)-1=0$$ and $$\sqrt3\tan(o)+1=0$$.
Comment: $\sqrt3\tan(o)+1=0$ can be replaced by $\sqrt3\tan(\theta)+1=0$
Answer: $$3\tan^2\theta-1=0 $$
$$ \left(\tan \theta - \frac1{\sqrt3}\right)\left(\tan \theta + \frac1{\sqrt3}\right)=0$$
$$ \theta =\pm \tan^{-1} \frac {1}{\sqrt3} $$
$$ \theta = \pm \pi/6 $$
Answer: Whenever you have terms containing the square of sine, cosine or tangent etc.
use $$\cos2A=2\cos^2A-1=1-2\sin^2A=\frac{1-\tan^2A}{1+\tan^2A}$$
Finally $\cos2A=\cos2B\implies2A=2m\pi\pm2B$ where $m$ is any integer


Do any professional sports leagues which have drafts use a snake draft format?

Question: A "snake" draft is a draft in which the team with the first overall pick gets the last pick of the second round, then goes first in the third round and last in the fourth, etc. It narrows the advantage of going first since you get that advantage in only half of rounds and receiving a partially-offsetting disadvantage in the even numbered-rounds. It is common in fantasy sports and seems to work well there, although most fantasy leagues start the season with everyone on equal footing in personnel terms (everyone has zero players) unlike in real professional sports where teams that did well in the previous season will likely have stronger rosters than those that did poorly.
Comment: No it doesn't, @NicholasV. I can't actually think of any offhand that do.
Comment: The NFL uses a snake draft, and I presume other leagues do too since it's generally pretty fair. Don't have time to make a detailed enough answer, though!
Comment: @MichaelMyers, yeah, come to think of it, I'm not actually sure what I was thinking ... definitely no snake draft in the NFL.
Answer: The purpose of the snake draft is to try and not give an advantage to any team drafting, under the assumption that having the 1 and 16 picks in an 8 team league is about the same value as 8 and 9.  This might not be so, but it is probably as close to favoring nobody as you can get.
The usual purpose of a league draft is the opposite - to give an advantage to poor teams to provide better competitive balance for the league going forward.  The NBA mitigates the advantage a little with the lottery, so that there isn't as large an advantage in tanking the season to have the worst record to get the #1 pick overall.
So leagues don't use snake drafts because the goals are different.


C# WinForms: A function that executes more than expected

Question: It sounds stupid, but this happens to me.
I activate a function, and it does its work, and after it finishes it enables itself again. With other words, the function activates twice, not once. I tried to find out why by debugging, but I didn't find the reason.
When I click on a panel this function activates:
<code>private void Play(object sender, EventArgs e)
{
    Play0(MousePositionX, MousePositionY);
    if (swich_player == true && AI_enabled == true)
    {
        AI_playing();
        swich_player = false;
    }
}
</code>
The whole code is really long.
Is it me not searching correctly? Are there other reasons? In order for this function to start again, something has to activate it. I can't find what is activating the function again.
Any suggestions, where to search for the problem? Or what is the problem?
EDIT:
I finally found the problem. There is a button (button1) that changes the panel's properties, and a second button (button2) that makes the panel 0 pixels wide and 0 pixels high (in order to make it invisible). The first button also adds an EventHandler that activates the function. But button2 does not remove the EventHandler. This way the function gets called as much times as the times I have pressed button1.
Comment: whhhhhhat?! can you explain better which function should be called by which one? or do you want to make the one above recursive? wouldn't you simply need a while(true) inside that if you just want to execute some code multiple times?
Answer: Looks like what you're looking for (via your comments/edit) is the source of multiple calls to this function. With the current snippet of code, it's not possible for us to tell. But what you should do is put a breakpoint on the entry of the function and then when it is hit, look at the "Call Stack" window in visual studio.
This can be accessed via the Debug -> Windows -> Call Stack menu item (when running the program. It will not show up in Windows if you're not running)
You can then see what is calling your function through this window. It is an extremely useful tool.
Pre Edit:
Your question isn't very clear, but I think (from your variable names) that you're looking for a game loop that will continually run. If so, take a look at this blog post which has some very good information on different styles of game loops. It ranges from simple to more complex (and scalable) loops.
Your question states that you activate something once and it "enables again", and also that "In order this function to start again, something has to activate it. I can't find what". These seem to be contradictory statements. Can you edit your question to be a little clearer? If my answer is not what you were looking for after your edit, I will do my best to add whatever is needful.
Comment: I understand better now, I didn't catch that from the original question. Have you debugged and used the "Call Stack" window to determine where each individual call is coming from?
Comment: I edited the question. But I don't think this can help me (but it might become useful in the future). I just want to know why is the function called twice with one click. The code has no lines that tell the program to do so, nor lines that call the function again.
Comment: No I haven't. I didn't know that this even existed. Thanks!
Comment: Not a problem, and good luck. I edited my answer to provide any more help finding this window, if you need it. I would *not* edit your function with bool flags/counters to keep it from running more than once, rather, you should use this functionality of Visual Studio to find what is calling it that you don't expect, and remove that.
Comment: Great, hope we helped. By the way, you do not need to manually set width/height to 0 for most controls to hide them. Look into Visibility=Visibility.Collapsed to do this for you.
Answer: check against which event you've registered this function. if you registered into to something no "OnClick" of that button, it might be the root cause
Comment: on the button properties pane, check against which event the function is written. it should be OnClick event only


What is the difference between proc{} and &proc{}

Question: What is difference in below usage
a = proc { puts 'hii' }

def abc(&a)
  a.call
end
abc(&a)

def xyz(c)
  c.call
end
xyz(a)

In below implementation more than one blocks can be passed as arguments -
def pqr(c, &t)
  c.call
  yield
  xyz(c)
  abc(&t)
end
pqr(a) { puts 'block to method'}

Answer: In the first of the two, the &a parameter will also capture a block passed like this:
abc {puts "Hello world"}

This is the same as:
xyz(proc {puts "Hello world"})

The other of the two only allows the last of the two.
Comment: Above both is not same in first case `actual block is passed` to method and in second case `block is passed as argument`. Second one should raise `ArgumentError: wrong number of arguments (1 for 0)`


Confidence Interval for Pareto Distribution

Question: A random variable is said to have probability density function $$f_X(x)=\frac{\alpha k^\alpha}{x^{\alpha +1}},\quad  \alpha , k>0 \; \text{ and }\; x>k.$$
1. Compute the MLE estimators $\widehat \alpha $ and $ \widehat k$ for $\alpha$ and k.
I figured they are $$\widehat \alpha = \frac{n}{\sum_i \text{ln}\frac{x_i}{\widehat k}} \quad\text{ while } \quad \widehat k=\text{min}_{i} \; x_i$$Correct me if I'm wrong.

Derive an 95% confidence interval for $k$.
Hint: Consider the distribution of the random variable $k/\widehat k$.

I don't get the point of the hint. Is it to figure out the critical value $(CV)$ to substitute in the expression
$$k= \widehat  k\pm CV se(\widehat k) \quad \text{where} \quad se(\widehat k)=\frac{1}{\sqrt{I_n(\widehat k)}}\quad \text{where }\quad I_n{(\widehat k)\; \text{is the Fisher Information at}\; \widehat k.}$$
If so, how do I answer this question.I feel I'll be able to get $I_n(\widehat k)$ but how do i get $CV$. Or what are other alternative methods.
Comment: In your MLE for $\alpha$, you need $\hat k$ where you have $k$.
Comment: I've now made the change.
Comment: Have you found the distribution of $\hat k$? ${}\qquad{}$
Answer: $$
\hat k >x \text{ if and only if }[X_1>x\ \&\ \cdots\ \&\ X_n>x]
$$
and the probability of that is $\Big(\Pr(X_1>x)\Big)^n$.
$$
\Pr(X_1>x) = \int_x^\infty \frac{\alpha k^\alpha}{u^{\alpha +1}} \, du = \left(\frac k x\right)^\alpha,
$$
so
$$
\Pr(\hat k>x) = \left(\frac k x\right)^{n\alpha}.
$$
Thus
$$
\Pr(x_1<\hat k < x_2) = \left(\frac k {x_1}\right)^{n\alpha}- \left(\frac k {x_2} \right)^{n\alpha}.
$$
$$
\Pr(Ak < \hat k < Bk) = A^{-n\alpha} - B^{-n\alpha}.
$$
$$
\Pr\left(A< \frac{\hat k} k < B\right) = \cdots
$$
$$
\Pr\left(\frac 1 B < \frac k {\hat k} < \frac 1 A\right) = \cdots
$$
$$
\Pr\left(\frac{\hat k}B<k<\frac{\hat k} A\right) = \cdots
$$
This gives you a confidence interval for $k$ if $\alpha$ is known.  Since $\alpha$ is not known, there is more work to do. (You have to choose $A$ and $B$ to get you the probablities that you want.)


Find the units and zero divisors of $\mathbb Z_3 \oplus\mathbb Z_{6}$

Question:
Find the units and zero divisors of $\mathbb Z_3 \oplus\mathbb Z_{6}$.

I would think that the units are {1,1}, {1,5}, {2,1}, {2,5}
But are there any zero divisors, because 3 is prime.
Comment: By unitary, do you mean unit? Usually, elements in that ring will be noted by $(x,y)$ rather than $\{x,y\}$. Finally, $3$ being prime does not prevent the ring from having zero-divisors (this is not just $\mathbb{Z}_3$ after all).
Comment: Consider elements $(0,i)$.
Comment: Tobias, yes my textbook uses the tems unit as well as unitary. I thought zero cannot be a zero divider. Isn't (0,0) the same as zero?
Comment: Yes, $(0,0)$ is the $0$-element. But what about elements of the form $(0,y)$ for $y\neq 0$?
Comment: Primality is not completely relevant, $(1,0)(0,1)=(0,0)$. Anyway, $6$ is not prime.
Comment: Does this mean that in any group or ring there can be only one zero element?
Comment: Yes, this is a standard exercise (if there were two, try to add them and see that their sum would equal both of them, so they were actually equal).
Answer: Note that if $R_1, R_2$ be rings then $U(R_1\times R_2)\cong U(R_1)\times U(R_2)$ where $U(R)$ denotes the group of units of the ring $R$.
By this, the ring $\mathbb Z_3\times \mathbb Z_6$ has $2\times 2=4$ units. In a finite ring a nonzero element is either a zero divisor or a unit. So the ring has $18-4=14$ zero divisors.
Comment: You are right. I missed that part. Thanks for the update
Comment: I apologize for my mistake. would you mind by editing my answer whatever is necessary ?


ANOVA with three IVs

Question: I have a following problem:
I have some research data that need to be analysed. There are three randomized independent variables (binary) and one dependent variable (reaction time). The data consists of several thousand observations (repeated measures for about 30 subjects, with full randomization):
[distractor, IV1, IV2, RT]
I need to test this data for interactions. AFAIK, I should use some version of ANOVA test, but I don't know which one exactly is appropriate here. I'd like to use R, or perhaps Scipy; I read some tutorials and articles on this topic, also here on SE. Unfortunately, my understanding of statistical analysis is very limited, and it seems I don't have enough theoretical knowledge to decide how it should be done. I would be really grateful for a possibly detailed explanation and tips on solving this with R.
Comment: By repeated measures fully randomized, do you mean each subject saw all levels of the independent variables? Is there missing data? Is the data balanced (equal number of observations for each subject in each level of the IVs)?
Comment: Yes, the data is balanced, and each subject went through all possible combinations of IVs, in random order. No missing data.
Answer: Mixed effects regression model may work for you. In R code:
library(lme4)
lmer(RT ~ IV1 * IV2 * distractor + (1 | ID), data=mydata)

where ID is subject identification, since it is a repeated measures of 30 subjects.
(1 | ID) type syntax is used with lmer for varying intercept or slope models. See: http://jaredknowles.com/journal/2013/11/25/getting-started-with-mixed-effect-models-in-r
Comment: Thank you! Could you please explain, what is this part about: `(1 | ID)`?
Comment: Please see the edit with link.
Comment: The answer provided won't test for interactions (which were mentioned in the question, though a very minor edit will (replace the first 2 plus signs with asterisks).
Answer: What you have described is a classic repeated measures ANOVA design. The data being balanced with no missing data makes the analysis even simpler (i.e. you could do it by hand in Excel in 5 minutes). You mentioned you randomized the order of the repeated measures. That means you cannot explicitly account for order effects (or at least it would be difficult to) but the randomization hopefully cancels out any systematic effect.
There are several ways to do repeated measures ANOVA in R. rnso provided the mixed effect regression method (it has like a billion other names like mixed models, multilevel models, etc.). Technically speaking, when you have balanced data with no missing values, it is equivalent to repeated measures ANOVA. Unless you plan on teaching yourself mixed effects regression on top of any other statistical training you may do, it is probably better to learn the more basic technique though. For starters, lmer will not give you p values. You may want to dive into that controversy and figure out why it doesn't and how to estimate them if you need them. Or you may just want to use an ANOVA command and avoid the headache. If you want to learn mixed effects regression, though, it is more flexible. I use it for all my repeated measures designs.
Here is good reference page for analyzing different kinds of repeated measures designs. It gives the analysis using aov lme and lmer. lme and lmer are both mixed effects regression functions from two different packages (rnso used lmer in his answer). Your exact design is not in there, though. You have a 3 way repeated measures design. They have 3 way split plot designs (an anachronistic word, unless of course you do agriculture research, for when you have both within subject factors and between subject factors... you only have within). However, it is easy to extend the 2-way repeated measures design to 3-way though. You simply add the third factor to both the fixed effects and the error strata. Your analysis is given by:
summary(aov(rt ~ distractor * IV1 * IV2 + Error(id/(distractor * IV1 * IV2)), data=dat))

Note that your data should be in long form (one row for each observation, meaning you'll have multiple rows for each subject). If your data is in wide format (i.e. one line per subject with multiple columns for different observations) you'll have to reshape your data or use another method (for instance the Anova function which I mention below.
There are other ANOVA commands in R that some people prefer, such as Anova from the car package or ezANOVA from the ez package. Regardless of what you do, though, you saying that you have very limited understanding of statistical analysis brings up some problems (that can't be fixed in a single forum reply). First, you mentioned you need to check for interactions. That single model above will tell you about the 3-way interaction, but the 2-way interaction terms may not mean what you think they mean, and their interpretation depends on how the IVs are coded. To check for both 2-way and 3-way interactions, you may have to run multiple models changing the coding to get what you want. Second, ANOVA is based on a set of assumptions that your data may or may not meet (normally distributed residuals, homogeneity of variance, and linearity). Repeated measures ANOVA adds additional assumptions (i.e. the assumptions of sphericity). Some functions, like ANOVA from the car package gives you tests of sphericity. Reaction time data rarely meets the normality assumption, but log transforming the reaction times often fixes the problem. Linearity just means that the data don't have non-linear patterns (or if they do you model that). If your IVs are dichotomous, this won't (can't) be a problem. Anyway, this is all stuff you can figure out pretty easily on Google. I mention them in passing here so you know that if you want to do the analysis right its a bit more complicated than the single line of code I put.
Comment: Thank you for an exhaustive explanation! I changed the accepted answer as it addresses all of my questions.

ANOVA with three IVs


Text hides when framelayout is set to some custom background (how to not inherit style from parent)

Question: I have a custom drawable as a background to the root of my framelayout with opacity(alpha) of 0.1. I have a LinearLayout inside which has some TextView. When I set my TextViews to the color of my FrameLayout's color it disappears( with no opacity ). How can I set opacity to my background(FrameLayout) without affecting my textviews(child of Framelayout). I have tried a lot of ways but it always hides the textviews inside.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout android:layout_width="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="@drawable/ic_img_bg"
    android:alpha="0.1"

    android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/linearlayout"

        android:orientation="vertical">

        <TextView
            android:layout_width="wrap_content"
            android:text="Not Verified,"
            android:textSize="32dp"

            android:textStyle="bold"
            android:textColor="@color/colorViews"

            android:padding="16dp"
            android:layout_height="wrap_content">

        </TextView>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingBottom="16dp"
            android:text="Sorry, We couldn't verify the mobile number ">

        </TextView>

        <LinearLayout
            android:layout_width="wrap_content"
            android:orientation="horizontal"
            android:layout_height="wrap_content">

            <ImageView
                android:layout_width="24dp"
                android:layout_height="24dp"

                android:src="@drawable/ic_icon_resentotp"

                ></ImageView>

            <TextView
                android:layout_width="wrap_content"
                android:layout_marginStart="8dp"
                android:text="Resend OTP"
                android:layout_gravity="center_horizontal"
                android:paddingBottom="16dp"
                android:layout_height="wrap_content"></TextView>
        </LinearLayout>

        <View
            android:layout_height="4dp"
            android:layout_width="match_parent"
            android:background="@color/colorViews"

            >

        </View>

        <LinearLayout
            android:layout_width="wrap_content"
            android:orientation="horizontal"
            android:paddingTop="16dp"
            android:layout_height="wrap_content">

            <ImageView
                android:layout_width="wrap_content"
                android:src="@drawable/ic_icon_changemblno1"

                android:layout_height="wrap_content">

            </ImageView>

            <TextView
                android:layout_width="wrap_content"
                android:text="Change mobile number"
                android:layout_height="wrap_content"></TextView>
        </LinearLayout>

    </LinearLayout>

</FrameLayout>

Answer: Well, If someone is still looking for an answer then I have it over here!!

xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent">

<FrameLayout android:layout_width="match_parent"
    android:background="@drawable/ic_img_bg"
    android:alpha="0.1"

    android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">

</FrameLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/linearlayout"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:text="Not Verified,"
        android:textSize="32dp"

        android:textStyle="bold"
        android:textColor="@color/colorViews"

    android:padding="16dp"
    android:layout_height="wrap_content">

</TextView>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingBottom="16dp"
    android:text="Sorry, We couldn't verify the mobile number ">

</TextView>

<LinearLayout
    android:layout_width="wrap_content"
    android:orientation="horizontal"
    android:layout_height="wrap_content">

    <ImageView
        android:layout_width="24dp"
        android:layout_height="24dp"

        android:src="@drawable/ic_icon_resentotp"

        ></ImageView>

    <TextView
        android:layout_width="wrap_content"
        android:layout_marginStart="8dp"
        android:text="Resend OTP"
        android:layout_gravity="center_horizontal"
        android:paddingBottom="16dp"
        android:layout_height="wrap_content"></TextView>
</LinearLayout>

<View
    android:layout_height="4dp"
    android:layout_width="match_parent"
    android:background="@color/colorViews"

    >

</View>

<LinearLayout
    android:layout_width="wrap_content"
    android:orientation="horizontal"
    android:paddingTop="16dp"
    android:layout_height="wrap_content">

    <ImageView
        android:layout_width="wrap_content"
        android:src="@drawable/ic_icon_changemblno1"

        android:layout_height="wrap_content">

    </ImageView>

    <TextView
        android:layout_width="wrap_content"
        android:text="Change mobile number"
        android:layout_height="wrap_content"></TextView>
</LinearLayout>


How to Translate Nested If/AND Statements into MIPS?

Question: As part of a class project I'm working on, a debug feature must be included.  I'm having trouble with some if/and statements.  This is what I wrote:
/previous code to find where status matrix contains a 1/
`beq  s0, 1, _debug_mode  #debug feature is ON if s0 contains 1
_debug_mode:
li   a0, 0            #tile flipped to say NOT revealed
_else:
li   a0, 1

`
I'm not getting the results I'm expecting, so my thinking is that the code is written incorrectly.  Any insight would be great!
Answer: This works out to the smallest C code of:
if (debug)
    status = !status;

In MIPS, this can be written (assuming s0 is debug, and a0 is status):
  blez s0, no_debug_mode
  xori a0, a0, 1
no_debug_mode:
   # ...

Or more verbosely
  blez s0, no_debug_mode
  blez a0, set_status_high
  li a0, 0
  j no_debug_mode
set_status_high:
  li a0, 1
no_debug_mode:
  # ...

The example you have posted only branches on one of the values and does not use a negation, so it will give the wrong results.  Further, you don't have a jump at the end of your _debug_mode label, so the _else will always execute.
It has been a while since I've done MIPS.  If there are branch delay slots required, those would have to be added to both of the above answers.
Comment: Real MIPS has branch-delay slots (unless you use MIPS32/64r6 no-delay branch instructions).  Many people doing MIPS homework program for MARS or SPIM with branch-delay slots disabled.  But the syntax in the question isn't using `$a0`, just plain `a0`, so it might not be either of those assemblers / simulators.  But yes, good answer, factoring out the `debug==1` precondition is possible in this case, simplifying everything.  Otherwise there are duplicate Q&As about the general case.  e.g. slt or whatever into registers that you combine with AND or OR.
Comment: Thank you, your answer was helpful.
Comment: @Nikki, glad to hear it.  You might consider using the checkmark to the left of the answer to accept it.  See https://stackoverflow.com/help/someone-answers


Unable to insert data into MySQL database using PHP

Question: I am unable to insert data into MySQL database. I do not know the reason since no error is triggered. I am using XAMPP on windows to run local server. Here is the code. It would be great if someone could help.
I am always getting "Values not inserted" output. I also tried printing the $query when I got exact values I entered through a form in the VALUES ('$email', ...) part of the SQL query.
<?php

$dbconnect = mysqli_connect("localhost","root","","id3626001_login_details");

if (!$dbconnect)
{
    die("Connection Failed" .mysqli_connect_error());
}

if (!mysqli_select_db($dbconnect, "id3626001_login_details"))
{
    echo "Could not connect to Database";
}

if (isset($_REQUEST['username']) && ($_SERVER["REQUEST_METHOD"] == "POST")){

$username = $_REQUEST['username'];
$email = $_REQUEST['email'];
$password = $_REQUEST['password'];

// Inserting values into the database through a query
$query = "INSERT INTO user_registration (ID, email, username, password) VALUES ('$email', $username', '".md5($password)."')";

if (!mysqli_query($dbconnect, $query))
{
    echo "Values not inserted";
}

$result = mysqli_query($dbconnect, $query);

if($result){
    echo "Registration Successful";
    }
}
?>

Answer: there is a problem in your query,
1) your column counts and count of values you are passing are not the same (must be same
2) you forgot to put ' (quote befor $username')
change your query to
// Inserting values into the database through a query

$query = "INSERT INTO user_registration ( email, username, password) VALUES ('$email', '$username', '".md5($password)."')";

When you are testing you should not only print only query, you should also copy that query and run it directly into database through [(localhost/phpmyadmin)> select your databse  > SQL ] and see what error are displaying there when firing a query.
UPDATE
for @Akintunde 's suggestion
for security concerns you should not be using these kind of insertion methods which is fully open to SQL injections you must follow some rule to avoid to get your script being target of sql injection
use Prepared Statements  instead for database operations
Answer: Here in your query you forgot to put upper quote '-> $username',
$query = "INSERT INTO user_registration (email, username, password) VALUES ('$email', '$username', '".md5($password)."')";

Here we are not passing Id as a param so you need to make id auto increment in database for that table.
and why are to passing your query twice into mysqli_query() you can check for once like,
$result = mysqli_query($dbconnect, $query);
if ($result)
{
  echo "Registration Successful";
}
else{
  echo "Values not inserted";
}

Comment: in your  query number of columns and values are different
Comment: Thanks @Irony Stack i edited my answer. thanks for pointing me.


Is this kit good enough if my goal is to develop rhythm?

Question: I'll start by saying my interests are mostly in DnB, Jungle and Breakcore. I'm looking to learn the drums and how people play them to make better songs, along with developing my sense of rhythm, but I probably won't be using them since I'll mostly just be using samples and MIDI. It'd mostly just be to teach myself rhythm and how to structure my beats.
With that being said, I was thinking tabletop electronic drum pads or some practice pads would suffice. But I do worry about sturdiness and ergonomics so I'm leaning towards something like this drum set.
Is my reasoning solid? Or is there another kit I should be looking for? Is there anything cheaper?
Comment: You can learn rhythm by clapping and snapping, or with a pair of sticks and a single practice pad. So no matter what you're asking is enough to learn rhythm, the answer is "yes".
Comment: This is two questions. If it's double braced hardware, and the cymbals have *one of the three names* on them, then it's "good enough". - Devolving rhythm has nothing to do with the gear.
Comment: Considering the target *styles*, being able to play drums is not a requirement. Knowing how drums and their playing works certainly doesn't harm (and may even provide some interesting insights), but you shouldn't consider that as fundamental. I remember loving some tracks in the early days of those genres and, being a drummer, I *knew* that some of those patterns wouldn't have made sense (with some being almost unplayable); nonetheless, they were extremely cool. Electronic music gives us freedom to explore the "unplayable", so, I'd reply to you with a premise and 2 quite different questions: »
Comment: » Premise: as said above, you don't need a drumkit to "develop rhythm"; there are plenty of percussionists who have deep rhythm knowledge/awareness, and they are **not** able to play drums, if not at basic levels. Questions: 1. do you realize the difficulties in learning drums (coordination/independence with all 4 limbs) and are you aware of your capabilities while considering the effectiveness of facing such difficulties? 2. have you considered that just being able to play drums doesn't automatically make your music better, but may only allow you to partially understand some of its aspects?
Answer: This kit is certainly good enough for you to develop rhythm skills. If portability and space saving is a big issue for you this practice pad set is a good way to go.
However, for about what this practice kit costs, on the same website you can get a basic electronic drum set which will have pad representations of snare, hat, 3 toms and 2 cymbals. Depending on how much you spend the bass drum may or may not have an actual pad and beater. The advantage to an e-kit is you can hear drum sounds with either earbuds, headphones or a powered speaker when you play. So not only does it have the complete kit which the practice pads do not have, you can hear the actual sounds of what you play. It also gives you the ability to output to a computer with USB which will allow you to use the kit to play and program your parts.
This site is not for product recommendations but I will at least say I'm not familiar with the "Fame" brand on that site. From personal experience, I bought an Alesis kit a few years ago with mesh tunable heads and a real bass drum pedal and pad and am very happy with it. Some say the mesh heads give a more natural feel, it's probably a matter of personal preference. I would say most major manufacturers produce products with comprable build and sound quality so if you choose to go this route do some research and read reviews (preferably published, not user reviews) to help you decide what is best for you personally. Good luck with whatever you decide.
Comment: Another option is a cheap acoustic drum set with the heads replaced by mesh heads and a set of low volume cymbals. Biggest downside to that setup is it's bigger than practice pads or electronic kits. The upsides are that it feels a lot more like a drum set and can be used as one with a head change and a set of real cymbals.
Comment: @ToddWilcox That  certainly is an option and has certain advantages like you say but by the time you buy a cheap kit and start adding mesh heads and low volume cymbals or cymbal mutes it starts to add up. Space, cost and volume were not mentioned as considerations by the OP so we can only speculate on those things.
Comment: I believe *Fame* is that particular store's house brand. I.e., the brand they use to re-sell OEM or white-label instruments. They're not necessarily bad. *Fame* guitars, for example, are built in cooperation with a luthier in East Germany that normally builds super-high-end guitars. *Fame* instruments are also sold in supermarkets, electronics stores, furniture stores, and on Amazon.
Comment: @JörgWMittag I'm familiar with store brands. We don't really have them here in the US but I know they exist in some European and Asian companies. It's very possible that Fame instruments are made in the same factory as some name brand instruments. I actually have a store brand Fender jazz style bass from Japan named "History". It is an excellent bass, every bit as good as USA Fenders.
Answer: I don't see this as 'recommend me a particular piece of kit' - so, the pads in question are all rather small, making learning to play drums quite tricky.
For the same sort of money, you could find a pre-loved drumkit, with real sounds, and real cymbals, all of decent proportions. Yes, the downside would be they're noisy to practise on, and take up more room. Or, for the same money, find a pre-loved, probably older electronic kit, which has the disadvantage mentioned - smaller pads, but the advantage of quiet play, using cans. Another advantage is that various other sounds could be programmed from this kit.
Using the kit in question I think would soon become boring, as it won't produce any variance in sounds, such as a proper kit would. Consider the 5 or 6 different sounds one can make from just one cymbal!
For basic rhythm patterns, a simple practice pad may suffice - use the floor as the bass and hi-hat if desperate, and that'll get you started. Or even a table top for the drumsticks (or use hands). Sounds crass, but it works!
Comment: I remember seeing a Drumeo pad that had multiple layers. I was thinking of buying that but is there any other practice pad you recommend instead? I was also thinking of investing in a practice bass too (it'd feel nice).
Comment: I think I have a better idea now. I'll use a practice pad for a snare and a hi hat stand and kick pedal to practice bass and hi hat. Do you have any suggestions how to practice toms?
Comment: I have that pad, but instead, tend to use a kit with my own home-made damper pads on each drum. That way, each drum is in its proper place, and the 'right' size, but 20% volume. I won't recommend anything, as that contravenes the rules of this site.
Comment: Short of having another couple of practice pads, no. But one would do for now.
Comment: I don't know how much the size is a problem, since most people try to hit the drums in the center anyway.
Comment: Going from an 8" trigger to an actual 14" snare is night and day. IMO all a pad does is teach you how to play w/o dynamics. Relying totally on how hard its hit as opposed to going slightly off-center for a ghost note is difficult.
Comment: @t_t "I'll use a practice pad for a snare and [buy a real] hi hat stand and kick pedal to practice bass and hi hat." - That's how you should be going about it. That 'thing' comes with a kick pedal. That's it. If it was a real HH stand, then sure. (only thing transferable to a real set is that meh kick pedal) - I just bought a $200 snare stand for a $300 ele set because I was tired of it bending out of the way on its single mount on a plastic rack. When I get the rest a real set together, I'll have a S stand worth using the rest of my life.


Cordova HTML input fields jumping on iOS

Question: I have a Cordova (version 6.3.1) app that is just HTML with some jQuery mobile code. This issue only occurs on iOS version of the app (Android works fine). Every time i press on a text box to insert a text after doing some scrolling, it jumps straight back to the top. The same happens with selecting radio buttons that are lower in the page. I have added a video to better explain myself.
Please see video here  on iOS 10.0.2
What I have tried:
1) Adding this to the config.xml file for platform=iOS:
<code><preference name="DisallowOverscroll" value="true"/>
<preference name="UIWebViewBounce" value="false"/>
</code>
2) Basically everything from  this issue.
Any other suggestions and help will be highly appreciated.
Comment: Is https://forum.ionicframework.com/t/click-a-input-field-whole-app-jumps-down-and-back-to-the-original-place/10876 this worth trying? This is a post for ionic and i am not sure where would i put that piece of code in a cordova app.
Answer: If you generating text field by programmatically you should clear dives using " clear: both;" or if it is not this problem won't happen if you create html page with responsive (better to use bootstrap).
Comment: I added div {clear:both;} to my css but this did not help.
Comment: did you try to implement html page in responsive page


Can't compile PrimeFaces demo

Question: I downloaded the PF demo from git at: https://github.com/primefaces/showcase
And run mvn package, but received the following message:
 martin@MyUbuntu:~/study/PrimeFaces/showcase$ mvn package
    [INFO] Scanning for projects...
    [INFO]
    [INFO] ------------------------------------------------------------------------
    [INFO] Building primefaces-showcase 6.0-SNAPSHOT
    [INFO] ------------------------------------------------------------------------
    Downloading: http://repository.primefaces.org/org/primefaces/themes/all-themes/1.0.10/all-themes-1.0.10.pom
    Downloaded: http://repository.primefaces.org/org/primefaces/themes/all-themes/1.0.10/all-themes-1.0.10.pom (10 KB at 8.7 KB/sec)
    Downloading: http://repository.primefaces.org/org/primefaces/themes/themes-project/1.0.10/themes-project-1.0.10.pom
    Downloaded: http://repository.primefaces.org/org/primefaces/themes/themes-project/1.0.10/themes-project-1.0.10.pom (4 KB at 8.1 KB/sec)
    Downloading: http://repository.primefaces.org/org/primefaces/primefaces/6.0-SNAPSHOT/maven-metadata.xml
    Downloading: http://repository.primefaces.org/org/primefaces/primefaces/6.0-SNAPSHOT/primefaces-6.0-SNAPSHOT.pom
    [WARNING] The POM for org.primefaces:primefaces:jar:6.0-SNAPSHOT is missing, no dependency information available
    Downloading: http://repository.primefaces.org/org/primefaces/themes/all-themes/1.0.10/all-themes-1.0.10.jar
    Downloading: http://repository.primefaces.org/org/primefaces/primefaces/6.0-SNAPSHOT/primefaces-6.0-SNAPSHOT.jar
    Downloaded: http://repository.primefaces.org/org/primefaces/themes/all-themes/1.0.10/all-themes-1.0.10.jar (1335 KB at 72.0 KB/sec)
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD FAILURE
    [INFO] ------------------------------------------------------------------------
    [INFO] Total time: 21.563 s
    [INFO] Finished at: 2016-03-08T16:30:14-08:00
    [INFO] Final Memory: 11M/153M
    [INFO] ------------------------------------------------------------------------
    [ERROR] Failed to execute goal on project showcase: Could not resolve dependencies for project org.primefaces:showcase:war:6.0-SNAPSHOT: Could not find artifact org.primefaces:primefaces:jar:6.0-SNAPSHOT in prime-repo (http://repository.primefaces.org) -> [Help 1]
    [ERROR]
    [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
    [ERROR] Re-run Maven using the -X switch to enable full debug logging.
    [ERROR]
    [ERROR] For more information about the errors and possible solutions, please read the following articles:
    [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/DependencyResolutionException

Answer: In your pom.xml file under <id>dev</id> fill in the correct version you find at https://repository.primefaces.org/org/primefaces/primefaces/
For the latest build as of today:
<dependency>
  <groupId>org.primefaces</groupId>
  <artifactId>primefaces</artifactId>
  <version>6.1.RC2</version>
</dependency>

Answer: The pom of the showcase references to an primefaces 6.0 snapshot jar on the primefaces sftp server.
As far as i can see there is no way to get this jar. I would recomend you to use the prebuild showcase war file and put it on a application server showcase download
Comment: In my case worked downloading not master source but 5.3 version. Then I changed in pom from   5.4-SNAPSHOT to 5.3 and it worked: mvn clean, mvn package and mvn jetty:run
Comment: You could also suggest to build the 6.0-SNAPSHOT too, locally. Then you have this jar.

Can't compile PrimeFaces demo


MLE on Structural VAR

Question: I have a simple model that I wish to fit using data. The model is of the form below.
\begin{gather}
y_t = -\lambda r_t + \theta a_t + \varepsilon_1 \\ \\
\pi_t = \pi_{t-1} + w y_t + \varepsilon_2 \\ \\
a_t = -\alpha r_t + \varepsilon_3 \\ \\
r_t = \phi_1 \pi_1 + \phi_2 a_t + \varepsilon_4
\end{gather}
where $\varepsilon_i$ are i.i.d. Gaussian shocks. This model has matrix form:
\begin{gather}
 \begin{bmatrix} y_t \\ \pi_t \\ a_t \\ r_t \end{bmatrix}
 =
  \begin{bmatrix}
   0 & 0 & \theta & -\lambda \\
   w & 0 & 0 & 0 \\
   0 & 0 & 0 & -\alpha \\
   0 & \phi_1 & \phi_2 & 0
   \end{bmatrix}
   \begin{bmatrix} y_t \\ \pi_t \\ a_t \\ r_t \end{bmatrix} +
   \begin{bmatrix}
   0 & 0 & 0 & 0 \\
   1 & 0 & 0 & 0 \\
   0 & 0 & 0 & 0 \\
   0 & 0 & 0 & 0
   \end{bmatrix}
   \begin{bmatrix} y_{t-1} \\ \pi_{t-1} \\ a_{t-1} \\ r_{t-1} \end{bmatrix} +
   \begin{bmatrix} \varepsilon_1 \\ \varepsilon_2 \\ \varepsilon_3 \\ \varepsilon_4 \end{bmatrix}
\end{gather}
i.e.
$$
Y_t = A Y_t + B Y_{t-1} + E
$$
For estimating this model, assume we have a $4 \times N$ matrix of time series data for $y_t, \pi_t, a_t, r_t$ (call it $D$).
How do I fit this model using maximum likelihood estimation? (without using Kalman filters or Bayesian methods)
My understanding is that this is an "Errors-in-variables" problem, which in some cases requires Total Least Squares (TLS). However, the TLS methods I've seen apply to more simple scaler $y=\beta x + \gamma$ problems, rather than VARs (or structural VARs).
Comment: If it's a DSGE model , then you're probably better off sending your question to economics.stackexchange.com. Also, if you google "horse race DSGE models" a lot of related papers will come up and some may be useful. The reason I googled for that was that there was  a paper that surveyed the various methods for estimating DSGE models that had the phrase "horse race" in the title. I can't recall the exact name and  it didn't come up in my google attempt but some other things did. It may be in the reference section of some of the papers that did come up since they too use the term horse race.
Comment: Thanks, but I'm trying to stick with simple MLE methods for this small example, if at all possible... I believe Errors-in-variables is the right approach, but I'm unsure how to proceed with it.
Comment: Hi Mich55. Unfortunately, I'm not knowledgeable enough about DSGE models to know if there is a simple approach.  I just googled for "solving dsge models using error in variables" and a paper from NBER came up titled: "solution and estimation methods for DSGE models". The first author is Jose-Fernandez Villaverde. That may tell you if it's possible to go in your direction. Good luck. Oh, like I said, there may be people who could answer your question on economics.stackexchange.com.
Comment: See also https://economics.stackexchange.com/questions/50345/mle-on-structural-var-dsge
Answer: I'm not particularly familiar with DSGE models, but a standard maximum likelihood estimation would go like this:
first we can write your matrix equation as:
$$ Y_t = (1-A)^{-1}BY_{t-1} + (1-A)^{-1}E$$
such that we can be express the conditional distribution of $Y_t$ given $Y_{t-1}$ :
$$ Y_t | Y_{t-1}  \sim \mathcal N ( \hat Y_t , \Sigma )$$
where $  \hat Y_t = (1-A)^{-1}BY_{t-1}$,  and $\Sigma = \sigma^2 (1 - A)^{-1}(1 - A^T)^{-1} $ (assuming $\varepsilon \sim  \mathcal N (0,\sigma^2)$
This follows from standard properties of the multivariate normal distribution.
The log-likelihood is therefore:
$$ \log\mathcal{L} = -\frac{1}{2}\sum_t (Y_t - \hat Y_t)^T\Sigma^{-1}(Y_t - \hat Y_t) - \frac{1}{2} N \log |\Sigma| $$
Now we can use the fact that $\Sigma^{-1} = (1 - A^T)(1 - A)/\sigma^2 $ to simplify some of the terms :
$$ \hat Y_t^T \Sigma^{-1} Y_t = Y_{t-1}^TB^T(1-A)Y_t = \pi_{t-1}\pi_t - \omega y_t y_{t-1}$$
$$ \hat Y_t^T \Sigma^{-1} \hat Y_t^T = Y_{t-1}B^TBY_{t-1} = y_{t-1}^2$$
Notice that we only have up to quadratic terms of $A$ from the exponential, so taking the derivative with respect to elements of $A$ from that part gives us something linear in $A$, e.g. :
$$ \frac{\partial}{\partial \theta} (\frac{1}{2} Y_t^T \Sigma^{-1} Y_t) = -\frac{1}{2\sigma^2} Y_t^T \left(\frac{dA^T}{d\theta}(1-A)  + (1-A^T) \frac{dA}{d\theta}\right)  Y_t$$
$$ = -\frac{1}{\sigma^2} \text{tr}\left( \frac{dA^T}{d\theta}(1-A) Y_t Y_t^T\right)$$
Notice that $\frac{dA^T}{d\theta}$ is a matrix that has just a single non zero entry at the location of $\theta$ , so we can write this more generally in a matrix notation
$$  \frac{\partial}{\partial A} (\frac{1}{2}\sum_t Y_t^T \Sigma^{-1} Y_t) = -\frac{1}{\sigma^2} (1 - A) \left(\sum_t Y_t Y_t^T \right) $$
(However keep in mind that this should be read as as equation for the non zero entries of $A$ only).
Now we are left to deal with the determinant part, for which we can take the derivative as follows :
$$ \frac{\partial}{\partial \theta}  \log |\Sigma|  = -\text{tr}(\frac{\partial \Sigma^{-1}}{\partial \theta} \Sigma) $$
plugging in the derivative of $\Sigma^{-1}$ we get
$$ \frac{\partial}{\partial \theta}  \log |\Sigma| = \frac{1}{\sigma^2}\text{tr}\left(\frac{dA^T}{d\theta}(1-A^T)^{-1}  + (1-A)^{-1} \frac{dA}{d\theta}\right) = \frac{2}{\sigma^2}\text{tr}\left( \frac{dA^T}{d\theta}(1-A^T)^{-1} \right) $$
and as before we can write it as
$$ \frac{\partial}{\partial A}  \log |\Sigma| = \frac{2}{\sigma^2}(1-A^T)^{-1} $$
putting everything together :
$$ \sigma^2 \frac{\partial}{\partial A}  \log \mathcal{L} =  (1 - A) \left(\sum_t Y_t Y_t^T \right) - B \left(\sum_t Y_t Y_{t-1}^T \right) - N(1-A^T)^{-1}.$$
Equating this to zero gives the maximum likelihood equation for $A$, But the equation is non linear and therefore can't be solved directly (in fact it can be written as a quadratic, but I don't think that helps much).
Nevertheless it can be easily solved iteratively using gradient descent methods, with the above gradient. Note that the dependence on the data $Y$ is only via the two correlation matrices defined above, which you only have to calculate once. Also note that the MLE does not depend on the noise variance $\sigma^2$.
[Note: I can't guarantee that every (-) sign and $^T$ is correct, if you are going to use some gradient based optimization tool you should verify the result against a numerical gradient, or you could use a symbolic program to calculate the derivatives. If you want to work out the details of the derivation by yourself, the Matrix Cookbook is a useful reference.]
Comment: Yes that's correct. I'm not entirely sure if it will still factor out as in the simple case, but it should  be easy to calculate as long you carefully take care of the orderings  (if it does though then the MLE will remain independent of it)
Comment: Thanks! Question: if the shocks have different variances (and/or non-zero covariance), is the result similar as long as you substitute $/sigma$ with $/Sigma$, and take care to keep it in the correct positions (since it may not commute)
Comment: Do things change a lot if you don't know the covariance matrix (i.e. \Sigma), and have to estimate it? e.g., does it add an extra term to the likelihood function?

MLE on Structural VAR


AngularJS ng-click doesn't work

Question: i have this select script, and I want to close the menu when

  <zc-select ng-init="CountryOpen = false; Country = []" status-var="CountryOpen">

                Select a country

{{i.name}}

        </zc-select>

somebody know why the ng-click don't work ?
I can't add more details. I can't add more details. I can't add more details. I can't add more details. I can't add more details. I can't add more details. I can't add more details. I can't add more details. I can't add more details. I can't add more details. I can't add more details. I can't add more details. I can't add more details. I can't add more details. I can't add more details. I can't add more details. I can't add more details. I can't add more details. I can't add more details. I can't add more details. I can't add more details. I can't add more details. I can't add more details. I can't add more details. I can't add more details. I can't add more details. I can't add more details. I can't add more details. I can't add more details. ( this is for error)
Comment: Can you define "don't work"? you are setting a variable to false, does it not set it to false?
Answer: Your problem is that you are trying to assign to a scope variable in your html template inside an ng-repeat. The ng-repeat creates a nested scope for each item, so the assignment happens only within that inner scope.
To fix this make sure the name you assign contains at least one dot .. An easy way to do this is to switch your code to use the 'controller as' syntax and then you can reference the required controller directly. Another way would simply be to push your scope variables inside an object instead of directly on the scope.

    <zc-select status-var="vm.CountryOpen">

            Select a country

{{i.name}}

    </zc-select>

and then update your controller to use this instead of $scope:
app.controller('Ctrl', [function() {
   var vm = this;
   vm.CountryOpen = false;
   vm.Country = [];
   vm.countries = [
   ...

(I pushed the ng-init stuff into the controller because it's good to keep as much of the code together as you can and keep the html as clean as possible)
Comment: Thanks! You helped me!

AngularJS ng-click doesn't work


send json data to another url - after you've got it back from my own url

Question: This is how the json I get from my page send when I clicked post, I throw a different URL.
That piece of data should like to come to look like this:
api.quickpay.net/subscriptions?currency=dkk&order_id=testworld&description=MB: 6-testworld
But when I get my json back watching it like this:
<code>{"Prices":220,"HiddenIdMedlemskab":6,"ordre_id":"6-8315042016","currency":"DKK","description":"MB: 6-8315042016"}
</code>
The json should I have shed into a url that I added earlier.
My jquery code looks like this:
<code>$.ajax({
    type: 'post',
    url: '/Medlem/medlemskabet',
    dataType: 'json',
    data: JSON.stringify(requestData),
    contentType: 'application/json; charset=utf-8',
    async: true,
    processData: false
});
</code>
Over on my url /Medlem/medlemskabet
That gets the dates that I need for my json to specify package price orderid etc
So my question is How do I tag my json about throwing it over to the api URL and throws it into their system.
I've built since the MVC C #
Answer: You can pass the JSON object as an argument to <code>$.get()</code>, and jQuery will convert the properties into URL parameters.
<code>$.ajax({
    type: 'post',
    url: '/Medlem/medlemskabet',
    dataType: 'json',
    data: JSON.stringify(requestData),
    contentType: 'application/json; charset=utf-8',
    async: true,
    processData: false,
    success: function(response) {
        $.get('api.quickpay.net/subscriptions', response);
    }
});
</code>
Comment: I don't understand what that means. My answer doesn't show anything, it just calls the API.
Comment: its give me a error on "requestData", its say: Uncaugth rederenceError: requestData is not defined
Comment: I took that from the code in your question. I thought that part was working, and it returns the JSON that you showed.
Comment: It does this too but I just saw the error by going into the console and look. This error happens first when I clicked on submit
Comment: i try to this here: http://tech.quickpay.net/api/services/?scope=merchant#POST-subscriptions---format-
Comment: You need to fix the part of the code that sets `requestData` before it calls `$.ajax`.
Comment: How do you think I should do it ?, this is the first time I, like, really work with json to javascript? and as well api
Comment: I really don't understand what you're asking. You just need to fill in `requestData` from your application's input before making the AJAX call. Without seeing more of the code, I can't be any clearer.


How does someone safely develop intensity at an extremely high tessitura?

Question: We've had a couple different questions about extending voice range.  This question is probably related more to endurance and tone quality, not just extending range.
Find a recording of Dexter Holland singing Half-Truism (or just remember it).  Notice that the tessitura of the vocal line is screaming high the entire song.  I'd have to listen to it again to be sure, but I remember a range of at least d'-c''.
One source claims that Dexter Holland's range is G-d'', but this particular song is obviously all in the highest octave (roughly) of that range.  (The same source also claims he is a "low tenor," which I don't believe quite matches the range given.)  Yet, it sounds intense without sounding forced, and it certainly doesn't sound like falsetto to me.
How does a male singer accomplish this?  I know recordings can be done in stages, but for a live performance, how does a singer pull that off and still have a voice left?
Comment: related: http://music.stackexchange.com/questions/758/how-much-louder-can-a-singer-go-safely-above-the-conversation-voice
Comment: @MatthewRead I suppose that's somewhat related, yes, though the singer may or may not actually be singing all that loud.  It just sounds "intense."
Answer: Often when a singer is performing in there higher register, they begin to constrict their vocal folds.  It is not healthy to consistently sing with your folds constricted. "To oscillate, the vocal folds are brought near enough together such that air pressure builds up beneath the larynx." (wiki article on vocal folds)  If your folds remain constricted the necessary air pressure goes over the folds, causing potentially permanent damage.
Different schools of vocal pedagogy teach us ways to avoid doing this, making it able to use one's high register for long periods of time while not damaging the voice.  Jo Estill has some fantastic materials on the subject of vocal health in all styles of singing.
Estill's program uses everyday "cues" to get your vocal mechanism into a healthy position for the style of singing you are about to do.  For a high level endurance (such as opera, musical theater, and even rock and roll) one uses a "belting" quality.  To get your mechanism in position, make the preparation to shout as if in great excitement: raised eyebrows; cheekbones or sinuses raised as if you have a big goofy smile on your face; for higher parts, use quick high chest-breaths instead of deep low stomach breaths.
This should help in that style of singing.  I would definitely suggest looking into Jo Estill's materials if you are going to be singing like this often, as they are full of valuable and voice-saving information.


No converse of ratio test, so how to find ROC given convergence of coefficients?

Question: A student brought me this problem and I admit I am stumped:
Suppose we have the series $\sum_{n=0}^{\infty} a_n x^n$ such that
$\lim_{n \to \infty}$ of the nth root of $|a_n|$ equals $L$ for $0 < L < \infty$
Let $\sum_{n=0}^{\infty} (n+1)a_{n+1} x^n$ be the series obtained by differentiating the original one term by term.  Show that the radius of convergence of the new series is $1/L$.
It looks plausible, but a proof eludes me.  The condition is the root test, and so we know that the series $\sum_{n=0}^{\infty} a_n$ is absolutely convergent.  But that doesn't imply that $|a_{n+1}|/|a_n|$ goes to a limit less than $1$.
If $|x| \leq 1$,
I see how by a comparison test $a_n x^n$ would also converge.  But I don't see how to find the full radius of convergence.  It just seems like an odd problem that would require a converse of the ratio test that doesn't exist.
As another point, I read somewhere that the limit L in the root test is the same L as in the ratio test, but I don't see how to prove that and that would also be needed.
Answer: $\sum_{n=0} a_n $ is not absolutely convergent. It will converge if $0<L<1$.
The radius of convergence for $\sum_{n=0} a_n x^n$ is $1/L$ by the root test:
$$\sqrt[n]{|a_nx^n|} = \sqrt[n]{|a_n|}\sqrt[n]{|x^n|}  = L|x| \Rightarrow |x|<1/L$$
The derivative will have the same radius of convergence
$$\sqrt[n]{|na_nx^n|} = \sqrt[n]{n}\sqrt[n]{|a_n|}\sqrt[n]{|x^n|}  = 1*L|x| \Rightarrow |x|<1/L$$


I cannot log in, and I am said I have 5 failed logins

Question: I've setup a virtual host on one of my machines. The front page shows fine, but the other pages don't. When I put in my login information, and I click the "Log in" button, I get the "page not found" error.
If I go to www.example.com/?q=user, I get that page, but when I try logging in, I see the following error message:

Sorry, there have been more than 5 failed login attempts for this account. It is temporarily blocked. Try again later or request a new password."

How can I solve this problem?
Comment: I dont think its related to Clean URL as the message implies.
Comment: Try my solution below.
Answer: The quick solution is to login in your database
mysql -u <username> -p<password> or drush sql-cli
and execute this query
truncate flood;
Thats it and you'll able to login again.
Answer: Disable clean URLs. Configure your server / drupal for clean URLs, then enable clean URLs.
How to configure clean url on an server depend on kind of server setup you are running.More info on clean urls http://drupal.org/getting-started/clean-urls
Comment: I am running MAMP server,I can't login so I'm unclear how to disable clean urls
Comment: ok i got them turned off in drupal by turning them off on my original site and then recopying the db over but now when I try to enable the clean url test fails I suspect it due to virtual host
Comment: double check your .htaccess file.
Answer: The issue can be resolved by either removing the entries in the flood table (as stated by user8012) or installing a module to assist with removing the entries. Please read http://bri-space.com/content/how-fix-drupal-7-blocked-account-after-5-incorrect-password-attempts for more details.
Answer: You can use phpMyAdmin to delete the entries in the "flood" table.

Go to your phpMyAdmin page and login

Select the database of your Drupal website from the left sidebar

Click on the "SQL" link on the top horizontal menu

Copy the following SQL query:
DELETE FROM flood;

paste it in the text area of the "SQL" page and click on the "Go" button.

The entries in the "flood" table will be deleted and you will now be able to login to your Drupal website.

OR
You can use terminal.

Connect to your server with ssh
ssh firstname.lastname@example.com

alternatively you can use the IP address of your website
ssh firstname.lastname@example.com

Start the MySQL prompt by typing
mysql -uroot -p

and give your password.

Select the database that you want to use
USE yourDatabaseName;

And delete the entries from the "flood" table
DELETE FROM flood;

Exit from MySQL and from the server and now you'll be able to login again.
exit;


Document private web API

Question: We set up a web API for project internal usage.
I'm looking for a nice way to document our API. I've searched the web and found

IO Docs
Swagger

These tools read in JSON files that can be created automatically, e.g. for Java. Our API has grown and I like to create the JSON manually, but not by hand in a text editor. Is there a tool or frontend that eases the burden of creating the descriptive JSON manually?
On the other hand, what are recommendable tools for the documentation of a web API?
Answer: I work in a .NET (C#) shop and we use swagger to document our apis.  We couldn't find any tools to do what your asking...so we just created our own.  I don't think swagger is mature enough to spawn utility projects like that...yet.
It was not to difficult to create classes to represent the json objects described by the swagger documentation.  We just take these instantiated classes and run them through a JSON serializer to get our individual json files describing our endpoints.
Best of luck!

Document private web API


How do I use an older jQuery version?

Question: Drupal 8.5 requires jQuery 3, which has some site breaking features. I would rather like to use version 2.2.4. I have tried the libraries-override approach suggested in How do I use a jQuery version different from the default one used by core? After applying that answer, the theme.libraries.yml file content is the following one.
global-styling:
  css:
    theme:
      css/main.css: {}

jquery-custom:
  remote: https://github.com/jquery/jquery
  version: "2.2.4"
  license:
    name: MIT
    url: https://github.com/jquery/jquery/blob/2.2.4/LICENSE.txt
    gpl-compatible: true

global-scripts:
  js:
    js/plugins.js: {}
    js/drupal-main.js: {}
    js/vendor/modernizr-3.3.1.min.js: {}
    js/jquery-2.2.4.min.js: { minified: true, weight: -20 }

  dependencies:
    - core/drupal
    - core/jquery
    - core/jquery.once

The theme.info.yml file content is the following one.
libraries:
  - theme/global-styling
  - theme/global-scripts
libraries-override:
  core/jquery: theme/jquery-custom

However, it gives me a reference error saying that jQuery is not defined. I have checked the path and there is no problem there. What am I missing here?
Is there any other way to downgrade from jQuery 3 to jQuery 2 in Drupal 8?
I also tried using the following code, but I still getting a reference error.
jquery-custom:
  remote: https://github.com/jquery/jquery.js
  version: "2.2.4"
  license:
    name: MIT
    url: https://github.com/jquery/jquery/blob/2.2.4/LICENSE.txt
    gpl-compatible: true
  js:
    js/jquery-2.2.4.min.js: { minified: true, weight: -20 }

global-scripts:
  js:
    js/plugins.js: {}
    js/drupal-main.js: {}
    js/vendor/modernizr-3.3.1.min.js: {}

Comment: Your custom jQuery library `jquery-custom` is missing the important `js` part. Additionally, you should remove jQuery from your global-scripts `js`.
Comment: You need to download jquery 3.5.1 min into your themes js folder for this to work. Maybe people are expecting it to be referenced to an external source?
Comment: @MarioSteinitz Thanks for your answer. Yes I tried that:
`jquery-custom:
  remote: https://github.com/jquery/jquery.js
  version: "2.2.4"
  license:
    name: MIT
    url: https://github.com/jquery/jquery/blob/2.2.4/LICENSE.txt
    gpl-compatible: true
  js:
    js/jquery-2.2.4.min.js: { minified: true, weight: -20 }

global-scripts:
  js:
    js/plugins.js: {}
    js/drupal-main.js: {}
    js/vendor/modernizr-3.3.1.min.js: {}
`
However, I still get the jqeury is not defined error.
Comment: Is the empty line between the `js` part and `dependencies` a paste error, or what you actually have in your definition? If so, remove that too. YAML is very sensitive to indents. - And omit the remote part of your `jquery-custom` library. A version and the js should do.
Comment: @MarioSteinitz That was a pasting error. I just checked the yaml file using a parser: https://imgur.com/a/JPyQKXU I didn't get any error.
Comment: Just to verify, you are using the actual theme key in place of `theme/` right?
Comment: @Kevin Yes, there's a proper theme name there like bartik.
Answer: I had the same issue with some older Google tags plugins that did not work with jquery 3.0.  You basically have to use the D8 library override methods in your theme to do this.
This actually goes into the theme info.yml file.  You need to have the other version of jquery defined in your library.yml file as well.  Here's some excerpts from my theme files.
my_theme.info.yml
libraries-override:
  #downgrade jquery / force jquery into header
  core/jquery: my_theme/jquery

The core/jquery was found by searching thru the core to find the jquery library definition.
my_theme.libraries.yml
jquery:
  header: true
  remote: https://github.com/jquery/jquery
  version: "2.2.4"
  license:
    name: MIT
    url: https://github.com/jquery/jquery/blob/2.2.4/LICENSE.txt
    gpl-compatible: true
  js:
    js/jquery-2.2.4.min.js: { minified: true, weight: -20 }

Note: The header: true loads jquery in the header and not the footer.  Helps a bit with embedded jQuery code that complains that jquery does not exist.  I have a local copy of jquery in the js directory of my theme as well.
This technique can override any CSS or javascript included by any module or core.
Comment: Did you do anything else? I keep getting the jquery not defined error.
Comment: Is the jquery not defined coming from JS code using jquery?  If so, make sure you have the header: true option above.  D8's default is to load jQuery in the footer so js using it might look for it before it's loaded (Marketo stuff in our case).  Having it in the header loads it before most other JS code.  Also, you should be able to see which jQuery is being loaded via Chrome's sources tab in the dev tools.  This will verify which version / if it's loaded.
Comment: I used `header: true`. However, I am still getting the error. jQuery is not loading at all. I used `jQuery.fn.jquery` to find the version, and I got the jQuery not defined again.
Comment: You did not show any dependencies in your libraries.yml.  D8 only loads jquery when needed as defined by dependencies.  You may need to add   dependencies:
    - core/jquery
To your global js scripts (or specific script) to tell D8 to load it.
Comment: I have. I added this question in the forum as well with my current files: https://www.drupal.org/forum/support/theme-development/2018-08-21/how-can-i-downgrade-jquery3-to-jquery-2-in-drupal-85
There you can see the complete file.
Comment: The dependency option should not go under the jquery-custom but rather under the global-scripts library definition.  This means that jquery should be loaded anytime the global scripts files are loaded (probably on every page).
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/82032/discussion-between-darkmatter-and-cg-monroe).

How do I use an older jQuery version?


How do you build a blues scale?

Question: Hi I am doing grade 8 theory (Trinity).
I need a quick and easy way to remember/ know of how to build blues scales.
TIA
Comment: Related: https://music.stackexchange.com/questions/32964/two-kinds-of-blues-scales
Comment: Also: https://music.stackexchange.com/questions/31071/exact-pitch-of-blues-scale-notes.
Answer: In terms of degrees of a given (Major) key the formulas are:
Minor Pentatonic: 1, b3, 4, 5, b7
Major Pentatonic: 1, 2, 3, 5, 6
This will get you the pentatonics in any key.  The minor pentatonic is related to the major pentatonic the same way that a relative minor key (or scale) is related to a major key.  Just start of the 6th degree.  So, you create the first formula from the second as follows:
Relative Minor Pentatonic: 6, 1, 2, 3, 5
It is easy to check that this is the same result treating the 6 as 1.  Think of C maj Pent and its relative minor A min Pent.  An interesting note:  All the major modes have the same major pentatonic, Ionian, Lydian, Mixolydian.  Since we are removing the 4th and the 7th from the list of notes.  The minor pentatonic fits over Aeolian, Dorian, and Phrygian.
As for blues, the traditional "blues" scale is the minor pentatonic with a flat 5 added,
Blues: 1, b3, 4, b5, 5, b7
Other answers have provided results in C or another key.  I hope this formula in degrees is more general and helps.
Answer: Which blues scale? I am assuming you mean the hexatonic blues minor scale. There are a number of ways.
1) Take the pentatonic minor scale:

C - E♭ - F - G - B♭

and add a sharpened fourth:

C - E♭ - F - F# - G - B♭

2) Take natural minor:

C - D - E♭ - F - G - A♭ - B♭

and remove the second and sixth degrees, and then add a sharpened fourth:

C - E♭ - F - F# - G - B♭
Comment: Then what would you do if it was major?
Comment: @EthanJarrott, the hexatonic major blues scale is pentatonic major with a sharpened second (C-D-E-G-A and C-D-D#-E-G-A, respectively).
Comment: @EthanJarrott - more usually, blues scales have **flattened** notes, not sharpened ones. So C maj blues will be spelled C D Eb E G A - the same notes, actually, as A **minor** blues. Jazzers tend to think in terms of #4 rather than b5.
Comment: @Tim, good point. I tend to forget. I mostly play jazz these days. Thank you.
Answer: There are two standard blues scales, major and minor.
Taking each, add one note to the pentatonics to produce the hexatonics.
C minor pent. is C E♭. F G B♭.  Add G♭/F♯ and it's C min. blues.
C major pent. is C D E G A. Add D♯/E♭ and it's C maj. blues.
Comment: @AlbrechtHügli - what I'm saying is there are two blues scales, major and minor. They work exactly like relative (English term) keys. C major/A minor. Pents and blues scales work in exactly the same relative way. In C major blues there is no bVII. Only in minor blues. So the relative of C maj blues has that bVII. The key is now A minor blues, with G (bVII).
Comment: I miss the B♭ in C maj7 (as the flat 7 is essential for the blues:

https://www.youtube.com/watch?v=2yzboutLwsI

or do you mean the Cmajor pent is the blues scale in the  key  of A
may be we are coming from different schools,Tim.
I've studied in the sixties at swiss jazz school and this was the terminology of Berkley School in Boston.
https://online.berklee.edu/handbooks
Answer: Take a natural minor, remove the 2nd and 6th degrees.
Add a sharpened 4th.
1 - b3 - 4 - #4 - 5 - b7
Tonic - Flattened Mediant - Sundominant - Sharpened Subdominant - Dominant - Flattened Leading Tone.
Answer: You may know the blues line for the bass: do mi so la ta la so mi (ta=b7) for the I7.
Mind that the blue notes are b3 b5 b7 (the major 7 is replaced by the b7, the minor 3 and dim. 5th can be added to the 3 and 5 of the ionic scale)
https://en.wikipedia.org/wiki/Blues_scale
advice: remind some "blues" titles from which you will always be able  to  develop the blues scale.
Comment: This answer is confused and confusing!

How do you build a blues scale?


Parallel Edge detection/handling not working on mxGraph at all

Question: I am having some trouble with mxGraph and parallel edges. My understanding that the parallelEdgeLayout is supposed to find edges between two vertices, and if they overlap, add a spacing. However, I cannot get this to work at all.
I have my vertex and edge styles defined here:
GraphManager.prototype.defineStyles = function () {

    // Vertices
    style = new Object();
    style[mxConstants.STYLE_FONTFAMILY] = "Salesforce Sans";
    style[mxConstants.STYLE_SHAPE] = mxConstants.SHAPE_RECTANGLE;
    style[mxConstants.STYLE_FOLDABLE] = 0;
    style[mxConstants.STYLE_ARCSIZE] = 9;
    style[mxConstants.STYLE_FILLCOLOR] = "#A6B8CE";
    style[mxConstants.STYLE_STROKECOLOR] = "#7591b3";//original
    style[mxConstants.STYLE_STROKEWIDTH] = 1;
    style[mxConstants.STYLE_PERIMETER] = mxPerimeter.RectanglePerimeter;
    style[mxConstants.STYLE_PERIMETER_SPACING] = 2;
    style[mxConstants.STYLE_ROUNDED] = true;
    style[mxConstants.STYLE_SHADOW] = false;
    style[mxConstants.STYLE_ORTHOGONAL] = true;
    this.graph.getStylesheet().putCellStyle(styles.step, style);

    // Edges
    var style = new Object();
    style[mxConstants.STYLE_ROUNDED] = true;
    style[mxConstants.STYLE_EDGE] = mxEdgeStyle.OrthConnector;
    style[mxConstants.STYLE_FONTFAMILY] = "Salesforce Sans";
    style[mxConstants.STYLE_STROKEWIDTH] = 3;
    style[mxConstants.STYLE_OPACITY] = 75;
    style[mxConstants.STYLE_SOURCE_PERIMETER_SPACING] = 5;
    style[mxConstants.STYLE_TARGET_PERIMETER_SPACING] = 5;
    style[mxConstants.STYLE_JETTY_SIZE] = 'auto';
    this.graph.getStylesheet().putCellStyle(styles.edge, style);
}

Then I set up my graph layout. I am using the stackLayout for the main layout of the graph. I have swim lanes set up that are stacked next to each other, and the stackLayout is the only layout that formats these correctly, so would like to use it.
GraphManager.prototype.defineLayout = function (model) {
    // Applies size changes to siblings and parents
    new mxSwimlaneManager(this.graph, false);

    var parallelEdgeLayout = new mxParallelEdgeLayout(this.graph);

    // Creates a stack depending on the orientation of the swimlane
    var layout = new mxStackLayout(this.graph);
    // Makes sure all children fit into the parent swimlane
    layout.resizeParent = true;

    // Applies the size to children if parent size changes
    layout.fill = true;

    // Only update the size of swimlanes
    layout.isVertexIgnored = function (vertex) {
        return !this.graph.isSwimlane(vertex);
    }

    // Keeps the lanes and pools stacked
    var layoutMgr = new mxLayoutManager(this.graph);

    layoutMgr.getLayout = function (cell) {
        if (!model.isEdge(cell) && this.graph.getModel().getChildCount(cell) > 0 &&
            (model.getParent(cell) == model.getRoot() ||
            this.graph.isPool(cell))) {
                layout.fill = this.graph.isPool(cell);

                return layout;
        }
    };

    this.graph.addListener(mxEvent.CELL_CONNECTED, function(sender, evt)
    {
        console.log('Getting Parallels');
        //var model = graph.getModel();
        var edge = evt.getProperty('edge');
        var src = model.getTerminal(edge, true);
        var trg = model.getTerminal(edge, false);

        console.log(src);
        console.log(trg);
        console.log(parallelEdgeLayout.findParallels(src));
        console.log(parallelEdgeLayout.findParallels(trg));

        parallelEdgeLayout.isEdgeIgnored = function(edge2)
        {
            var src2 = model.getTerminal(edge2, true);
            var trg2 = model.getTerminal(edge2, false);

            return !(model.isEdge(edge2) && ((src == src2 && trg == trg2) || (src == trg2 && trg == src2)));
        };

        parallelEdgeLayout.execute(graph.getDefaultParent());
    });
}

I have tried using a compositeLayout with stack layout and parallel edge layout, that didn't work either. The approach above does not work. in the console.logs for my cell connected listener, it will not detect any parallel edges between any vertices even though from this picture:

There are definitely parallel edges... I would greatly appreciate any insight on getting parallel edge handling running on mxGraph. It would be nice to have the graph be able to sort this out on its own. Otherwise, I am going to have to calculate out all the exit and entry points for my edges on vertices, which I would like to avoid.
Answer: Here is an example for running the parallel edge layout:
var graph = new mxGraph(container);
var parent = graph.getDefaultParent();

graph.getModel().beginUpdate();
try
{
    var v1 = graph.insertVertex(parent, null, 'Hello,', 20, 20, 80, 30);
    var v2 = graph.insertVertex(parent, null, 'World!', 200, 150, 80, 30);
    var e1 = graph.insertEdge(parent, null, '', v1, v2);
    var e2 = graph.insertEdge(parent, null, '', v2, v1);
}
finally
{
    graph.getModel().endUpdate();
}

var layout = new mxParallelEdgeLayout(graph);
layout.execute(parent);


Evitar dados duplicados aplicando contador para registo de utilizações

Question: Num formulário simples que grava os seguintes dados:

ID, IP, Data/Hora, Nome, Email, Estado/Cidade.

Quando uma pessoa preenche o formulário, este dados são registrados no banco de dados. Mas se o mesmo utilizador for preencher o formulário novamente, vai ser registado um novo registo, criando uma duplicação de informação.
Como posso controlar este cenário de forma a que se a mesma pessoa usar o formulário com os mesmos dados, ao invés de duplicar o registo, incremente apenas um contador de controlo ?
Comment: Qual o tipo de ligação à base de dados que estás a utilizar? [`PDO`](http://php.net/manual/en/pdo.prepared-statements.php), [`mysql`](http://php.net/manual/en/mysql.examples-basic.php), [`mysqli`](http://php.net/manual/en/mysqli.quickstart.statements.php) ?
Comment: Já experimentou ir ao W3school, a aprender o básico de SQLi ?
E também podes evitar isso pelo SQL, utilizando o Unique.
`IP => $_SERVER['REMOTE_ADDR'];`
`data => date();`
`hora = time();` // podes sempre criar uma função para escrever em portugues.
Answer: A lógica correta é utilizar um destes campos ID, IP, Data/Hora, Nome, Email e Estado/Cidade como um validador. Você pode utilizar uma espécie de validação utilizando o campo Email, por exemplo, como referência. O ip está fora de questão, uma vez que dentro de uma casa 2 ou mais pessoas, podem utilizar o mesmo ip:
Exemplo:
$email = $_POST['email'];

$dupesql = "SELECT * FROM table where (email = '$email')";

$duperaw = mysql_query($dupesql);

if (mysql_num_rows($duberaw) > 0) {

  //FIM DO CADASTRO
  //AVISA QUE JÁ POSSUI UM EMAIL COM ESTES DADOS
}else{

  //CONTINUA O CADASTRO

}

Comment: Removi o trecho que me cita porque eu deletei a resposta.Ok? Não tinha percebido a parte que ele pede pra incrementar um contador
Comment: ok..............
Answer: Primeiramente sugiro que crie uma chave única com os campos que não podem ser duplicados, dessa forma o próprio MySQL evita a duplicidade.
Por exemplo:
UNIQUE INDEX `nome_da_chave` (`nome`, `email`, `cidade`)

Com essa chave criada quando tentar inserir um registro duplicado a consulta vai gerar um erro 1022 SQLSTATE: 23000 (http://dev.mysql.com/doc/refman/5.1/en/error-messages-server.html#error_er_dup_key)
Antes de inserir um novo registro você deve consultar a tabela, se não existir o registro pode inserir, caso contrário atualizar.


Every $A$-mod is flat iff every mod-$A$ is flat.

Question: $\require{AMScd}$ Suppose $A$ is a ring, and we have a SES of left $A$-modules $$0\longrightarrow M'\mathop\longrightarrow\limits^f M \mathop\longrightarrow \limits^g M''\longrightarrow 0$$ where $M''$ is flat. Now let $N$ be any right $A$-module. Show that $$0\longrightarrow N\otimes M'\longrightarrow N \otimes M \longrightarrow N\otimes  M''\longrightarrow 0$$ is exact. Still assuming $M''$ is flat, show also that if $M'$ is flat, then so is $M$, and conversely.
I am sure the second claim follows easily from the nine lemma, but I am stuck with the first one. The hint is to consider a SES $0 \longrightarrow K\longrightarrow F \longrightarrow N \longrightarrow 0$ where $F$ is free and analyze the resulting diagram obtained from tensoring term by term. One gets the following  $$\begin{CD} {}&{}&0&{}&0&{}&0\\
 {}&@VV(*)V@VV(*)V@VVV
  \\
0@>(?)>>
K\otimes M^\prime
  @>>>
  K\otimes M
  @>>>
  K\otimes M^{\prime\prime}
  @>>> 0
  \\
{}& @VVV @VVV @VVV
  \\
0 @>>>
F\otimes M^\prime
  @>>>
 F\otimes M
  @>>>
  F\otimes M^{\prime\prime}
  @>>>
  0
  \\
{}&@VVV @VVV @VVV
  \\
0 @>\rm prove>>
N\otimes M^\prime
  @>>>
  N\otimes M
  @>>>
 N\otimes M^{\prime\prime}
  @>>>
  0
  \\
{}& @VVV @VVV @VVV
  \\
{}&{}&0&{}&0&{}&0
\end{CD}$$
The second row is exact since $F$ is free hence flat, the third column is exact since $M''$ is flat. I want to prove the last row is exact, i.e. that $1_N\otimes f$ is injective, but I am not sure how to proceed. I tried some diagram chasing, but no luck. I am not sure $(?)$ the first row is exact i.e. that $1_K\otimes f$ is injective, since submodules of flat modules needn't be flat. Even assuming $(*)$ $M',M$ are both flat I do not get a diagram that allows the application of the nine lemma. At any rate, I don't want to make this assumption.
Comment: The title seems to be unrelated to the question. Nowhere is that equivalence mentioned.
Comment: Dear Pedro, I went to look for you in chat, but then saw you'd posted your question here.  I will post an answer below.  Cheers,
Comment: @rghthndsd The first claim proves the equivalence stated in the title. If you can think of a better title, please let me know.
Comment: @MattE Thank you very much! I wouldn't mind to get a hint. =)
Comment: Yeah, I've never used snake / 9 lemmas or proved flatness. Can't help ya here.
Comment: @seaturtles I'll delete the comment.
Answer: Try using the snake lemma.
The second row is short exact, and the first row is almost short exact; you can make it short exact on the nose just by replacing $K \otimes M'$ with its image in $K \otimes M$.  (Note that by short exactness of the second row, the map from
$K \otimes M'$ to $F \otimes M'$ factors through this image.)
Now you have a map between two short exact sequences, and the snake lemma gives
a six term exact sequence.  The first two terms will be irrelevant, but the rest of them will give what you want.
[One way to think of this approach is that your (?) , while it generally has a negative answer --- you are right that submodules of flat modules need not be flat, and
it's not hard to find examples where this map won't be injective --- this doesn't matter for the problem at hand!]
[And a general philosophical remark: when you have a diagram like the one you wrote, and you are trying to show that first arrow in a putative s.e.s. is injective, the snake lemma is a natural thing to use, so you want to try to set things up so that you putative s.e.s. is the last three terms of a snake lemma 6-term exact sequence.  This is made systematic by the theory of derived functors, and the theory of Tor is underlying this question.  More precisely, this question is a special case of the general fact that Tor${}^R_i(M,N)$ can be computed using a flat resolution of either $M$ or $N$.]
Comment: OK, I will try this and get back at you. It is almost 2 a.m. here, so I'll be doing this tomorrow. =)
Comment: Dear Matt, I have added what I think is a correct solution. If you have any criticism, let me know.
Answer: I will add the solution here. I am hoping all is correct. We have the diagram (I've removed some irrelevant arrows) $$\begin{CD} {}&{}&{}&{}&{}&{}&0\\
 {}&{}&{}&{}&{}&@VVV
  \\
&{}&
K\otimes M^\prime
  @>>>
  K\otimes M
  @>>>
  K\otimes M^{\prime\prime}
  @>>> 0
  \\
{}& @VV\iota \otimes 1 V @VVV @VVV
  \\
0 @>>>
F\otimes M^\prime
  @>>>
 F\otimes M
  @>>>
  F\otimes M^{\prime\prime}
  \\
{}&@VVV @VVV @VVV
  \\
&{}&
N\otimes M^\prime
  @>>>
  N\otimes M
  @>>>
 N\otimes M^{\prime\prime}
  \\
{}& @VVV @VVV @VVV
  \\
{}&{}&0&{}&0&{}&0
\end{CD}$$
Since the columns are exact, the various $\eta\otimes 1:F\otimes M'\longrightarrow N\otimes M'$ are cokernels for various $\iota\otimes 1$, and the uppermost $0$ is the kernel of the third $\iota\otimes 1$. Thus the snake lemma gives a connecting morphism $\partial$ making the sequence $0\mathop\longrightarrow\limits^{\partial}N\otimes M'\longrightarrow N\otimes M$ exact, as we wanted.


Bootstrap 3: Stack cols only when screen size is less than 500px

Question: I want the bootstrap to stack the columns only when the device size is less than 500px, but the below code stacks them after I reach the extra small threshold which is 768. How can I change that?

  1

  2

  3

Answer: You can change the less file variables
change
screen-sm-min = 768px

to
screen-sm-min = 500px

If you want small devices in general (default < 768px ) You could use
class=" col-sm-4 col-xs-12"

http://getbootstrap.com/css/#grid
Comment: Thanks Sven, is it a wise idea? May it have unpredictable affects laters?
Comment: No screen-sm-min is a variable that is used in a less file to set the col-sm size, when compiled to css it is converted to the pixels you've set. It's the recommended method by bootstrap.
Answer: you are using col-sm it is for small devices, instead of col-sm use col-xs might be it fix your concern.

  1

  2

  3

Comment: When I use `col-xs` then the columns always stay next to each other, they don't pile up.
Comment: Also col xs = <768 not <500


Congruence system

Question: Could you please help me to find out the solution of the system
$$
\begin{array}{ccc}
x&\equiv&2& (\textrm{mod} \ 5) \\
x&\equiv&3& (\textrm{mod} \ 4) \\
x&\equiv&9& (\textrm{mod} \ 6)
\end{array}
$$
Using the Chinese reminder theorem. Here is my progress: the numbers $b_1=2$, $b_2=3$ and $b_3=3$ are particular solutions of each congruence, respectively. We compute
$$
y_1= 6\cdot4=24, y_2= 5\cdot6=30, y_1= 5\cdot4=20
$$
The theorems guarantees that the following congruences have solution
$$
24x_1\equiv1 \ (\textrm{mod} \ 5), 30x_2\equiv1 \ (\textrm{mod} \ 4),
20x_3\equiv1 \ (\textrm{mod} \ 6),
$$
ie.
$$
4x_1\equiv1 \ (\textrm{mod} \ 5), 2x_2\equiv1 \ (\textrm{mod} \ 4),
2x_3\equiv1 \ (\textrm{mod} \ 6),
$$
I can get $x_1=4$, but what about $x_2$ and $x_3$?
The answer, according to Wolfram Alpha is $x\equiv27 \ (\textrm{mod} \ 60)$
Answer: The congruence $2x_2\equiv1\pmod4$ has no solutions as an odd number cannot be a multiple of $2$.
One needs to decompose the system so that the moduli (in our case $5, 4$, and $6$) are mutually prime, which is the hypothesis of Chinese Remainder Theorem.
Now observe that the congruence $x\equiv9\equiv3\pmod6$ is equivalent with $$x\begin{cases}\equiv0\pmod3\\\equiv1\pmod2\end{cases},$$ by Chinese Remainder Theorem. Moreover, the congruence $x\equiv1\pmod2$ is implied by another congruence $x\equiv3\pmod4$. So we can reduce the original system to
$$
x\begin{cases}\equiv2\pmod5\\\equiv3\pmod4\\\equiv0\pmod3\end{cases}.
$$
I suppose you can continue from here.

Hope this helps.
Answer: You have $$
\begin{array}{ccc}
x&\equiv&2& (\textrm{mod} \ 5) \\
x&\equiv&3& (\textrm{mod} \ 4) \\
x&\equiv&9& (\textrm{mod} \ 6)
\end{array}
$$
$x=5k+2$
So $5k+2 \equiv 3 (mod 4)$
$5k \equiv 5 (mod 4)$
So $k \equiv 1 (mod 4)$
Or $k=4m+1$
$\therefore x=5(4m+1)+2$
Or $x=20m+7$
Now, $20m+7 \equiv 9 (mod 6)$
$\Rightarrow 20m \equiv 2 (mod 6)$
$20m \equiv 20 (mod 6)$ (adding 18)
So $m \equiv 1 (mod 3)$
Or $m=3p+1$
$x=20(3p+1)+7$
$x=60p+27$
$\therefore x \equiv 27 (mod 60)$
Hope this helps :)
Comment: This is a long but effective way of solving a system of congruences not more than 4 otherwise it becomes tedious.
Comment: I needed to use Chinese remainder theorem
Comment: @MarcosPaulo Above does use CRT, but *pairwise* $(2\,$ at a time). It solves the first pair to get the equivalent congruence $\,x\equiv 7\pmod{20},\,$ then it solves that paired with last $\,x\equiv 9\pmod{6}\,$ to get $\,x\equiv 27\pmod{60}.\ $ This is a common convenient way to apply CRT.

Congruence system


Function para guardar script ? JAVASCRIPT

Question: Tenho um script e gostaria apenas de coloca-lo dentro de uma function porque não é boa prática deixar scripts "soltos", então gostaria de uma função que não modifique em nada o meu script, apenas sirva de "deposito" e que meu script continue funcionando e sendo reconhecido perfeitamente pelo HTML.

var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
    // The type of chart we want to create
    type: 'line',

    // The data for our dataset
    data: {
        labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
        datasets: [{
            label: 'My First dataset',
            backgroundColor: 'rgb(255, 99, 132)',
            borderColor: 'rgb(255, 99, 132)',
            data: [0, 10, 5, 2, 20, 30, 45]
        }]
    },
    options: {}
});

<title></title>

<canvas id="myChart"></canvas>

Answer: Você pode definir funções de várias formas dentro do javaScript e fazer a chamada depois, primeiramente usando a declaração de função, que é carregado antes de executar
function soma(a, b){
    return a + b
}

Também pode utilizar uma function expression que só executa depois da declaração
const sub = function(x,y){
    return x - y
}

Também temos funções arrow
let dobro = (a) => {
    return 2*a;
}

Podemos inclusive atribuir funções a variáveis, normalmente utilizamos const, para que elas não sejam alteradas. Você pode deixar seu código em algo equivalente á:
function myChart(){
 var ctx = document.getElementById('myChart').getContext('2d');
 var chart = new Chart(ctx, {
    // The type of chart we want to create
    type: 'line',

    // The data for our dataset
    data: {
        labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
        datasets: [{
            label: 'My First dataset',
            backgroundColor: 'rgb(255, 99, 132)',
            borderColor: 'rgb(255, 99, 132)',
            data: [0, 10, 5, 2, 20, 30, 45]
        }]
    },
    options: {}
 });
}

myChart(); //chamada de função dentro do script

Comment: Obrigado, era isso que procurava!