'new' keyword in getter > performance hit?

Question: I have the following code:
public class Character
{
    public Vector2 WorldPixelPosition
    {
        get { return Movement.Position; }
    }
    public Vector2 WorldPosition
    {
        get { return new Vector2(Movement.Position.X / Tile.Width, Movement.Position.Y / Tile.Height); }
    }
    public Vector2 LevelPosition
    {
        get { return new Vector2(WorldPosition.X % Level.Width, WorldPosition.Y % Level.Height); }
    }
}

Now somewhere else in my code, I make about 2500 calls in a loop to Character.LevelPosition.
This means that per update-cycle, 5000 'new' Vector2s are being made, and on my laptop, it really drops the framerate.
I have temporarily fixed it by creating
var levelPosition = Character.LevelPosition;

before I initiate the loop, but I kinda feel its ugly code to do this everytime I come across a similar situation. Maybe it -is- the way to go, but I want to make sure.
Is there a better or commonly accepted way to do this?
I'm using the XNA-Framework, which uses Vector2's.
Comment: If the return value of the property doesn't change, and performance tests show that it's faster to call it once and put this value into a local var, then by all means do so!
Comment: Is `Vector2` a `class`? There's not much code here but it looks like it could (should?) be a `struct`, in which case it should perform way better. In any case, the fix you mention is a totally valid optimization since you know for a fact what exactly is slowing you down.
Comment: Oh, I'm sorry. I'm working in the XNA-Framework, I should've mentioned.
Comment: Do you really need to do that 2500 times? Can't it be cut down to for example the visible area?
Comment: Actually, I already cut it to the visible area. I'm drawing tiles from a tile-based game, offset by the players position.
Comment: This would be a good time for you to read and listen to [Understanding XNA Framework Performance](http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=16477).
Answer: From what I understand, you should avoid allocating lots of objects from the heap in XNA, because that causes bad performance. But since Vector2 is a struct, we're not allocating anything on the heap here, so that shouldn't be the problem here.
Now, if you have tight loop, like you do, in a performance-critical application, like a game, you will always have to think about performance, there is no going around that.
If we look at the code for LevelPosition, you call the getter for WorldPosition twice and probably some more getters. The getter for WorldPosition probably calls few other getters. (It's hard to say what exactly is going on without having the source, because getter call and field access look exactly the same.)
Call to a getter, which is actually just a call to a special method, is usually pretty fast and can be even faster if the compiler decides to use inlining. But all the calls add up together, especially if you call them in a loop.
The solution for this is some sort of caching. One option would be to make LevelPosition a field and devise a system to update it when necessary. This could work, but it could also actually hurt performance if you need to update it more often than you read it.
Another solution is, as you discovered, to cache the result in a local variable. If you know that this is correct, i.e. that the value of the property won't change during the execution of the loop, then that's awesome! You solved your performance problem and you did it with only a single line of code that's easily understandable to any programmer. What more do you want?
Let me restate that. You found a solution to your performance problem that:

works
is simple to implement
is easy to understand

I think such solution wold be very hard to beat.
Comment: Alright, this is also a very clear answer. I will play around with these solutions some more and figure out what works best for me. Thank you too!
Answer: Creating many objects in a loop may be an expensive operation (*). Maybe if would help to create the Vector2 in advance (for example when the coordinates change) and in the future just change the coordinates.
Example:
public class Character
{
    private Vector2 m_worldPosition = new Vector2(0, 0);
    private Vector2 m_levelPosition = new Vector2(0, 0);

    ....

    public Vector2 WorldPosition
    {
        get
        {
            m_worldPosition.X = ...;
            m_worldPosition.Y = ...;
            return m_worldPosition;
        }
    }

    public Vector2 LevelPosition
    {
        get
        {
            m_levelPosition.X = ...;
            m_levelPosition.Y = ...;
            return m_levelPosition;
        }
    }
}

EDIT
The same should be done for the LevelPosition property as well. See modified source code.
(*)
Tim Schmelter pointed me to this question with a detailed discussion about the impact of instantiating objects. I have rephrased my initial sentence that object creation is always expensive. While creating objects is not always an expensive operation, it may still slow down performance in certain cases.
Comment: When talking about speed issues, object creation is always a good starting point for speeding things up. Glad I could help.
Comment: @ThorstenDittmar: It was only an assumtion ("might have...").
Comment: I think this is a great idea. Actually it might have increased its performance over my original solution. Thank you!
Comment: I agree you should be able to store the values, and only update them when necessary.
Comment: @ThorstenDittmar: Your premise that creating objects is always expensive is too categorical. http://stackoverflow.com/questions/2105011/is-it-expensive-to-create-objects-in-net It sounds as if you'd recommend to avoid objects wherever possible, then you're using the wrong language.
Comment: I don't think this will help anything. `Vector2` is a `struct`, so creating it is very cheap. The performance hit here probably comes from the calculations and copying, which you did not improve at all.
Comment: @Tim Schmelter: Not at all! I'm in no way against objects or object orientation! I just suggested that in the OP's situation it might be much faster instantiating only once and the modifying instead of instantiating every time - and as he said it worked. In the link you provided, please refer to Jon Skeet's answer, especially the following: "I strongly suspect the performance hit will be insignificant, but if you are using this in a tight loop, it may not be." The OP is creating 5000 objects in a tight loop and it *was* lowering performance significantly.
Comment: @svick: Well, why would the OP then say that it actually improved the performance a lot?
Comment: @Tim: Well, in the end the OP is happy with this solution and it is still proper class design - so we shouldn't be nitpicking. I agree with you that instantiating is *not always* expensive, but it seem that in this case it was.
Answer: You can make a private field to store the value and not compute it each time. You can make a method to update the private fields and subscribe for the Movement.Position changes in some way. This way the value will be computed only once when position changes.
Comment: Subscribing might work, but isn't that a whole lot of overhead everytime I come across a similar situation?
Comment: performance overhead or coding overhead? I doubt it is performance overhead since you need to update the values anyway. In coding... it certainly is. Maybe you can use some generic base class to ease the situation.


LinkedList with 2 time data

Question: I have to give 2 time data to a linkedlist from a txt file.
but i can't fill it in.
StreamReader sr;
public void FileReader(string file, LinkedList<Task> Tasks)
{
    string splitter= ".";
    int TaskIndex= 0;
    sr = new StreamReader(file);
    LinkedList<Task> data = new LinkedList<Task>();

    while (!sr.EndOfStream)
    {
        string tempString = sr.ReadLine();
        if (splitter== tempString)
        {
            TaskIndex++;
            Tasks.Add(data);

        }
    }
    sr.Close();
}

public class Task
{
    public TimeSpan FullTime= new TimeSpan(0, 24, 0, 0);
    public TimeSpan TaskLength { get; set; }
    public TimeSpan Deadline{ get; set; }
    public int Penalty{ get; } = 50000;
    public Task(TimeSpan TaskLength, TimeSpan Deadline)
    {
        this.TaskLength= TaskLength;
        this.Deadline= Deadline;
    }
}

And the txt: The first 2 data is the TaskLengths hour and minute the second 2 is the deadlines hour and minute, every line is a task

2,30,5,0.
4,0,16,0.
1,0,2,0.
6,0,14,0.
3,30,10,0.
2,0,22,0.
Comment: You're getting close votes so I think you should clarify what you mean by "but i can't fill it in".  Looking at your code and your data I'm guessing by the end of your `FileReader` method `data` is empty.  Is that correct?
Comment: data has an error: cannot convert from 'LinkedList' to 'Task'
Comment: You never create a `Task` instance and are instead adding one `LinkedList` (`data`) to another (`Tasks`).  You need to pick one list to use, either `data` or `Tasks`, and add `Task`s to it.
Answer: It sounds like what you want to do is read each line from the file, split that line on the comma character (and get rid of the period since every line is a task), parse the numbers from the line into integers, create two TimeSpan objects from the numbers, create a Task object from the two TimeSpan objects, and then add that Task to a LinkedList<Task>.
If that's the case, then here's a sample method that you can pass a file name to and which will return a LinkedList<Task> from the contents of the file:
public LinkedList<Task> GetTasksFromFile(string filePath)
{
    // This will hold our results from reading the file lines into Tasks
    var tasks = new LinkedList<Task>();

    // Loop through each line in the file
    foreach (string line in File.ReadLines(filePath))
    {
        // Split the line on the comma and period characters so we get separate values
        string[] parts = line.Split(new[] {'.', ','},
            StringSplitOptions.RemoveEmptyEntries);

        // These will hold the parsed values from each line of text in our file
        int lengthHour;
        int lengthMinute;
        int deadlineHour;
        int deadlineMinute;

        // int.TryParse will try to convert a string to an int, and will return
        // true if successful. It will also set the 'out' parameter to the result.
        // We do this on each part from our line of text
        // (after ensuring that there are at least 4 parts)
        if (parts.Length > 3 &&
            int.TryParse(parts[0], out lengthHour) &&
            int.TryParse(parts[1], out lengthMinute) &&
            int.TryParse(parts[2], out deadlineHour) &&
            int.TryParse(parts[3], out deadlineMinute))
        {
            // If our parsing succeeded, create a new task
            // with the results and add it to our LinkedList
            TimeSpan length = new TimeSpan(lengthHour, lengthMinute, 0);
            TimeSpan deadline = new TimeSpan(deadlineHour, deadlineMinute, 0);
            Task task = new Task(length, deadline);
            tasks.AddLast(task);
        }
    }

    // Return our linked list back to the caller
    return tasks;
}

LinkedList with 2 time data


How do I get the square root of a complex number?

Question: If I'm given a complex number (say $9 + 4i$), how do I calculate its square root?
Comment: The answers of using de Moivre's formula are correct but it may also be instructive to try and find the square roots directly using $(a+bi)^2 = 9 + 4i$ (say) and solve for $a$ and $b$ or even just use the quadratic formula directly, which will give you an appreciation for why we use de Moivre's formula.
Answer: This is a three parts post. The first part was written by user Did; it provides a formula and some brief comments on it. The second part was written by user Hans Lundmark; it provides a geometric way to understand the formula. The third part was written by user t.b.; it provides some explanatory pictures and some brief comments on them.

(Did) If one is able to compute the square root of every positive real number and the modulus of every complex number, a nice formula for the principal square root $\sqrt{z}$ of $z$ is
$$
\sqrt{z}=\sqrt{r}\frac{z+r}{|z+r|},\quad r=|z|.
$$
Try to prove it and you will see, it works...
The principal square root is the one with a positive real part. The only case when the formula fails is when there is no principal square root, that is, when $z$ is a negative real number.
No sine or cosine is involved, one does not even need to solve second degree polynomials, one just uses squares and square roots. For example, for $z=9+4\mathrm{i}$,
$$
\sqrt{z}=\frac{9+\sqrt{97}+4\mathrm{i}}{\sqrt{2(9+\sqrt{97})}}.
$$

(HL) There's a geometric way of understanding the formula in Did's answer. To find a square root of a given complex number $z$, you first want to find a complex number $w$ which has half the argument of $z$ (since squaring doubles the argument). Compute $r=|z|$ and let $w = z+r$; thus $w$ lies $r$ steps to the right of $z$ in the complex plane. Draw a picture of this, and it should be clear that the points $0$, $z$ and $w$ form an isosceles triangle, from which one sees that the line from $0$ to $w$ bisects the angle between the real axis and the line from $0$ to $z$. In other words, $w$ has half the argument of $z$, as desired. Now it only remains to multiply $w$ by some suitable real constant $c$ so that $|cw|^2 = |z|$; then we will have $(cw)^2=z$ and hence $cw$ is a square root of $z$. Obviously, $c=\pm\sqrt{|z|}/|w|$ will do the trick, so this method only fails when $w$ happens to be zero, i.e., if $z$ is a negative real number.

(t.b.) Following a suggestion of Did, I take the liberty of adding two pictures I originally posted as a separate answer, but it seemed better to have them here:

Here's the picture for $z = 9 + 4i$:

Remark: The construction of the square roots is geometrically exact. That is to say, they were constructed using straightedge and compass only. I decided to hide the construction, as it seems rather obfuscating the intended illustration than adding to it. Nevertheless, I suggest taking a moment and thinking about how you would achieve the geometric construction.

Added (t.b.)
Here's the construction I used: Intersect the circle around $z/2$ through $z$ with the tangent to the unit circle orthogonal to $z$. Then $h^2 = (|z|-1)\cdot 1$ and thus the red circle has radius $\sqrt{|z|}$. It remains to intersect the red circle with the angular bisector of the $x$-axis and $z$ which I constructed using the process Hans described in his part of the post.

The pictures were created using GeoGebra.
Comment: Hans: Following a suggestion of @Didier I added two pictures I originally posted as a separate answer. It seemed more reasonable to have them in one answer. I hope you don't mind.
Comment: @Hans: very true. To reduce confusion, I deleted my comment :)
Comment: @legends2k Right, the formula gets even simpler... Thanks for noticing this. Since you checked the formula, I cancelled the mention "unless I am mistaken".
Comment: @Hans: Yes. This is a question where a picture would be useful (if only I knew how to draw pictures on MSE (and if I had more time on my hands)). Thanks.
Comment: Since you can't see it on my deleted post, here's @Didier's original comment:
"Theo and @Hans: What do you think about the idea of making one single post from our three complementary answers? (Re reputation, if that matters, either one of you may sign the resulting post, I really do not care.)"  I refrain from adding Didier's answer in since it seems a bit too aggressive an edit to me, but I'd be strongly in favor of doing it.
Comment: Hans, @Theo: Done (at the risk of being seen as aggressive...). As soon as Hans says he is OK with the expanded version of his post, I will delete mine.
Comment: Hans, @Didier: I added a little bit to the aggression since I think the people at [GeoGebra](http://www.geogebra.org/cms/) deserve being mentioned prominently for creating such a nice and free tool.
Comment: @Didier: That's fine with me. As far as rep is concerned, I don't care either. We could make this answer CW.
Comment: @Theo: Nice pictures! :)
Comment: @Hans: Thanks! Glad you like them.
Comment: I've made the answer CW.
Comment: Hans, @Theo: Deleted my answer. Thanks to both of you.
Comment: @Theo: This conversation is not going to make much sense to anyone else after we both edited our comments almost at the same time... ;)
Comment: @Did Thanks for clearing that up, I was getting confused for sometime looking at it.
Comment: Wow. Just wow. Loved the first simple answer. :-) Thank you so much
Comment: As the pictures show, this formula bisects the argument of z and rescales to have the appropriate modulus. Does the fact that we can't trisect angles with a compass and ruler suggest that there's no analogous formula for $\sqrt[3]{z}$?
Comment: @NickBoshaft: I rolled back your edit. The issue is with $z$ on the negative real **axis**, and for those $z$ the formula really breaks down. Your comment along with the edit seemed to indicate that you were thinking of $z$ in the left half **plane** (but not on the negative real axis), and for those $z$ there is indeed no problem (but also no need for a separate drawing).
Comment: Awesome answer! An extra thought on the geometric construction: If z is located within the unit circle, seems you can use a similar construction method, but would need to swap the roles of the circles to get an intersection.  Using the the intersection of the tangent to circle around the origin radius |z| (instead of 1) with the circle around 1/2 through 1 (instead of around z/2 through z).
Comment: I would say one must be careful, the first formula  collapses at $z=-1$.
Answer: The square root is not a well defined function on complex numbers. Because of the fundamental theorem of algebra, you will always have two different square roots for a given number. If you want to find out the possible values, the easiest way is probably to go with De Moivre's formula, that is, converting your number into the form $r(\cos(\theta) + i \sin(\theta))$, and then you will get $(r(\cos(\theta)+ i \sin(\theta)))^{1/2} = ±\sqrt{r}(\cos(\theta/2) + i \sin(\theta/2))$.
Comment: The "two different square roots" issue applies to real numbers as well; it's just that in that case there's a consensus on which one is the "principal" square root.
Comment: Oh, and I am afraid I must object to the assertion that going with De Moivre's formula would be *the easiest way*.
Comment: @user1374 There is also a consensus about which square root of a complex number is the principal square root--at least for *almost every* complex number... See my answer.
Comment: The reason for preferring positive square roots of positive real numbers is practical. For instance, the distance formula in any finite number of dimensions is a positive square root - namely, for two points, the distance apart is the square root of the sum of the squares of the respective differences of coordinates. It also ensures that the square-root function is the simple function we all know, and so we may and do speak naturally of THE square root of a number a simpler idea than otherwise... In fact, I can think of no argument for why one would want to do anything different than this.
Comment: @Did What's the rational basis for having positive square roots as the principal square roots instead of negative square roots?
Comment: @DougSpoonwood You might want to explain what you have in mind when you call some complex numbers *positive* and some others *negative*.
Answer: Here is a direct algebraic answer.
Suppose that $z=c+di$, and we want to find $\sqrt{z}=a+bi$ lying in the first two quadrants.  So what are $a$ and $b$?
Precisely we have
$$a=\sqrt{\frac{c+\sqrt{c^{2}+d^{2}}}{2}}$$ and
 $$b=\frac{d}{|d|}\sqrt{\frac{-c+\sqrt{c^{2}+d^{2}}}{2}}.$$  (The factor of $\frac{d}{|d|}$ is used so that $b$ has the same sign as $d$) To find this, we can use brute force and the quadratic formula.  Squaring, we would need to solve $$a^2-b^2 +2abi=c+di.$$  This gives two equations and two unknowns (separate into real and imaginary parts), which can then be solved by substitutions and the quadratic formula.
I hope that helps!
Comment: This is actually a very useful formula that people don't use often enough.  Universally, this can be written as √(A+B)=(√(A+√(A²-B²))+sgn(B)√(A-√(A²-B²)))/√(2).  This can be used to take complex square roots as well as determine if a number, such as 6+2√(5), has a simple square root. √(6+2√(5)) can now be rewritten as √(5)+1.  Some numbers, like 2√(5)+7, don't have a simple square root and return something lengthy like in this case (√(7+√(29))+√(7-√(29))/√(2).
Comment: Better add and say that you want d/|d|=1 for d=0, right?
Comment: @MostowskiCollapse what do you mean by that? Isn't it impossible for $d=0$? SO how can $\frac{d}{|d|} =1$?
Comment: if $d=0$ then $z$ is real
Comment: For fast computation, you can use b=d/(2a), which even works for positive real numbers (but not negative reals). This with the formula for a give the fastest algorithm I've found for computing.
Comment: @Eric Naslund, the $\frac{d}{|d|}$ point is very important and interesting, but I haven't seen this being used anywhere else in any topic of math. The closest thing I get is $(-1)^n$ when determining the final terms of series with alternating signs. Where else is $$\frac{d}{|d|}$$ used? Perhaps I will make a post asking for examples.
Answer: You can also do following (technique often advised at school) :

Let's write $z² = 9 + 4i$ with $z = a + bi$.  The goal is to find $z$
Thus we have  $(a + bi)² = 9 + 4i$ and if you expend we get $a²+ 2abi - b² = 9 + 4i$
If you identify the real and imaginary parts, you obtain :
$a²-b² = 9$   (1)
and
$2ab= 4$   (2)
Now, as $z² = 9 + 4i$, the modulus of $z²$ and $9 + 4i$ are equal so we can write :
$a²+b² = \sqrt{9²+4²}$
$a²+b² = \sqrt{97}$   (3)
Now find $a$ and $b$ with the the equations (1) , (2) and (3) :
(1) + (3) $\Leftrightarrow 2a² = 9+\sqrt{97} $
so $a = \sqrt{\frac{1}{2}(9+\sqrt{97})} $  or  $a = - \sqrt{\frac{1}{2}(9+\sqrt{97})} $
With equation (2) and the previous result you can now find $b$ :
$2ab= 4$
$b= 2/a$
so $b = 2\sqrt{\frac{2}{9+\sqrt{97}}} $  or  $b = - 2\sqrt{\frac{2}{9+\sqrt{97}}} $
The answer is : $z = \sqrt{\frac{1}{2}(9+\sqrt{97})} + 2i\sqrt{\frac{2}{9+\sqrt{97}}}  $ or $z = - \sqrt{\frac{1}{2}(9+\sqrt{97})} - 2i\sqrt{\frac{2}{9+\sqrt{97}}}  $
Comment: Shouldn't you get 4 roots for a=+- and b=+-. How did you eliminate two choices??
Comment: @HarshitJoshi: As  you have $2ab=4>0$, you *know* $a$ and $b$ have the same sign, whence only two square roots, which arre opposite .
Comment: Why is the modulus of z = a^2 + b^2 instead of sqr( a^4 + b^4 + 4*a^2*b^2 )?
Comment: @Mirte modulus is square root of $a^2+b^2$, or $\sqrt{a^2+b^2}$.
Answer: One way is to convert the complex number into polar form. For $z = re^{i\theta}$, $z^2 = r^2 e^{i(2\theta)}$. So to take the square root, you'll find $z^{1/2} = \pm \sqrt{r} e^{i\theta/2}$.
Added: Just as with the nonnegative real numbers, there are two complex numbers whose square will be $z$. So there are two square roots (except when $z = 0$).
Answer: Claim 1. Suppose $b\neq 0$. Then the two roots to the equation $x^2 = a +bi$ are: $$\pm\frac{\sqrt{2}}{2}\left(\sqrt{\sqrt{a^{2}+b^{2}}+a}+\mathrm{i}\frac{b}{\left|b\right|}\sqrt{\sqrt{a^{2}+b^{2}}-a}\right).$$

Claim 2. Suppose $b>0$. Then:
(a) The two roots to the equation $x^2 = a +bi$ are $$x = \pm\frac{\sqrt{2}}{2}\left(\sqrt{\sqrt{a^{2}+b^{2}}+a}+\textrm{i}\sqrt{\sqrt{a^{2}+b^{2}}-a}\right). $$
(b) And the two roots to the equation $x^2 = a -bi$ are $$x=\pm\frac{\sqrt{2}}{2}\left(\sqrt{a+\sqrt{a^{2}-b^{2}}}-\textrm{i}\sqrt{a-\sqrt{a^{2}-b^{2}}}\right).$$

Proof of Claim 1. \begin{alignat*}{1}
 & \left[\pm\frac{\sqrt{2}}{2}\left(\sqrt{\sqrt{a^{2}+b^{2}}+a}+\mathrm{i}\frac{b}{\left|b\right|}\sqrt{\sqrt{a^{2}+b^{2}}-a}\right)\right]^{2}\\
=\  & \frac{1}{2}\left[\sqrt{a^{2}+b^{2}}+a-\left(\sqrt{a^{2}+b^{2}}-a\right)+2\mathrm{i}\frac{b}{\left|b\right|}\sqrt{\left(\sqrt{a^{2}+b^{2}}+a\right)\left(\sqrt{a^{2}+b^{2}}-a\right)}\right]\\
=\  & \frac{1}{2}\left(2a+2\mathrm{i}\frac{b}{\left|b\right|}\sqrt{a^{2}+b^{2}-a^{2}}\right)=a+\mathrm{i}\frac{b}{\left|b\right|}\left|b\right|=a+\mathrm{i}b.
\end{alignat*}

Proof of Claim 2. \begin{alignat*}{1}
\textbf{(a)} \ & \left[\pm\frac{\sqrt{2}}{2}\left(\sqrt{\sqrt{a^{2}+b^{2}}+a}+\mathrm{i}\sqrt{\sqrt{a^{2}+b^{2}}-a}\right)\right]^{2}\\
= \ & \frac{1}{2}\left[\sqrt{a^{2}+b^{2}}+a-\left(\sqrt{a^{2}+b^{2}}-a\right)+2\mathrm{i}\sqrt{\left(\sqrt{a^{2}+b^{2}}+a\right)\left(\sqrt{a^{2}+b^{2}}-a\right)}\right]\\
= \ & \frac{1}{2}\left(2a+2\mathrm{i}\sqrt{a^{2}+b^{2}-a^{2}}\right)=a+\mathrm{i}\sqrt{b^{2}}=a+\mathrm{i}b.
\end{alignat*}
\begin{alignat*}{1}
\textbf{(b)} \  & \left[\pm\frac{\sqrt{2}}{2}\left(\sqrt{a+\sqrt{a^{2}-b^{2}}}-\mathrm{i}\sqrt{a-\sqrt{a^{2}-b^{2}}}\right)\right]^{2}\\
= \ & \frac{1}{2}\left[a+\sqrt{a^{2}-b^{2}}+a-\sqrt{a^{2}+b^{2}}-2\mathrm{i}\sqrt{\left(a+\sqrt{a^{2}-b^{2}}\right)\left(a-\sqrt{a^{2}-b^{2}}\right)}\right]\\
= \ & \frac{1}{2}\left[2a-2\mathrm{i}\sqrt{a^{2}-\left(a^{2}-b^{2}\right)}\right]=a-\mathrm{i}\sqrt{b^{2}}=a-\mathrm{i}b.
\end{alignat*}
Comment: Except when b < 0 the last line isn't true because sqrt(b^2) isn't equal to b. For b < 0 replace + i... by -i... Also typo in second to last line: r + a - (r + a) should be r + a - (r - a), where r = sqrt(a^2 + b^2).
Comment: @Wout: Thanks for spotting that error! I've now corrected, hopefully it's now good.
Comment: Better say b>=0, so that we have sqrt(-1)=i as a first solution.
Answer: Here's a useful picture from Wikipedia (ref). This helps visualise some comments above about having two square roots of most complex numbers.
The horizontal plane is the original complex number $z$.
The vertical axis is the real part of the square root(s) of $z$. (Note how there are two solutions for most numbers, i.e. all except zero.)
The colour is the angle of a square root of $z$, where red is 0° i.e. the real axis, cyan is $\pm$180° and so on.
The principal square root is the top half of the surface.
The see how the imaginary part behaves, rotate the surface 180° about the vertical axis. (Of course, the colours don't rotate, they stay where they are. More precisely, the magenta part will go to the bottom, and the green to the top, while the yellow and blue will stay as they are.)
Answer: SQUARE ROOT OF A BINOMIC COMPLEX NUMBER
The number $\sqrt{a+bi}$ is a complex (or complex) $x+yi$ such that: $a+bi=(x+yi)^{2}$
So: $a+bi=(x^{2}-y^{2})+2xyi\rightarrow \left.
x^{2}-y^{2}=a \atop
2xy=b
\right\}$ Solving this system, and taking into account, to solve the bi-square equation, that $\sqrt{a^{2}+b^{2}}\geq a$:
$$\left.
y=\dfrac{b}{2x} \atop
4x^{4}-4ax^{2}-b^{2}=0
\right\}\rightarrow \left.
x^{2}-y^{2}=a \atop
x^{2}=\dfrac{a+\sqrt{a^{2}+b^{2}}}{2}
\right\}\rightarrow \left.
x^{2}=\dfrac{a+\sqrt{a^{2}+b^{2}}}{2} \atop
y^{2}=\dfrac{-a+\sqrt{a^{2}+b^{2}}}{2}
\right\}$$
Now, the equation $2xy=b$ tells us that the product $xy$ has the same sign as $b$. Therefore, if $b>0$, $x$ and $y$ have the same signs, and if $b<0$, they have different signs.
$$b\geq 0\rightarrow \sqrt{a+bi}=\pm \left( \sqrt{\dfrac{a+\sqrt{a^{2}+b^{2}}}{2}}+i\sqrt{\dfrac{-a+\sqrt{a^{2}+b^{2}}}{2}}\right)$$
$$b<0\rightarrow \sqrt{a+bi}=\pm \left( \sqrt{\dfrac{a+\sqrt{a^{2}+b^{2}}}{2}}-i\sqrt{\dfrac{-a+\sqrt{a^{2}+b^{2}}}{2}}\right)$$
In practice, these formulas are not used, but the process is followed.
Also, it is highly recommended to pass it to polar.
Answer: $x^2 - y^2 +2ixy$ = write the complex no.
$x^2 - y^2$ = write the real value---------(1)
$2xy$ = write the imaginary  value------(2)
from equation (1) and (2)
$x^2 + y^2 = \sqrt{(x^2 - y^2)^2 +  4x^2y^2}$
you will get $x^2 + y^2 = ?$ -------(3)
from equation (1) and (3)
you will get the value of $x$ and $y$
Answer: You can write each complex number $a+bi$ as $re^{i\theta}$ for some $r$ and $\theta$. To take the square root of that would be
$$\sqrt{a+bi}=\sqrt{r}e^{\frac{i\theta}{2}}$$
which answers your question.
Answer: ok, Would someone please tell me if I'm wrong about this.
We want $\pm\sqrt{a+bi}.$  $($This kind of square root is not well-defined without the $\text{"}{\pm}\text{''}.)$
If $a+bi = r(\cos\theta+i\sin\theta)$ then $\displaystyle\tan\frac\theta2 = \frac{\sin\theta}{1+\cos\theta} = \frac b {\sqrt{a^2+b^2}+a},$ so
$$
\sin\frac\theta2 = \frac b{\text{something}} \text{ and } \cos\frac\theta 2 = \frac{\sqrt{b^2+a^2}+a}{\text{something}}
$$
where $\text{"something''}$ makes $\sin^2+\cos^2=1,$ so the efficient way to think about this is the tangent half-angle formula. Or is there a more efficient way?
Answer: Write $(a+bi)^2 =  9+4i$. Then $a^2-b^2 +2abi = 9+4i$.
By comparison of coefficients,
$2ab = 4$ and $a^2-b^2 = 9$.
Thus $ab=2$ and $a^2 = 9 +b^2$.
Setting $a = 2/b$ with $b\ne 0$ gives $4/b^2 = 9 + b^2$ and so $4 = 9b^2 + b^4$, i.e., $b^4 + 9b^2 -4 = 0$.
Solve $x^2 + 9x-4=0$, where $x=b^2$. Solutions are
$x_{1,2} = \frac{-9\pm\sqrt{9^2-4\cdot 1\cdot (-4)}}{2\cdot 1} = \frac{-9\pm\sqrt{97}}{2}$. Solutions are $b_{1,2,3,4} = \pm\sqrt{\frac{-9\pm\sqrt{97}}{2}}$. This gives the corresponding values $a_{1,2,3,4}$. All solution pairs are real-valued.
Answer: A formula that works for $z$ not on the negative real axis:
$$\bbox[5px,border:2px solid red]
{\sqrt{z} = \pm \frac{(z + |z|)}{\sqrt{2(\mathcal{Re}\ {z}+|z|)}}
}$$
Example:
$$\sqrt{3 + 4i}= \pm \frac{3 + 4 i + 5}{\sqrt{2(3+5)}}=\pm(2+i)$$

$\bf{Added:}$ The colored  triangles are similar. Conclude  the complex numbers $\frac{\mathcal{Re}\, z + |z|}{2}$, $\frac{z+|z|}{2}$, $z$ form a geometric progression, and so
$$z\cdot \frac{\mathcal{Re}\, z + |z|}{2} =\left(\frac{z+|z|}{2}\right)^2$$

$\bf{Added:}$ Formally
$$\sqrt{z} = \frac{z + \sqrt{z w}}{\sqrt{z}+\sqrt{w}}= \frac{z + \sqrt{z w}}{\sqrt{z + w + 2 \sqrt{z w}}}$$
in fact,  a true equality:  whenever we choose a determination for $\sqrt{z w}$, and then for $\sqrt{z + w + 2 \sqrt{z w}}$, the formula gives a determination for $\sqrt{z}$.  Now the idea is to consider a $w$ that "simplifies" the problem, in our case it is $\color{red}{w = \bar z}$, so the radicals are real radicals.


Qual é a diferença entre usar #include "stack.h" ou usar a declaracao dessa class ?

Question: Tendo estas duas classes, em dois ficheiros .h distintos.
um.h
class um {
  //(...)
};

dois.h
#include "um.h" //opcao 1

class um; //opcao 2

class dois{
  public:
    void f1(um * p);
};

Qual a diferença entre estas duas opções e qual a mais indicada?
Answer: Não são opções, já que não fazem a mesma coisa.
Ao fazer #include "um.h" você de fato inclui o arquivo de cabeçalho da classe (supostamente já definida), de forma que a partir de então (no local onde está incluindo e recursivamente, se este local também for um cabeçalho) você tem acesso à todos os elementos da interface dela. Isto é, você pode referenciar um atributo ou método dessa classe - claro, dependendo do escopo declarado e de onde a referência está sendo realizada.
Ao fazer class um; você apenas declara a classe (isto mesmo, vazia por não ter definição), cuja interface deverá ser fornecida (definida) em algum momento. Isso é comumente chamado de "forward declaration", e é útil quando você precisa apenas informar que vai usar essa classe, mas não precisa dos detalhes de sua implementação ainda. Em outras palavras, você diz que vai usar, mas não deseja (ou não pode) incluir o cabeçalho por algum motivo.
Um exemplo de uso é quando uma classe A referencia uma B que referencia A de volta. A classe A inclui o cabeçalho da B, mas a classe B pode apenas indicar que "reconhece" a classe A e assim evita uma referência circular nos includes:
Arquivo b.h:
class A;
class B
{
    A *a;
};

Arquivo a.h:
#include "b.h"
class A
{
    B *b;
};

Mas note que eventualmente o compilador precisa encontrar a definição de uma classe predefinida (assim como a sua implementação - o código dos métodos), caso contrário vai produzir erros de compilação e/ou linkedição.
Comment: Bom, nesse caso é só garantir que não ocorra inclusão circular. Leia sobre o [`#pragma once`](http://pt.stackoverflow.com/a/155570/73) e sobre a alternativa com [`#ifndef`](http://pt.stackoverflow.com/q/9592/73). Vc também pode usar o [*forward declaration*](http://pt.stackoverflow.com/a/124405/73). Na prática é como você preferir, mas eu acho mais claro usar uma das duas alternativas anteriores se for apenas para evitar referência circular.
Comment: Fiquei esclarecido.
Caso se use a declaração deve-se usar o `include` dessa class definida, para evitar eventuais erros?
No entando, no meu problema usando apenas o `include` para uma função tipo `void f1(nomeclass * p);`, recebo erro compilação, que o nomeclass não é identificado, e quando coloco `class nomeclass;`, compilador já identifica, daí a minha questão. E ainda mais, tendo outras classes, o mesmo género de função funcionam apenas com includes. A ordem dos includes tem relevância?
Comment: (1) Sim, naturalmente. (2) Precisa ver qual é o erro, pois se está tudo ok no arquivo .h isso não devia ocorrer. (3) A ordem pode ter relevância dependendo da forma como você desenvolveu. E não apenas isso, mas o tempo de compilação e as dependências também decorrem dessa estrutura. O ideal é separar os arquivos de forma que as classes fiquem o mais independentes possível. E lembre-se de que vc *não precisa* ter um .h para cada classe, pode também declarar e definir mais de uma classe em um mesmo arquivo .h (se isso fizer sentido no seu domínio de problema).
Comment: É um projecto grande, daí cada classe ter o seu .h. Penso que o problema está em, algo ambíguo, pois o que acontece no meu problema, é que tenho duas classes, e ambas as classes necessitam do include uma da outra, ou seja, uma class tem um include .h, e nesse include tem, outro include que se chama a ela própria. E penso que seja daí o problema, daí ter que usar a declaração da classe.


SwiftUI: How to get content aligned to top of screen, but keep back button

Question: I'm learning SwiftUI (with Swift 5, targeting iOS 13.2)
Q) How do I get it so that my photo (and contents underneath) are aligned behind the notch area?
What I've got so far in the simulator:
As you can see, I've found out how to use an inline navigation bar style.

What I want

View Code:
<code>import SwiftUI

struct DrinkDetail: View {

    var drink: Drink

    var body: some View {
        List {
            ZStack(alignment: .bottom) {
                Image(drink.imageName)
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                Rectangle()
                    .frame(height: 80.0)
                    .opacity(0.75)
                    .blur(radius: 10)

                HStack {
                    Text(drink.name)
                        .font(.largeTitle)
                        .foregroundColor(.white)
                        .padding(8)
                    Spacer()
                }
            }
                .listRowInsets(EdgeInsets())

            Text(drink.description)
                .font(.body)
                .foregroundColor(.primary)
                .lineLimit(nil)
                .padding(.bottom, 50.0)
                .lineSpacing(12)

            HStack {
                Spacer()
                Button(action: {}) {
                    Text("Order me")
                }
                    .frame(width: 200.0, height: 50.0)
                    .background(Color.blue)
                    .foregroundColor(.white)
                    .cornerRadius(10)

                Spacer()
            }
        }
        .edgesIgnoringSafeArea(.top)
        .navigationBarTitle(Text(""), displayMode: .inline)
    }
}
</code>
Comment: Does this answer your question https://stackoverflow.com/a/65523676/12299030?
Answer: Looks like this simply isn't possible, despite the tutorial I watched showing it previously being possible.
Until further notice, this is the only way: https://stackoverflow.com/a/65523676/12299030


Can I place HS22 and LS22 blades in the same BladeCenter?

Question: Is it possible to place HS22 and LS22 blades in the same IBM BladeCenter without compatability issues?
Comment: One needs to know your chassis type to answer the question.
Answer: Yes, you can mix any combination of blades in the same BladeCenter chassis provided the blades themselves are supported in that chassis.
The table here lists the compatibility table between blades and chassis.
(huh, actually the LS22 is no longer listed. You can find it's compatibility list here.)
Answer: On IBM's webpage there is a "bladecenter redbook" this correctly answers your question.
This is one of that:
http://www.redbooks.ibm.com/Redbooks.nsf/RedbookAbstracts/sg247523.html
Comment: It's considered bad form on this site to simply provide a reference without actually providing the answer. By all means, please do provide the reference - but also please answer the question.


What is the difference between a basis for the domain and a basis for the codomain?

Question: What is the difference between a basis for the domain and a basis for the codomain?
Until now, I was under the impression that the basis you choose for the domain must also be the basis for the codomain. Of course, we can convert from one basis to another, but I thought that the conversion must take place for both the domain and the codomain.
Take the following linear transformation:
$T:{\bf R}^2\to{\bf R}^2$ given by $T(v)=2v$. Take $\{\,(2,3),(4,5)\,\}$ as the basis for the domain and the standard basis for the codomain. In this case, the matrix representing $T$ would be $\pmatrix{4&8\cr6&10\cr}$.
Apparently, the above example has a different bases for the domain and codomain. However, this distinction is still not clear to me.
What would the above example look like if the bases were reversed -- if the standard basis was a basis for the domain and $\{\,(2,3),(4,5)\,\}$ was a basis for the codomain?
I would greatly appreciate it if people could please take the time to elaborate on this concept and help me understand it.
Answer: For your first example, $v_1 = (2,3)$ and $v_2 = (4,5)$ is the basis for the domain and $w_1 = (1,0)$ and $w_2 = (0,1)$ is the basis for the codomain.
When you say that the matrix is $ \left( \begin{array}{cc} 4 & 8 \\ 6 & 10 \end{array} \right) $,
what you really mean is that
$$T(v_1) = 4w_1 + 6w_2,$$
$$T(v_2) = 8w_1 + 10w_2.$$
Equivalently, any vector in the domain can be written as $v = a_1 v_1 + a_2 v_2$ for some coefficients $a_1, a_2 \in \mathbb R$. Its image under $T$ can be written as $T(v) = b_1 w_1 + b_2 w_2$ for some coefficients $b_1, b_2 \in \mathbb R$. These coefficients are related by the matrix equation,
$$ \left( \begin{array}{cc} b_1 \\ b_2  \end{array} \right)  = \left( \begin{array}{cc} 4 & 8 \\ 6 & 10 \end{array} \right) \left( \begin{array}{cc} a_1 \\ a_2  \end{array} \right)$$
Is this enough of an explanation for you to work out the correct matrix when the bases reversed?
Comment: $T(w_1) = T(1,0) = (2,0) =-5(2,3) + 3(4,5) = -5v_1 + 3v_2 $
Comment: $T(w_2) = T(0,1) = (0,2) = 4(2,3) - 2(4,5) = 4v_1 - 2v_2.$
Comment: So the matrix this way round is $\left( \begin{array}{cc} -5 & 4 \\ 3 & -2 \end{array} \right)$
Comment: I still don't understand. Can you please elaborate?
Comment: $T(v_1) = T(2,3) = (4,6) = 4(1,0)+ 6(0,1)$.
Comment: $T(v_2) = T(4,5) = (8,10) = 8(1,0) + 10(0,1).$
Comment: But isn't that exactly the same as what you wrote above? What is the difference between the reversed version and the original one?
Comment: The numbers in the matrix come from reading off the coefficients.
Comment: @kennywong I found this question, if you have time please answer my confusion. my question is, when you do T(e1) you produce a vector (2,0) in R^2, because it is in R^2 you can represent it as linear combination of the basis v that is also in R^2 right? But why (2,0) is not in column for matrix Transformation and when it considered to be column of matrix transformation? Thankyou!
Answer: Here's the definition of the matrix of a linear map taken straight from Sheldon Axler's Linear Algebra Done Right, Third Edition:

Suppose $T\in \mathcal L(V,W)$ and $v_1, \dots, v_n$ is a basis of $V$ and $w_1, \dots, w_m$ is a basis of $W$.  The matrix of $T$ with respect to these bases is the $m$-by-$n$ matrix $\mathcal M(T)$ whose entries $A_{j,k}$ are defined by $$Tv_k = A_{1,k}w_1 + \cdots + A_{m,k}w_m.$$

So, as you can see, when constructing a matrix from a linear map you have to choose a basis for the domain and codomain first.  But they certainly don't have to be the same -- in fact if $V\ne W$ then they couldn't possibly be the same.

Here's how we apply this to your example to construct a matrix.  First apply $T$ to each vector in your domain's basis:
$$T(1,0) = 2(1,0) = (2,0) \\ T(0,1) = 2(0,1) = (0,2)$$
Then we have to expand these in the basis for the codomain.  In this case we have
$$T(1,0) = (2,0) = -5(2,3) + 3(4,5) \\ T(0,1) = (0,2) = 4(2,3) -2 (4,5)$$
Compare this to the definition above (written for a $2\times 2$ matrix):
$$Tv_1 = A_{1,1}w_1 + A_{2,1}w_2 \\ Tv_2 = A_{1,2}w_1 + A_{2,2}w_2$$
Then we see that the coefficients given above become the elements of our matrix in this specific way $${\mathcal M}(T) = \begin{bmatrix} -5 & 4 \\ 3 & -2\end{bmatrix}$$
Answer: In my opinion, it's simpler to explain in a general context. So suppose you have a linear map from a vector space $E$ to a vector space $F$, and this linear map is represented by a matrix $A$ when $E$ and $F$ are equipped with bases $\mathcal B$,  $\mathcal C$ respectively.
Now if we change bases to $\mathcal B'$,  $\mathcal C'$, denote $P$ the change of basis matrix from $\mathcal B$ to  $\mathcal B'$, and $Q$  the change of basis matrix from $\mathcal C$ to  $\mathcal C'$ is
$\;A'=Q^{-1}AP$.
Remember $P$ is the matrix of the identity map from $(E, \mathcal B')$ to $(E, \mathcal B)$, and $Q$ is the matrix of the identity map from $(F, \mathcal C')$ to $(F, \mathcal C)$.
We have the matrix $A$ of the linear map from   $(E, \mathcal B')$ to $(F, \mathcal C)$.
We want  the matrix $B$ of the linear map from   $(E, \mathcal B)$ to $(F, \mathcal C')$. Consider the commutative diagram:
\begin{alignat}{2}
(&E, \mathcal B')&\xrightarrow{~ A~~}~&(F, \mathcal C)\\
&  \llap{P^{-1}}\uparrow\Vert&&\downarrow\Vert\rlap{Q^{-1}}\\
(&E, \mathcal B)&\xrightarrow{~ B~~}~&(F, \mathcal C')
\end{alignat}
You deduce at once that
$\;B=Q^{-1}AP^{-1},$ and in the present case, since $E=F$ and $P=Q$:
$$B=P^{-1}AP^{-1}.$$


Opening jQuery UI Dialog box with dynamic content and then dynamically react to click in the dialog

Question: I want to populate a jQuery dialog with dynamic content from a getData.php file. That works fine so far via:
$("#buttonGetData").click(function() {

  $.get("getData.php", function(data){
      $("#dialog").html(data);
      $("#dialog").dialog();
      return false;
  });
});

The getData.php just gives something back like:

data1

data2

data3

My problem now is: How do I add a dynamic click listener to each data row so I can use the clicked data in my site? I want each 'p' be clickable and then use the data inside for setting its content to a 'textarea'.
The problem seems to be, that the new dynamically added rows arent part of the JS from the site, so I can't reach them via a clickListener.
How would this be done correctly? Thank You!
Comment: You can use [event delegation](https://learn.jquery.com/events/event-delegation/)
Comment: I am looking into this right now. It looks promising. I will report back if it worked.
Answer: When you get html related data result using Ajax like you used $(get)... , your newly generated html from Ajax cannot be used for jQuery code OR in other word jQuery/JS don't recognized your newly added html elements generated from Ajax. There is a way you can achieve your required result. You can send your jQuery/JS code with html codes to Ajax from your file (getData.php) as String.In your getData.php you can echo like this.
echo '
data1
';
echo '';
die();

Above may be very straight forward answer so there is another way which may be more convicting. You can also used delegation on based on event handler. Examples:
$("#dialog").on("click","p", function(){
  alert("DATA1 Clicked");
 // your code to add content of this element to textarea
});

$("#dialog").on("click","#data1", function(){
  alert("DATA1 Clicked");
 // your code to add content of this element to textarea
});

$(document).on('click', '#data1', function(){
    alert("DATA1 Clicked");
 // your code to add content of this element to textarea
});

One of them should be able to solve the problem.
Comment: I was assuming something like this. But, how would this help? The javascript in the php file, which I would add via echo, wouldn't have access to the JS in my main html file, no? Doing an standalone like you did there like "alert" works, but I want the clicked data to be parses to my main html file, from which the AJAX call was initiated. For example: click button, ajax call, data fill into the dialog. Then user clicks on row x, and then the page will fill a textarea of the main html page with the data x content.
Comment: I have updated my answer. Please do check them if that will solve your problem.


Inequality for supremums of functions

Question: We have the reverse triangle inequality:
$|x-y| \geq ||x| - |y||$
Let $f, g \in \mathbb{R}^I$ for some interval $I$. Fix $x \in I$.
Do we have that sup$\{f(x)-g(x)\} \geq$ sup$\{f(x)\}$ - sup$\{g(x)\}$ ?
P.S. I'm asking this because I believe I need that to proof that $(X,$$d_{\infty,\infty})$ is a metric space.
Answer: We have
$$
\sup_{\Omega} f(x) - \sup_{\Omega} g(x) \le
\sup\limits_{\Omega}(f(x)-g(x)) \le
\sup_{\Omega} f(x) - \inf_{\Omega} g(x).
$$
This assumes that the domain of both functions is $\Omega$.
Comment: The inequality provided is true, but I think the answer is yes, see my proof.
Comment: Yes. "No" in my answer referred to the inequality in the title. :)
Comment: Agreed, @Alex, the title makes no sense actually.
Answer: Yes. For every $x\in I$, we have
$$ f(x) = \big(f(x)-g(x)\big) + g(x) \leq \sup (f-g)(I)+\sup g(I).$$
Taking the supremum over $x\in I$ thus gives
$$ \sup f(I) \leq \sup (f-g)(I)+\sup g(I).$$
Now re-arrange to get
$$\sup (f-g)(I) \geq \sup f(I) - \sup g(I),$$
as requested.

Inequality for supremums of functions


Annihilator of image $T$ equals to $\text{ker}(T^*)$

Question: Let $T:V\to W$ be a linear transformation, then $\text{Ann}(\text{Im}T)=\text{ker}T^*$.
How one could start to prove it?
Many thanks.
Answer: $\phi\in Ann(ImT)$ iff $\phi(Tx)=0$ for all $x\in v$ iff $T^*(\phi) x=0$ for all $x\in V$ iff $\phi\in Ker(T^*)$


lasso regression on top of random forest

Question: Some time ago, I found a paper describing usage of lasso/elastic net regression on binary variables come from random forest. In short, (i,j)-th variable takes 1 if given observation belong to leaf no. i inside tree no. j. Because this will result in a huge number of variables, authors suggested using lasso regression to obtain sparse and interpretable solution.
Does somebody know if such a procedure is implemented in R/Python or can (at least) post a link to this article (or similar). Thanks in advance.
Answer: First I think it is hard to say one model out "perform" another. Each model has different pros and cons and should be applied to different cases. For example, I would not say random forest outperforms linear regression, because linear regression is 1. more "stable" 2. requires less computational power 3. more interpretable, plus, if you ground truth between feature and value is really linear, no one can beat linear regression.
Now, back to your question, on code to try two approaches.
You can easily to do the experiment with both way and compare the performance. The trick is using model.matrix in R. Here is one example from ISL book to use model.matrix to convert factors to design matrix and use ridge or lasso.
# Chapter 6 Lab 2 of ISL book: Ridge Regression and the Lasso
library(ISLR)
library(glmnet)
Hitters=na.omit(Hitters)

# transfer formula input to matrix input
x=model.matrix(Salary~.,Hitters)[,-1]
y=Hitters$Salary

set.seed(1)
train=sample(1:nrow(x), nrow(x)/2)
test=(-train)
y.test=y[test]

grid=10^seq(10,-2,length=100)

# The Lasso
lasso.mod=glmnet(x[train,],y[train],alpha=1,lambda=grid)
plot(lasso.mod)
set.seed(1)
cv.out=cv.glmnet(x[train,],y[train],alpha=1)
plot(cv.out)

# get best fit lamda and fit all data
bestlam=cv.out$lambda.min
lasso.pred=predict(lasso.mod,s=bestlam,newx=x[test,])
mean((lasso.pred-y.test)^2)
out=glmnet(x,y,alpha=1,lambda=grid)

On the other hand, you can easily do randomForest like
randomforest(Salary~.,data=Hitters)
Comment: How does it relate to my question?
Comment: you were asking if you can do experiment with Python or R,  and I listed some code you can try yourself. In addition, I do not believe you can directly compare two types of the model in your way.
Comment: is this related (not randomforest but svm)? please check [When to use LIBLINEAR but not LIBSVM](https://www.csie.ntu.edu.tw/~cjlin/liblinear/FAQ.html)
Comment: I asked about procedure (or at least article) which enables to obtain binary variables from randomforest and then applies some regularized regression. I have no interest in comparing randomforest and regression, that's why I considered your post completely irrelevant.
Comment: I was trying to suggest to use model.matrix (the procedure) to "obtain binary variables from random forest then applies some regularized regression". Sorry for your confusion.
Answer: This is two years after the original post, but may be of use to others:
R package pre allows for fitting prediction rule ensembles through the algorithm of Friedman & Popescu. It is available from CRAN; development version and an example can be found on GitHub (https://github.com/marjoleinF/pre).
Comment: The current development version on github now supports survival regression. Not extensively tested yet, comments and suggestions are welcome. Here's an example (please excuse lack of line breaks):
`library("devtools");
install_github("marjoleinF/pre"); library("pre");
data("GBSG2", package = "TH.data");
set.seed(42);
surv_pre <- pre(Surv(time, cens) ~ ., data = GBSG2);
surv_pre;
predict(surv_pre, newdata = GBSG2[1:10,], type = "response");
coef(surv_pre)[1:10,];
imp <- importance(surv_pre);
imp`
Comment: Actually, I've already used your package! It's really cool. I was wondering, whether you have a plan to add (or maybe it's already done) some survival regreesion rulefit models (like taking the leaf assignments from randomForestSRC for survival analysis task and apply som regularized Cox regression model)?
Comment: Cool, thanks! Survival regression is not implemented yet, but should not be too hard to implement. Would be an interesting addition. Will take a look at it this week and let you know when implemented (or when it turns out to be more difficult than I thought).
Answer: This sounds almost like RuleFit described in Friedman & Popescu (2005) in which the lasso is applied to rules formed by an ensemble of trees in addition to linear terms of the variables.
R code is available via the first link.
EDIT: Just noticed that it says on the website that the current RuleFit implementation will not function after Dec 29, 2015 and no updates seem to be available. But give it a try and see if it still works.
Comment: This wasn't article I was talking about, but, anyway, thanks for the link - I 'll definitely try that out.
Comment: Just found this http://bmcsystbiol.biomedcentral.com/articles/10.1186/1752-0509-8-S3-S5 Is that the paper you were talking about?


Maintain same volume levels in a digital guitar processor

Question: I have a BOSS ME-25 and i observe that when i switch between patches, the volume levels are different. I edited the patches and set the same volume and save them. However when i play and switch between those patches i see difference in the volume levels. This is an issue when i play on stage as the sound man complains my patches are not correct.
I'm looking for a more detailed answer in terms of how i should set up my patches, irrespective of the processor that I use (unless it really depends on the type of processor that i use) to ensure the volume is even and i still want the tone that i dialed in (in terms of any or all of these settings - comp/fx, Preamp, os/ds, modulation/reverb etc)
Answer: If you have distortion or compression in your patches, then there is no way to guarantee that the volume won't change between patches.
Distortion e.g. tends to amplify the signal when the guitar is played softly. When the guitar is played aloud, then the volume does not increase as much as the the volume of the undistorted signal does. In that case the undistorted signal may well be louder than the distorted signal. The same considerations apply to compressors.
So I believe you have to fine tune the volume settings to your playing style and you need to do it per patch.
Answer: In looking at the ME-25 Manual (PDF) you can see that each patch usually has a preamp volume, and every overdrive or compression effect also has a volume setting within it.  So you can have up to three volumes that all affect the overall output volume of a given patch. You are going to want to fine tune these to get a volume you like. Modulation, reverb and delay levels are usually more about the amount of modulation/reverb/delay used, so they affect the overall volume less. The ones to focus on are preamp, overdrive, and compression.
The important thing to remember is that that a volume setting that may produce a perfect volume for one patch (say preamp:7, OD:6) might be too loud or too quiet if you use the same settings for a different patch.  Every amp model and the different OD effects all affect the overall volume differently, so to get a really even tone you are going to want to go through and listen to each patch and adjust the volume by ear, not by the number values.
This is a tedious process, and is really only necessary for the patches you use the most or the ones you might want to use live.  But you start with one patch, dial in the right volume, then switch to a new patch, adjust the volume so it is consistent with the previous patch and then save it. You are going to have to switch back and forth to confirm the volumes are relatively equal, then once you find the right level you can save it and move on to the next one.
It takes a lot of time and effort to set up a unit like that for evenness and consistency, but if you are playing with a band or doing gigs, it's pretty important that you go through and dial in all the tones you can see yourself using and make sure the levels match.  This is actually one of the reasons I sometimes prefer using separate pedals, because its much easier to tweak and fine tune this sort of thing without having to go through menus and saving patches. But in a multi-effect unit like yours, once you get it set properly, then you can forget about it for the most part, which is also useful.
edit: one note, if playing live or with a band, you are going to want a handful of patches that are a bit louder, your "boost" patches, that you can use during a solo or anytime you  need that extra bit of volume.


Ruby regular expression groups

Question: I am trying to match strings that might represent ranges somewhere in a document but can't quite figure out one thing about the groups... I have this so far:
/(^-?[0-9]+)(\.\.+)(-?[0-9]+$)/

Which matches  1..10, -20...20, -01234567890...-999999999, etc. However, I want the second group ($2) to have a value ONLY if the middle was 3 digits instead of two. So I would want it to be like:
=~ -01234567890...-999999999
$1 = -01234567890
$2 = ...
$3 = -999999999

=~ 1..10
$1 = 1
$2 = (empty because only two dots instead of 3)
$3 = 10

Any way to specify this, to only make a group if it's a certain value?
Answer: You can use:
(^-?[0-9]+)(?:(?:[.]{,2})|([.]{,3}))(-?[0-9]+$)

which will only put the result in the second group if it is three ..
Explanation:

?: - non-capturing group.
| - OR

Note that (?:[.]{,2}) is non-capturing while ([.]{,3}) will capture the group.
Comment: Our answers were almost identical! Possibly worth explaining what `?:` is doing here
Comment: @NeilSlater - agreed.

Ruby regular expression groups


R - Convert to time values after group_by

Question: I have a column in a dataframe, chr and in the form "%Y-%m-%d %H:%M:%S". I have no problem converting them to POSIXct. However, if I leave that column as chr and after I use group_by with that column as the first column of the new dataframe, I cannot convert that first column to POSIXct any more
R says do not know how to convert 'abc[, 1]' to class "POSIXct". I check the structure of the new dataframe and the first column is still chr. Really appreciate any help.
Comment: While SO users are generally imaginative a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) would greatly help
Answer: You can try doing the conversion; and then, use group_by to group the variables. I have grouped date variables many times without problem.
lubridate is another package from the tidyverse, it makes easier work with dates and times.


Como passar um post com um array para uma URL de um WebFORM

Question: Estou tentando mandar um array com alguns elementos em um post para uma url.
Chamei método 'WebBroser', passei os parâmetros, mas mesmo assim fiquei sem ideia de como terminar de implementar.
Segue meu código:
<code>   private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("MINHA_URL");
        request.Method = "POST";
        request.Accept = "application/json";
        request.UserAgent = "curl/7.37.0";
        request.ContentType = "application/x-www-form-urlencoded";

        using (var streamWriter = new StreamWriter(request.GetRequestStream()))
        {
            string data = "browser=Win7x64-C1|Chrome32|1024x768&url=http://www.google.com";

            streamWriter.Write(data);
        }

    }
    private void label2_Click(object sender, EventArgs e)
    {

    }

    private void button1_Click(object sender, EventArgs e)
    {
        var lista = new string[]
        {
            info.nome,
            info.idade,
              info.estado= "H",
           //DAQUI PRA BAIXO JÁ É PRÉ-DEFINIDO

            info.regiao,
            info.tipousuario = "X",
            info.formulario = "0",
            info.t = "+",
            info.v = "",
            info.pop = "",
            info.t= "",
            info.p= "",
            info.t= "x",
            info.r= "x",
            info.e= "2",
            info.f= "n",
            info.id= ""
        };

         webBrowser1_DocumentCompleted(lista, null);
    }

    #region inputs
    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        info.estado= textBox1.Text;
    }

    private void textBox2_TextChanged(object sender, EventArgs e)
    {

        info.nome= textBox2.Text;
    }

    private void textBox3_TextChanged(object sender, EventArgs e)
    {
        info.idade= textBox3.Text;
    }
    #endregion
</code>
Comment: Não entendi qual é sua dúvida.
Comment: Então cigano. Tenho uma URL que vai receber um post de um array. O que quero é, mandar esse post que está no button1_Click para o método webBrowser1_DocumentComplete.
Comment: E depois? O que acontece?
Comment: Desejo que essa url, execute com os parâmetros que foi enviado a ela.
Answer: Aparentemente está tudo certo. Falta só recolher a resposta:
<code>private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("MINHA_URL");
    request.Method = "POST";
    request.Accept = "application/json";
    request.UserAgent = "curl/7.37.0";
    request.ContentType = "application/x-www-form-urlencoded";
    request.KeepAlive = false;

    using (var streamWriter = new StreamWriter(request.GetRequestStream()))
    {
        string data = "browser=Win7x64-C1|Chrome32|1024x768&url=http://www.google.com";

        streamWriter.Write(data);
    }

    WebResponse response = request.GetResponse();
}
</code>
Comment: Valeu, vou testar assim que puder. E te dou um feedback. Obrigadão!
Comment: aconteceu o seguinte erro:' A conexão subjacente estava fechada: A conexão foi fechada de modo inesperado.'
Comment: Esse bug acontece por alguma característica diferente no cabeçalho do retorno. Experimente usar `request.KeepAlive = false;`. Já atualizei a resposta.
Comment: continua dando o erro de "A conexão foi fechada..." E outra dúvida. em string data = "browser=Win7x64-C1|Chrome32|1024x768&url=MINHA_URL"; Nessa parte da "minha_url" eu coloco a url q passo no Create, n é?


Intellij IDEA Class Files Expanded

Question: I am having this odd issue in IntelliJ IDEA where the Java class files are automatically expanded by default when I navigate through packages. See the following images:

This happened after I downloaded the most recent update, of which I am currently on:
<code>IntelliJ IDEA 2016.3.4
Build #IU-163.12024.16, built on January 31, 2017
JRE: 1.8.0_112-release-408-b6 x86_64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
</code>
I don't think I made any changes to my configuration, however sometimes I do accidentally use the wrong hotkeys, so it is possible I cmd + shift + random key to toggle this feature on.
Answer: Original Solution
You should turn off "show members" in project view.
Illustration:

Intellij IDEA Class Files Expanded


Why can't my networks reach each other?

Question: We have two Buffalo WZR-HP-G300NH2 routers, with the default firmware, DD-WRT v24SP2-MULTI (10/31/11) std - build 17798. Each has a separate cable internet connection with a public static IP address. They are both in the 126.96.36.199/24 space.
Both of them can contact pretty much the whole internet, and they can both be accessed out on the internet with no problem, but for some reason they can't talk to each other! When I try to ping one from the other I always get "Destination Host Unreachable". There are no strange routing or firewall rules in place. And they are both set to respond to pings, I can ping them from outside.
Our main IT guy is going to call our ISP on Monday, but I'm impatient, so does anyone have any ideas?
Answer: It sounds like they have their netmasks set improperly. If they're both in 126.96.36.199/24 and they both have their netmask set to /24, then each one will think the other one's hosts are on its local network, so it will use ARP to try to connect to them locally, which won't work.
It sounds like whoever configured the routers didn't correctly set the netmask. It's also possible that individual machines on the LAN have the LAN netmask set incorrectly. Check the routing table on the machines to make sure they're correct to use the router to reach machines on the other network. Then check the routers to make sure the netmasks are correct to use the Internet to reach machines on the other network. I'll bet you one or both of those is incorrect.
Comment: Thanks man! I changed the netmask on the WAN interface from 255.255.255.0 to 255.255.255.255, and it works now!
Comment: That's incorrect, too... with a /32 netmask, they should not even be able to reach their default gateway (i.e. their ISP's remote endpoint).
Answer: It sounds like you don't have a route between the two.

Why can't my networks reach each other?


Why gradient boosting uses sampling without replacement?

Question: In Random Forest each tree is built selecting a sample with replacement (bootstrap). And I assumed that Gradient Boosting's trees were selected with the same sampling technique. (@BenReiniger corrected me).  Here there are the sampling techniques implemented for Catboost
My questions:

Why is Gradient Boosting sampling done without replacement?
Why would it be worst to sample with replacement?
Are there any sampling techniques used in GB that are with replacement?

I quote a paper for SGB:

Stochastic Gradient Boosting is a randomized version of standard Gradient Boosting algorithm... adding randomness into the tree building procedure by using a subsampling of the full dataset. For each
  iteration of the boosting process, the sampling algorithm of SGB selects random s·N objects without replacement and uniformly

This question is crossposted at Data Science Stack Exchange, since I didn't got any answers i am posting it here
Comment: The last option (Poisson) actually uses replacement, and it's more like a classic bootstrap
Comment: Yes! I see that there is one sampling that is done with replacement, but in the original (and most sampling techniques) it is done with out, and I am curious why this
Answer:
I would say that there are two main reasons for the use of sampling without replacement for most implementations of stochastic variants of Gradient Boosting.
The first one is simply historic: In 1999 both Breiman and Friedman published papers that went in the similar direction of trying reduce both Bias and Variance for ensemble estimators. Breiman published Adaptive Bagging, which was more based on Random Forests and used sampling with replacement. Friedman (who had also authored the first paper on Gradient Boosting) published instead Stochastic Gradient Boosting, which used sampling without replacement. In general, the work of Friedman in this field has been much more successful, as his work on Gradient Boosting is at the base of all modern implementations, which therefore use sampling without replacement as the standard.

The second reason is that sampling without replacement is more flexible: the goal of Stochastic Gradient Boosting is not only to introduce randomness, but also to make boosting iterations faster.
Quoting from the original paper:

Using $\tilde{N} = N$ introduces no randomness and causes Algorithm 2 (SGB, e.n.) to return the same result as Algorithm 1 (GB, e.n.). The smaller the fraction $f=\tilde{N}/N$, the more samples used in successive iterations will differ, thereby introducing  more overall randomness into the procedure. Using the value $f=1/2$ is roughly equivalent to drawing bootstrap samples at each iteration. Using $\tilde{N} = f \cdot N$ also reduces computation by a factor of $f$.

This means that we could indeed use sampling with replacement instead (also sampling a lower fraction $f$), but the computation factor would be much higher for an equivalent amount of "randomness" added to the iterations.


How do I insert Javascript via content page form field in Umbraco?

Question: I need to be able to insert Javascript into a webpage via an Umbraco Document property.  How do I do this?
Answer: Add a field to your document type with the type Textbox Multiple. Give it an appropirate alias like HeaderCode.
Add a reference to HeaderCode in your template.
<code><html>
    <head>
        ...
        <script type="text/javascript">
            <umbraco:Item runat="server" field="HeaderCode"/>
        </script>
    </head>
    ...
</html>
</code>
You can now enter your script into the HeaderCode, e.g.
<code> $(function() {
     // Stuff to do on page ready.
 });
</code>


Evitar duplicação em MySql

Question: É possível evitar duplicações em mysql ? Eu tive a procurar e nada se encaixa no meu caso, sempre que eu tento duplica na mesma.
Eu estou tentando importar isto na tabela:
INSERT INTO profiles (id, rep, gems, plevel) VALUES (id, 0, 100, 1)
Comment: Você deseja evitar que tenha inserts com valores iguais?
Answer: Para evitar a duplicação, você deve definir a chave que não quer que seja duplicada como PRIMARY KEY. Ou seja, se não quer dois id's repetidos, a coluna id deve ser uma PRIMARY KEY.
Dessa forma, quando tentar inserir um registro com o mesmo ID, o MySQL vai retornar o erro DUPLICATE ENTRY '0' FOR KEY 'id'.
Answer: Tente colocar o ID como chave primária, e os demais valores que você não deseja que exista repetido utilize o atributo unique.
Exemplo de criação de tabela com campo Unique:
CREATE TABLE Persons (
    ID int NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int,
    UNIQUE (ID)
);

Exemplo de alteração da estrutura da tabela para que seja unique:
ALTER TABLE Persons
ADD UNIQUE (ID);

Remover Unique:
ALTER TABLE Persons
DROP INDEX UC_Person;

Fonte: https://www.w3schools.com/sql/sql_unique.asp

Evitar duplicação em MySql


Odds of drawing any 3 identical cards from 27-card deck (9 unique x 3 copies each) in 9 draws

Question: I have a 27-card deck with 3 copies of each of 9 distinct cards.  If I'm drawing 9 cards, what are the odds that I draw all 3 copies of any one of the 9 possible options?  [Also known as "What are the odds of drawing all three of the same city in the Pandemic Legacy season 2 prologue game?"]
My initial approach was to count the number of possible matching hands versus the ${27 \choose 9}$ total possible number of hands.
I figured that there are ${24 \choose 6}$ possible ways to pick the rest of the 9-card draw after assuming one full set of 3 cards, so that makes $9 * {24\choose6}$ starting hands.
However, this double-counts hands that have two or more sets of 3 cards so I need to subtract those.  Calculating that follows a similar approach, so we have to subtract $8 * {21 \choose 3}$ cards.  Of course that latter bit double-counts the hands where our six cards are two sets of three.  So we have to subtract the 7 such hands from that.
So my final formulation was:
$\frac{9 * {24\choose6} - (8 * {21\choose3} - 7)}{27\choose9}$ ~= 25.6%
Does that seem right?  If not, what am I doing wrong?
Answer: Note:  "probability" and "odds" are not the same thing. $1:1$ odds corresponds to probability $\frac 12$, for example.  It looks like you are computing the probability, so that's what I have done below.
The approach is fine, but the arithmetic is not.  There are $\binom 92=36$ ways to choose two cities and $\binom 93=84$ ways to choose three.  Thus your numerator should be $$9\times \binom {24}6-36\times \binom {21}3+84$$  making your final answer $$\frac {1163568}{4686825}=.2483$$
As another approach:
Let's work backwards.  Let $p$ be the probability that no three of a kind is drawn.
Then each city must be represented by $0,1,2$ cards.
If there are exactly $n$ cities for which you drew $2$ cards then there must be $9-2n$ cities for which you drew exactly $1$.
Assuming you drew exactly $n$ cities for which you drew two cards, then we need to choose those $n$ cities ($\binom 9n$), choose the two cards from each city (3), then choose the $9-2n$ cities for which one card will be drawn ($\binom {9-n}{9-2n}$), and choose the one card from each of those cities.  Thus $$\binom 9n \times 3^n\times \binom {9-n}{9-2n}\times 3^{9-2n}$$
We need to sum these from $n=0$ to $n=4$ and divide by the total number of hands, namely $\binom {27}9$.  Thus $$p=\sum_{n=0}^4 \binom 9n \times 3^n\times \binom {9-n}{9-2n}\times 3^{9-2n}\Bigg / \binom {27}{9}=\frac {3523257}{4686825}=.7517$$
So, barring arithmetic error, the answer to your question is $$1-p=\boxed {.2483}$$
Answer: Sure, inclusion-exclusion (as you've done) is one way to do it.  It's nice to check by doing it another way when you can.  In this case, consider the ways to choose $9$ cards without choosing all three of any one "rank".  You must either have $9$ singletons, or $7$ singletons and a pair, or $5$ singletons and two pairs, or $3$ singletons and $3$ pairs, or one singleton and $4$ pairs.  Each singleton or pair can be chosen in three ways from its "rank".  So this amounts to
$$
3^9+\frac{9!}{7!}\cdot3^8+\frac{9!}{5!2!2!}\cdot3^7+\frac{9!}{3!3!3!}\cdot3^6+\frac{9!}{4!4!}\cdot3^5=3523257
$$
ways to not get three of any one "rank".  Dividing this by the ${{27}\choose{9}}=4686825$ draws gives a
$$
\frac{3523257}{4686825}\approx 75.174\%
$$
chance of not getting three of a kind, which doesn't quite agree with your stated chance of getting one.  You've done two small things wrong.  First, when subtracting the double-counted cases (where you've drawn two sets of three and three leftovers), there are ${{9}\choose{2}}=36$ (not just $8$) ways to choose the two ranks.  Second, when adding back in the double-counted cases from that set (where you've drawn three sets of three), there are ${{9}\choose{3}}=84$ possibilities (not just $7$).  So you should get
$$
\frac{9\cdot{{24}\choose{6}} - 36\cdot {{21}\choose{3}} + 84}{{27}\choose{9}}=\frac{1163568}{4686825}\approx 24.826\% ...
$$
this is now in exact agreement with the other approach.
Answer: Generating Function Approach
For each "suit" there is $\binom30=1$ way to choose $0$ cards, $\binom31=3$ ways to choose $1$ card, $\binom32=3$ ways to choose $2$ cards, and $\binom33=1$ way to choose $3$ cards.
Therefore, I counted the number of ways to draw no more than $2$ of each suit to be
$$
\begin{align}
&\left[x^9\right]\left(1+3x+3x^2\right)^9\\[6pt]
&=\left[x^9\right]\left((1+x)^3-x^3\right)^9\\[3pt]
&=\left[x^9\right]\left(\binom90(1+x)^{27}-\binom91(1+x)^{24}x^3+\binom92(1+x)^{21}x^6-\binom93(1+x)^{18}x^9+\dots\right)\\
&=\binom90\binom{27}{9}-\binom91\binom{24}{6}+\binom92\binom{21}{3}-\binom93\binom{18}{0}\\[6pt]
&=3523257
\end{align}
$$
Whereas, the number of ways to draw $9$ cards is
$$
\begin{align}
\left[x^9\right]\left(1+3x+3x^2+x^3\right)^9
&=\left[x^9\right](1+x)^{27}\\
&=\binom{27}{9}\\
&=4686825
\end{align}
$$
this gives a probability for drawing at least one triple to be
$$
1-\frac{3523257}{4686825}\doteq0.24826359
$$

Inclusion-Exclusion
Number of ways to draw a triple
$$
\overbrace{\overbrace{\ \ \ \binom{9}{1}\ \ \ }^{\substack{\text{choices}\\\text{of suit}}}\overbrace{\ \ \binom{24}{6}\ \ }^{\substack{\text{choices}\\\text{for rest}}}}^{\text{one triple}}-\overbrace{\overbrace{\ \ \ \binom{9}{2}\ \ \ }^{\substack{\text{choices}\\\text{of suits}}}\overbrace{\ \ \binom{21}{3}\ \ }^{\substack{\text{choices}\\\text{for rest}}}}^{\text{two triples}}+\overbrace{\overbrace{\ \ \ \binom{9}{3}\ \ \ }^{\substack{\text{choices}\\\text{of suits}}}\overbrace{\ \ \binom{18}{0}\ \ }^{\substack{\text{choices}\\\text{for rest}}}}^{\text{three triples}}=1163568
$$
Number of hands
$$
\binom{27}{9}=4686825
$$
Giving the probability of getting a triple to be
$$
\frac{1163568}{4686825}=0.24826359
$$


Selenium Webdriver throws timeout excption for chrome

Question: I have updated version of chrome as well as WebDriver. Still getting the timeout exception. It was working properly previously but suddenly it started giving exception. It is not even reaching to test as well. If anyone has solution lease help.
Version 64.0.3282.140 (Official Build) (64-bit)
Webdriver: WebDriver.ChromeDriver.win32 2.35.0
var smth = m_driver.WaitUrl(new Regex(settings.GetSiteString("xyz") + "#/.*"));

for (int maxWait = 60000; maxWait > 0; maxWait--, System.Threading.Thread.Sleep(500))
    if (m_driver.FindElement("//div[@ng-show='vm.loaded']").Displayed)
    {
        System.Threading.Thread.Sleep(500);
        return;
    }

throw new TimeoutException("Failed to wait for xyz page to load.");

Error message: The HTTP request to the remote WebDriver server for URL http://localhost:63425/session/cdc3e59/url timed out after 120 seconds.
Comment: Please provide more information, like the script you try to run. The exact versions you're using etc.
Comment: chrome version - Version 64.0.3282.140 (Official Build) (64-bit)
WebDriver.ChromeDriver.win32 2.35.0
Comment: Selenium Versions? Script?
Comment: What it mean by script? Where I will get that? Sorry I am new to these tests
Comment: The Test-Script you try to execute?
Comment: m_driver.WaitUrl(new Regex(settings.GetSiteString("xyz") + "#/.*"));

            for (int maxWait = 60000; maxWait > 0; maxWait--, System.Threading.Thread.Sleep(500))
                if (m_driver.FindElement("//div[@ng-show='vm.loaded']").Displayed)
                {
                    System.Threading.Thread.Sleep(500);
                    return;
                }

            throw new TimeoutException("Failed to wait for xyz page to load.");
Comment: Please update your Question with this informations. Also please add the exact error message you receive.
Comment: @Shraddha , which version of selenium are you using?
Comment: Selenium Version - 220.127.116.11
Answer: It seems that adding the no-sandbox argument to your chrome driver options fixes the problem. I'm still trying to figure out why this fixes it.
Here is an example of how to instantiate a ChromeDriver so that it doesn't give you timeouts on pages that actually load properly.
var chromeOptions = new ChromeOptions();
chromeOptions.AddArgument("no-sandbox");

var webDriver = new ChromeDriver(Directory.GetCurrentDirectory(), chromeOptions);

I found this solution in this Github thread


What is the format of the content in the .text generated by the linker?

Question: During the compilation process, the linker maps our code text content into the .text in the code memory section. I would like to know what is the meaning of the text content, does it mean the actual code in text or in assembly?
Thanks a lot!
Answer:
does it mean the actual code in text or in assembly?

Neither: it's actual code in machine instructions.
For example:
$ cat > t.c
int foo() { return 42; }
$ gcc -c t.c
$ objdump -d t.o

t.o:     file format elf64-x86-64

Disassembly of section .text:

0000000000000000 <foo>:
   0:   55                      push   %rbp
   1:   48 89 e5                mov    %rsp,%rbp
   4:   b8 2a 00 00 00          mov    $0x2a,%eax
   9:   5d                      pop    %rbp
   a:   c3                      retq

The contents of the .text section is the following 11 bytes:
554889e5b82a0000005dc3

Update:

is it correct to say that it contains the assembly code which converted into machine readable binary format?

You could say that, but it not very clear.
Perhaps "contains machine readable binary instructions, produced by compiling and assembling the program source, and applying relocations". (That last part is what the linker does, not demonstrated in the example above.)
Comment: Hi, Thanks for the information. So is it correct to say that it contains the assembly code which converted into machine readable binary format?


custom form module not showing upload functionality

Question: <code><?php

function form_test_menu() {
  $items['formtest'] = array(
    'title' => 'Form Test',
     'page callback' => 'drupal_get_form',
     'page arguments' => array('form_test_form'),
     'access callback' => TRUE,
    );
   return $items;
}

function form_test_form($form,&$form_submit) {
   $form['firstname'] = array(
    '#title' => t('Firstname'),
    '#type' => 'textfield',
    '#required' => TRUE,
  );
    $form['lastname'] = array(
    '#title' => t('Lastname'),
    '#type' => 'textfield',
  );
  $form['submit'] = array(
    '#value' => 'Submit',
    '#type' => 'submit',
    );
  return $form;
}
</code>
Hello all,
Can anyone explain to me why this will not work?  I am trying to test the form submission and I created a module folder with a .info file.  I am using mywebiste/formtest, but every time I try and load the page it says "page not found."  I have been looking at tutorials and they all seem to work fine but it seems that I must be doing something wrong.  Any thoughts?
Any and all help is greatly appreciated, thank you in advance.
Comment: really sorry, I forgot to update the title, I was going to ask a different question but decided not to in the end.  Sorry!
Comment: what is your module name?
Answer: Try to clear all cache of your Drupal website and try to access your url: http://wwww.your_domain.com/formtest
Comment: Hello Dvex,
I have cleared the cache every time I update code and still no luck.
Comment: Hello Aboodred my module name is upload
Comment: Drupal hook implementations are always the module (or theme) name replacing the word "hook".

So `form_test_menu()` is the **form_test** module's implementation of `hook_menu()`.

If your module name is, as you say, **upload**, then you should name your functions as `upload_menu()`, etc.
Comment: @pjcdawkins I Agree with you. Replace the word HOOK with the name of your module.


Is there way to make SQL+ accept a parameter that isn't a number?

Question: I'm stuck on this Homework problem for Oracle Plus, so any pointers in the right direction would be great. I need to...
"1.Create a script that will take an parameter of division(DIV) with script execution and generate employee report for all employee in this division."
Here's the layout of the relevant tables
Divisions
-Division_ID, Name
Employees2, Employee_ID, Division_ID, Job_ID, First_Name, Last_Name, Salary
So far I have
SET DEFINE '#'
SELECT Last_Name || ',' || first_name AS Name, Divisions.Name

FROM Employees INNER JOIN Divisions
ON Employees2.Division_ID = Divisions.Divisions_ID

WHERE Division_ID = #v_Division_ID

It asks me for the division_id input but when i put it in it doesn't work. Now being that the Division_ID column isn't a number but rather an abbreviation like "SAL" for sales It seems that the error is because oracle plus wont take letters as input but rather only numbers? Is there a way to make this script so it accepts string/data that isn't numbers but rather something like "sal"?
Comment: What is "Oracle Plus"?
Comment: Try `...WHERE Division_ID = '#v_Division_ID'`
Comment: I assume you mean SQL*Plus and not Oracle+, right?
Answer: When the substitution variable is being compared to a VARCHAR2, you want to enter the value you want to supply, e.g. 'SAL', with single quotation marks around it.
Here is an example from the SCOTT sample schema:
SCOTT@dev> SET DEFINE '#'
SCOTT@dev>
SCOTT@dev>
SCOTT@dev> SELECT e.ename employee_name
  2  FROM emp e
  3  INNER JOIN dept d
  4  ON e.deptno   = d.deptno
  5  WHERE d.dname = #v_dname
  6  /
Enter value for v_dname: 'SALES'
old   5: WHERE d.dname = #v_dname
new   5: WHERE d.dname = 'SALES'

EMPLOYEE_N
==========
ALLEN
WARD
MARTIN
BLAKE
TURNER
JAMES

6 rows selected.

Thus for you, you just need to enter 'SAL' for your #v_Division_ID.


MVUE using Lehmann Scheffe theorem

Question:
Trying to solve the task from above, I'm having trouble with solving the last part. My idea was to find both $E[-Y_1]$ and $E[\frac{Y_n}{2}]$ and show, that both are equal to $\frac{n}{n+1}\theta$. The answers provided by the book say, that $\frac{n+1}{n} \hat\theta$ is the MVUE of $\theta$.
My calculations lead me to completely another answer, I'm wondering if there is a typo in the book, or if my calculations are bad. Tried to find mistake, but couldn't. Or maybe the method is completely wrong for some reason, that I don't see?
For those brave enough, to go through my calculations, here they are.
Thanks in advance for all Your help.
Comment: https://math.stackexchange.com/q/3627187/321264
Answer: For anybody, that would have simmilar problem. You need to get the distribution of $\hat\theta$ and then get expected value based on that.

MVUE using Lehmann Scheffe theorem


The joint pdf of two random variables defined as functions of two iid chi-square

Question: Let $X$ and $Y$ be two i.i.d.
chi-square distributed random variables with four degrees of freedom.
How can we get the joint probability distribution function of the random variables  $U=(X-Y)/(X+Y)$, $V=X+Y$?
Comment: What is the parameter $\alpha$? The chi-squared distribution has only one parameter, the degrees of freedom.
Comment: I expect in this case you're meant to do a bivariate change of variable. Don't forget the Jacobian.
Comment: Note that $V = X+Y$, being the sum of i.i.d. $\chi^2$ random variables with $4$ degrees of freedom, is itself a $\chi^2$ random variable with $8$ degrees of freedom.
Since $X$ and $Y$ are nonnegative random variables, we note that for any $\beta > 0$, _conditioned_ on
$V = X+Y = \beta$, $X-Y$ can take on values in $[-\beta,+\beta]$. Thus, $U = \frac{X-Y}{X+Y}$ takes on values in
$[-1,+1]$, and this holds true regardless of the choice of positive number $\beta$.  This hints at the possibility that $U$ and $V$ might be independent random variables (as is indeed shown in wolfie's answer).
Answer: If you would like to do this manually, just look up the Method of Transformations in a good book on mathematical statistics. For ease of computation, I prefer to use automated tools, where they are available. In this instance, $X$ and $Y$ are independent $Chisquared(n)$ random variables, so the joint pdf of $(X,Y)$, say $f(x,y)$ is:

Then, the joint pdf of $(U = \frac{X-Y}{X+Y}, V=X+Y)$ is say $g(u,v)$:

where Transform is an automated function (from the mathStatica add-on to Mathematica) that does the nitty gritties of the Method of Transformations for one (I am one of the authors of the package), and with domain of support:

All done.
Here is a plot of the joint pdf $g(u,v)$ in your case, with parameter $n=4$:
Comment: It is interesting to see that $U$ and $V$ turn out to be independent random variables. $V$ is, of course, a $\chi^2$ random variable, while $U$ is a centered and scaled Beta random variable? Perhaps this latter too can be deduced directly?


HttpURLConnection GET call with parameters not working

Question: I have a very simple code which is not working.
Class HttoCon:
package test;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

public class HttpCon {

public static void main(String[] args) {
    try {
        sendGet();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
    // HTTP GET request
        private static void sendGet() throws Exception {

            String url = "http://myweb.com/public/resource/data/stream";

            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();

            // optional default is GET
            con.setRequestMethod("GET");

            //add request header
            con.setRequestProperty("begin", "1430295300000");
            con.setRequestProperty("end", "1430297279988");
            con.setRequestProperty("id", "140621");
            con.setRequestProperty("time", "FIFTEEN_MINUTE");

            int responseCode = con.getResponseCode();
            System.out.println("\nSending 'GET' request to URL : " + url);
            System.out.println("Response Code : " + responseCode);

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            //print result
            System.out.println(response.toString());

        }
}

Error Trace:
{"fault":{"exceptionType":"MissingServletRequestParameterException","host":"126.96.36.199","cause":"Required Long parameter 'id' is not present","status":"400","query":"/public/resource/data/stream","stackTrace":"org.springframework.web.bind.MissingServletRequestParameterException: Required Long parameter 'id' is not present\n\tat org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter$ServletHandlerMethodInvoker.raiseMissingParameterException(AnnotationMethodHandlerAdapter.java:774)\n\tat org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveRequestParam(HandlerMethodInvoker.java:509)\n\tat

NOTE:
If I hit the url directly in browser it works fine.
http://myweb.com/public/resource/data/stream?begin=1430295300000&end=1430297279988&id=140621&time=FIFTEEN_MINUTE
UPDATE:
Using curl:
curl -X GET http://myweb.com/public/resource/data/stream?begin=1430295300000&end=1430297279988&id=140621&time=FIFTEEN_MINUTE

Above curl doesn't work and the exception is same -
curl -X GET 'http://myweb.com/public/resource/data/stream?begin=1430295300000&end=1430297279988&id=140621&time=FIFTEEN_MINUTE'

This curl works fine.
Comment: link doesn't seem to work
Comment: try con.setRequestProperty("id", "140621L");
Comment: @Pratik - I changed the link just for demo purpose.
Comment: Well if the URL works if you hit it directly in the browser, what speaks against adding the parameters to the request directly by appending them as you do in the Browser, as it looks already that you expect them to be there?
Comment: It looks like setRequestProperty is used to set stuff like "Content-Type" and "User-Agent".  From what I just researched it is not used to set parameters that need to be passed to your code on the url.  For what you are doing, you want to do something like @CraigParkinson did in his answer.
Comment: "curl" needs quoting of the url parameter if e.g. "&" is used ("&" has a special meaning in bash/shell)
Answer: You create a String containing the parameters, which then gets appended onto the URL. Create a URL Obj from this. For example :-
String this.url = "http://myweb.com/public/resource/data/stream";
this.url += "?begin=1430295300000&end=1430297279988&id=140621
    &time=FIFTEEN_MINUTE";
this.urlObj = new URL(this.url);

Then you create the connection as in your original example.
Answer: openConnection will establish the connection and issue the GET. Subsequent settings of GET parameters on the returned URLConnection object are ignored, since the URL has already been open.
Add the parameters to the URL as query string params just as the link above and open that link
or
try to post the parameters to the server (which is even better)


Signature of the product of two manifolds

Question: Let $M, N$ be two compact oriented manifolds with dimensions $4m$ resp $4n$. Is there something we can say about the signature $\sigma (M \times N)$, maybe even a formula only depending on $ \sigma (M), \sigma (N)$ and $m, n$?
I tried to apply the Künneth formula, but this only resulted in a lenghty and confusing computation.
Answer: In fact, $\sigma(M\times N) = \sigma(M)\sigma(N)$. (The result also holds without the restriction than $\dim M, \dim N$ are divisible by $4$, though it's almost vacuous in that case.) To prove it, use the Künneth formula to show that the only contributions to the intersection form on $M\times N$ are of the form $H^{2m}(M)\otimes H^{2n}(N)$, then decompose it into eigenvectors of the Poincare duality map on $H^{2m}(M)$ and $H^{2n}(N)$.
Comment: I had this idea. But I was not able to write down the matrix in the general case, and in special cases I dont see, where the product comes from.
Comment: Using the Kunneth formula, write $i_{M\otimes N}$ as the direct sum of $i_M\otimes i_N$ and some form on the $H^*(M) \otimes H^*(N)$ not of the middle dimension, then find a large trivial subspace for the latter to show that its signature vanishes. Take a look at something like $T^{4n}$ for motivation.


Is it a chord? Same note different pitches

Question: Is playing the keyboard notes on different pitches example c5,c6,c7, simultaneously from the white keys. a chord? Pardon for my English
Answer: No, it's called unison. A chord needs to have 3 different note names in it. (Some agree that two only constitutes a chord).


MySQL Index performance for decimal column type

Question: I searched everywhere but i couldn't find a proper answer about index on decimal columns types.
I have a table (innodb) with reviews, column score is decimal(3,1) mean there will be a number between 0.0 and 10.0
I have index on score column where i can order by desc my reviews.
What are the advices you can give me to make a good index on a decimal column? Is there any changes i need to make or this will be the right way to do the index?
Any infos are welcome
Answer: Your looking too soon, Make the index on it, if there are performance issues, solve them then. without knowing the query, simply adding an index to the column and letting MySQL sort it is by far the best way.
An alternative is storing between 0 and 100, which would be a TINYINT(In reality 0-255), Though you lose the meaning of the type and have to remember to divide by 10 each use.
Its MUCH better to just stay as you are and fix the problems as you come to them.


incompatible types boolean cannot be converted to Usuarios

Question: Estou criando uma função para inserir novos usuarios no banco, porem apresente essa erro: "incompatible types: boolean cannot be converted to Usuarios". Alguém sabe uma forma de solucionar esse caso:
public String InsertUserCpf(@PathParam("nome")String nome,
        @QueryParam("email") String email,
        @QueryParam("senha") String senha,
        @QueryParam("dtnasc") Date dtnasc,
        @QueryParam("fone") String fone,
        @QueryParam("oab") String oab,
        @QueryParam("cep") String cep,
        @QueryParam("cpf") String cpf)
{
    Usuarios u = new Usuarios();
    u.setNome(nome);
    u.setEmail(email);
    u.setSenha(senha);
    u.setDtnasc(dtnasc);
    u.setFone(fone);
    u.setOab(oab);
    u.setCep(cep);
    u.setCpf(cpf);

    UsuarioDAO dao = new UsuarioDAO();
    u = dao.inserir(u);

    Gson g = new Gson();
    return g.toJson(u);
}

UsuarioDao.java:
public boolean inserir(Usuarios usuario)
    {
        String sql = "INSERT INTO usuarios(nome,email,senha,dtnasc,fone,oab,cep,cpf) VALUES(?,?,?,?,?,?,?,?)";
        Boolean retorno = false;
        PreparedStatement pst = Conexao.getPreparedStatement(sql);
        try {
            pst.setString(1, usuario.getNome());
            pst.setString(2, usuario.getEmail());
            pst.setString(3, usuario.getSenha());
            pst.setDate(4, usuario.getDtnasc());
            pst.setString(5, usuario.getFone());
            pst.setString(6, usuario.getOab());
            pst.setString(7, usuario.getCep());
            pst.setString(8, usuario.getCpf());

            if(pst.executeUpdate()>0)
            {
                retorno = true;
            }

        } catch (SQLException ex) {
            Logger.getLogger(UsuarioDAO.class.getName()).log(Level.SEVERE, null, ex);
            retorno = false;
        }

        return retorno;

    }

Comment: Onde ocorre o erro? Qual linha?
Comment: nesse comando que aparece o erro:   u = dao.inserir(u);
Comment: Retornar `boolean` para sinalizar se deu erro ou não é uma péssima prática de programação. Isso esconde os erros, as suas causas e dificulta a sua recuperação. Foi exatamente para que os programadores não fizessem isso, que as exceções foram inventadas, portanto, use-as.
Comment: Pelo que você está dizendo, parece ser o caso de [marcar uma resposta como aceita](http://meta.pt.stackoverflow.com/questions/1078/). Aqui não escrevemos "resolvido" na questão. Se tem uma resposta que realmente te ajudou, marque-a como aceita. Se chegou sozinho à solução, poste a solução como resposta. Assim o conteúdo fica mais organizado e fácil de ser encontrado futuramente por outras pessoas com problemas parecidos
Answer: Note que você declara um Usuario u e depois o faz receber o método inserir() que retorna um boolean e não um usuário. Ou seja, são tipos diferentes. Observe:
Usuarios u = new Usuarios(); // aqui você instancia
u.setNome(nome);
u.setEmail(email);
u.setSenha(senha);
u.setDtnasc(dtnasc);
u.setFone(fone);
u.setOab(oab);
u.setCep(cep);
u.setCpf(cpf);

UsuarioDAO dao = new UsuarioDAO();
u = dao.inserir(u); // aqui tenta receber em "u" o retorno de dao.inserir()
                    //que no caso é um boolean (true ou false) e não um Usuario
Gson g = new Gson();
return g.toJson(u);

Pelo que entendi, o método inserir retorna um boolean que refere-se ao sucesso da inserção. Logo sua lógica ficaria algo assim:
boolean sucesso = false;
sucesso = dao.inserir(u);

if (sucesso) { // sucesso ao inserir
    Gson g = new Gson();
    return g.toJson(u);
    //...
}

Porém, como o @Victor Stafusa mencionou, utilizar boolean para retornar erros é uma má prática de programação, ao invés disso utilize Exceptions
Comment: Lembrando que retornar `boolean` para indicar sucesso ou erro é uma má prática de programação.
Comment: Obrigada @Zulian, resolveu o problema e vou tentar agora incluir Exceptions. Obrigada pela dica