Glitchy map AnnotationView Behavior

Question: I've created a custom MKAnnotationView similar to this project created by Apple. In it, I place an imageView and a label. However, I am noticing very glitchy behavior as I scroll and zoom around on the map. Even right after launching this behavior is displayed. The views can be seen briefly in the upper left-hand corner before they jump around.
Below is a link to a gif of the problem
The Problem
Below is the code for the Custom AnnotationView
Update
I switched to using a modified version of the AnnotationView apple uses with the suggestions below but I'm still experiencing the same jumpy behavior jumpy behavior
a link to the complete code
import Foundation
import UIKit
import MapKit
import SDWebImage

class AppleCustomAnnotationView: MKAnnotationView {

    private let boxInset = CGFloat(10)
    private let interItemSpacing = CGFloat(10)
    private let maxContentWidth = CGFloat(90)
    private let contentInsets = UIEdgeInsets(top: 10, left: 30, bottom: 20, right: 20)

    private lazy var stackView: UIStackView = {
        let stackView = UIStackView(arrangedSubviews: [label, imageView])
        stackView.translatesAutoresizingMaskIntoConstraints = false
        stackView.axis = .vertical
        stackView.alignment = .top
        stackView.spacing = interItemSpacing

        return stackView
    }()

    private lazy var label: UILabel = {
        let label = UILabel(frame: .zero)
        label.textColor = UIColor.white
        label.lineBreakMode = .byWordWrapping
        label.backgroundColor = UIColor.clear
        label.numberOfLines = 2
        label.font = UIFont.preferredFont(forTextStyle: .caption1)

        return label
    }()

    private lazy var imageView: UIImageView = {
        let imageView = UIImageView(image: nil)
        return imageView
    }()

    private var imageHeightConstraint: NSLayoutConstraint?

    override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
        super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)

        backgroundColor = UIColor.clear
        translatesAutoresizingMaskIntoConstraints = false

        addSubview(stackView)

        // Anchor the top and leading edge of the stack view to let it grow to the content size.
        stackView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: contentInsets.left).isActive = true
        stackView.topAnchor.constraint(equalTo: self.topAnchor, constant: contentInsets.top).isActive = true

        // Limit how much the content is allowed to grow.
        imageView.widthAnchor.constraint(lessThanOrEqualToConstant: maxContentWidth).isActive = true
        label.widthAnchor.constraint(equalTo: imageView.widthAnchor).isActive = true
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func prepareForReuse() {
        super.prepareForReuse()
        imageView.image = nil
        label.text = nil
    }

    override func prepareForDisplay() {
        super.prepareForDisplay()

        /*
         If using the same annotation view and reuse identifier for multiple annotations, iOS will reuse this view by calling `prepareForReuse()`
         so the view can be put into a known default state, and `prepareForDisplay()` right before the annotation view is displayed. This method is the view's opportunity to update itself to display content for the new annotation.
         */
        if let annotation = annotation as? ImageAnnotation {
            label.text = annotation.title
            let placeHolder = #imageLiteral(resourceName: "DSC00042")
            self.imageView.sd_setImage(with: annotation.photoURL, placeholderImage: placeHolder, options: SDWebImageOptions.refreshCached, completed: {(image,error,imageCacheType,storageReference) in
                    if let error = error{
                        print("Uh-Oh an error has occured: \(error.localizedDescription)" )
                    }
                guard let image = image else{
                    return
                }
                if let heightConstraint = self.imageHeightConstraint {
                    self.imageView.removeConstraint(heightConstraint)
                }

                let ratio = image.size.height / image.size.width
                self.imageHeightConstraint = self.imageView.heightAnchor.constraint(equalTo: self.imageView.widthAnchor, multiplier: ratio, constant: 0)
                self.imageHeightConstraint?.isActive = true
                })
        }

        // Since the image and text sizes may have changed, require the system do a layout pass to update the size of the subviews.
        setNeedsLayout()
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        // The stack view will not have a size until a `layoutSubviews()` pass is completed. As this view's overall size is the size
        // of the stack view plus a border area, the layout system needs to know that this layout pass has invalidated this view's
        // `intrinsicContentSize`.
        invalidateIntrinsicContentSize()

        // The annotation view's center is at the annotation's coordinate. For this annotation view, offset the center so that the
        // drawn arrow point is the annotation's coordinate.
        let contentSize = intrinsicContentSize
        centerOffset = CGPoint(x: 0, y: -contentSize.height/2)

        // Now that the view has a new size, the border needs to be redrawn at the new size.
        setNeedsDisplay()
    }

    override var intrinsicContentSize: CGSize {
        var size = stackView.bounds.size
        size.width += contentInsets.left + contentInsets.right
        size.height += contentInsets.top + contentInsets.bottom + 30
        return size
    }

    override func draw(_ rect: CGRect) {
        super.draw(rect)

        // Used to draw the rounded background box and pointer.
        UIColor.darkGray.setFill()

//        let path2 = UIBezierPath(ovalIn: CGRect(x: rect.width/2, y: rect.height - 10, width: 10, height: 10))
//
//        let shapeLayer2 = CAShapeLayer()
//        shapeLayer2.path = path2.cgPath
//        shapeLayer2.fillColor = UIColor.purple.cgColor
//        shapeLayer2.strokeColor = UIColor.white.cgColor
//        shapeLayer2.lineWidth = 1
//
//        layer.addSublayer(shapeLayer2)
//        shapeLayer2.position = CGPoint(x: -10, y: 15)

        // Draw the pointed shape.
//        let pointShape = UIBezierPath(ovalIn: CGRect(x: rect.width/2, y: rect.height - 10, width: 10, height: 10))
//        pointShape.move(to: CGPoint(x: 14, y: 0))
//        pointShape.addLine(to: CGPoint.zero)
//        pointShape.addLine(to: CGPoint(x: rect.size.width, y: rect.size.height))
//        pointShape.fill()

        // Draw the rounded box.
        let box = CGRect(x: boxInset, y: 0, width: rect.size.width - boxInset, height: rect.size.height - 30)
        let roundedRect = UIBezierPath(roundedRect: box, cornerRadius: 5)
        roundedRect.lineWidth = 2
        roundedRect.fill()

        UIColor.purple.setFill()
        let circleDot = UIBezierPath(ovalIn: CGRect(x: box.midX - 7.5, y: rect.size.height - 15, width: 15, height: 15))
        circleDot.lineWidth = 2
        circleDot.fill()

    }
}

Delegate
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    if annotation is MKUserLocation{
        return nil
    }
    if let annotation = annotation as? ImageAnnotation{

        guard let annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "Apple", for: annotation) as? AppleCustomAnnotationView else{
            fatalError("Unexpected annotation view type")
        }
        annotationView.annotation = annotation
        annotationView.clusteringIdentifier = MKMapViewDefaultClusterAnnotationViewReuseIdentifier
        annotationView.collisionMode = .rectangle
        return annotationView
    }else if let cluster = annotation as? MKClusterAnnotation{

        guard let view = mapView.dequeueReusableAnnotationView(withIdentifier: "ClusterAnnotationView", for: annotation) as? AppleClusterAnnotationView else{
            fatalError("Wrong type for cluster annotationview")
        }

        return view
    }
    return nil
}

Answer: There is one very unusual thing you do: you override init and you are doing your main layout work there.
This makes no sense, since an MKAnnotationView can be reused to display different annotations.
You make use of this reuse feature in the delegate.
This way of implementing it is also not shown in the Appl project you are citing.
What you should do in your MKAnnotationView is:
override var annotation: MKAnnotation? {
    willSet {
        // do what you did in override init(...) {...} before.
        // be aware that Apple sets annotation to nil if it is not used any more.
    }
}

in your delegate, after dequeueing only do
annotationView.annotation = annotation

make sure you don't display anything in case of view.annotation == nil.
This makes sure the same layout code is used for the dequeue case and when you create a new MKAnnotationView
Hope this helps
Comment: thank you so much for all of your help I think I fixed it by removing the line `translatesAutoresizingMaskIntoConstraints = false` from the init function of the annotationView
Comment: Thank you for your detailed answer, please see the updates above. I tried your suggestions regarding removing adding constraints inside of init but the same glitches continues. To rule out my custom annotationview I switched to a modified version of the class used in apples project along with your delegate suggestions but the jumpiness still persists do you think it could be related to the clustering
Comment: edit: make sure you don't display anything in case of `view.annotation == nil`.

Glitchy map AnnotationView Behavior


Thread-safe sorted collection that supports iteration in Java

Question: Is there a Collection in java that is :

Thread-Safe
Sorted
Iterable (or has an equivalent method of element access that is thread safe)

I can't seem to find any just by searching google/javadocs thanks for the help!
Answer: What about a skip list?
Satisfies all your constraints:

thread safety
intrinsically sorted
iterable
Comment: EXACTLY what i was looking for thank you, will accept as soon as i can :D
Answer: Just to offer another possibility, you can use the java.util.Collections class to created a synchronized and sorted Set like so:
Set<String> myset = Collections.synchronizedSortedSet(new TreeSet<String>());

It wasn't specified in the question whether you wanted List or Set semantics, so I just thought I'd offer this up as an alternative.  Although I imagine the ConcurrentSkipListSet probably offers better performance because it seems to offer lock free behavior whereas the solution above is synchronized and thus locks.


Determine the number of integer solutions for $x_1+x_2+x_3+x_4+x_5 < 40$

Question: Determine the number of integer solutions for $x_1+x_2+x_3+x_4+x_5 < 40$
a) $x_i \geq 0, i = 1,2,\dots,5$.
b) $x_i \geq -3, i = 1,2,\dots,5$.
c) $-3 \leq x_i \leq 10, i = 1,2,\dots,5$.
My try is
a)$x_1+x_2+x_3+x_4+x_5+x_6=40$
${40+6-1 \choose 40}=1221759$
need help on b) and c)
Comment: For b, let $y_i=x_i+3$, and so $x_i=y_i-3$, so $\sum_i (y_i-3)=40$, so $\sum_i y_i= 40+18$ where $y_i \geq 0$ and now you've reduced the problem to the type of part a.
Comment: Be careful.  In part (a), since $x_1, x_2, x_3, x_4, x_5$ are non-negative integers whose sum is less than $40$, $x_6 \geq 1$.  Let $y_6 = x_6 - 1$.  Then $y_6$ is a non-negative integer.  If we substitute $y_6 + 1$ for $x_6$ in the equation $$x_1 + x_2 + x_3 + x_4 + x_5 + x_6 = 40$$ we obtain $$x_1 + x_2 + x_3 + x_4 + x_5 + y_6 = 39$$ which is an equation in the non-negative integers with $\binom{39 + 5}{5} = \binom{44}{5}$ solutions in the non-negative integers.
Answer: For the first problem, observe that if $x_1, x_2, x_3, x_4, x_5$ are non-negative integers satisfying the inequality
$$x_1 + x_2 + x_3 + x_4 + x_5 < 40 \tag{1}$$
then $x_1 + x_2 + x_3 + x_4 + x_5 \leq 39$.  Let $x_6 = 39 - (x_1 + x_2 + x_3 + x_4 + x_5)$.  Then $x_6$ is a non-negative integer. Moreover, the number of solutions of inequality 1 in the non-negative integers is equal to the number of solutions to the equation
$$x_1 + x_2 + x_3 + x_4 + x_5 + x_6 = 39 \tag{2}$$
in the non-negative integers.  A particular solution to equation 2 corresponds to a choice of where to insert five addition signs in a row of $39$ ones.   Hence, the number of solutions of equation 2 in the non-negative integers is $$\binom{39 + 5}{5} = \binom{44}{5}$$ since we must select which five of the $44$ symbols ($39$ ones and five addition signs) are addition signs.
For the second problem, let $y_k = x_k + 3$ for $1 \leq k \leq 5$.  Since each $x_k \geq -3$, each $y_k$ is a non-negative integer.  Substituting $y_k - 3$ for $x_k$, $1 \leq k \leq 5$ in inequality 1 yields
\begin{align*}
y_1 - 3 + y_2 - 3 + y_3 - 3 + y_4 - 3 + y_5 - 3 & < 40\\
y_1 + y_2 + y_3 + y_5 + y_5 & < 55 \tag{3}
\end{align*}
Then $y_1 + y_2 + y_3 + y_4 + y_5 \leq 54$.  Let $y_6 = 54 - (y_1 + y_2 + y_3 + y_4 + y_5)$.  Then $y_6$ is a non-negative integer.  The number of solutions of inequality 3 in the non-negative integers is equal to the number of solutions of the equation
$$y_1 + y_2 + y_3 + y_4 + y_5 + y_6 = 54 \tag{4}$$
in the non-negative integers.  The number of solutions of equation 4 in the non-negative integers is

 $$\binom{54 + 5}{5} = \binom{59}{5}$$

For the third problem, we must exclude those solutions of the second problem in which at least one of the variables $x_1, x_2, x_3, x_4, x_5$ exceeds $10$.  Since $y_k = x_k + 3$ for $1 \leq k \leq 5$, this is equivalent to excluding those solutions of equation 4 in which one or more of the variables $y_1, y_2, y_3, y_4, y_5$ exceeds $13$.  Since $4 \cdot 14 = 56 > 54$, at most three of the variables $y_1, y_2, y_3, y_4, y_5$ can exceed $13$ simultaneously.
Suppose $y_1 > 13$.  Then $z_1 = y_1 - 14$ is a non-negative integer.  Substituting $z_1 + 14$ for $y_1$ in equation 4 yields
$$z_1 + y_2 + y_3 + y_4 + y_5 + y_6 = 40 \tag{5}$$
Equation 5 has

 $$\binom{40 + 5}{5} = \binom{45}{5}$$

solutions in the non-negative integers.  Since there are $\binom{5}{1}$ ways for one of the variables $y_1, y_2, y_3, y_4, y_5$ to exceed $13$, the number of solutions of equation 4 in the non-negative integers in which one of the variables $y_1, y_2, y_3, y_4, y_5$ exceeds $13$ is

 $$\binom{5}{1}\binom{45}{5}$$

Suppose $y_1, y_2 > 13$.  Let $z_1 = y_1 - 14$; let $y_2 = z_2 - 14$.  Then $z_1, z_2$ are non-negative integers.  Substituting $z_1 + 14$ for $y_1$ and $z_2 + 14$ for $y_2$ in equation 4 yields
$$z_1 + z_2 + y_3 + y_4 + y_5 + y_6 = 26 \tag{6}$$
Equation 6 is an equation with

 $$\binom{26 + 5}{5} = \binom{31}{5}$$

solutions in the non-negative integers.  Since there are $\binom{5}{2}$ ways for two of the variables $y_1, y_2, y_3, y_4, y_5$ to exceed $13$, the number of solutions of equation 4 in the non-negative integers in which two of the variables $y_1, y_2, y_3, y_4, y_5$ exceed $13$ is

 $$\binom{5}{2}\binom{31}{5}$$

By similar argument, the number of solutions of equation 4 in the non-negative integers in which three of the variables $y_1, y_2, y_3, y_4, y_5$ exceed $13$ is

 $$\binom{5}{3}\binom{12 + 5}{5} = \binom{5}{3}\binom{17}{5}$$

By the Inclusion-Exclusion Principle, the number of solutions of the second problem in which $x_k \leq 10$ for $1 \leq k \leq 5$, is

 $$\binom{59}{5} - \binom{5}{1}\binom{45}{5} + \binom{5}{2}\binom{31}{5} - \binom{5}{3}\binom{17}{5}$$
Comment: What happened to the displays?
Comment: @MikeJones  When I scroll over the displays, the hidden expressions or equations are revealed.  What happens when you scroll over them?  I hid the expressions or equations since I wanted the person who posted the question to think about the answers rather than passively reading them.
Comment: Cool! I simply didn't know about that feature / technique.


Trying to work out whether a rectangle will fit within half of a circle.

Question: Probably a really simple question, but I am trynig to fit an air bed in a tent.
Circular tent with a diameter of $3$m and a central vertical pole in the middle.
The air bed measures $1.41$ m $\times$ $1.9$ m.
Will the air bed fit fully inside the tent without being obstructed by the central pole?
Comment: Is height not an issue? If yes, how tall is the tent (is it a true hemisphere) and how tall is the bed?
Answer: It won't. Consider a quarter of the circle with half bed. The corner of the bed will be $\sqrt{1.41^2+\left(\frac{1.9}{2}\right)^2}\approx1.7$ meters distant from the tent's center. It's radius is not enough.
Answer: Not a computation, but I constructed an approximate picture (the relative dimensions should be correct up to $0.01$m):

I think in this case a proof by sketch might be ok. It will not fit in.


Store int value into char* - C++?

Question: I have allocated a block of memory as (char *), in which I want to be able to store an integer.
char * arr = new char[50];
int num = 9;

for(int i = 0; i < sizeof(int); i++)
{
      *((int *)arr) = arr[i];
}

memcpy(&arr, &num, sizeof(num));

cout<<"Contents of arr: "<<arr<<endl;

I seem to be getting a segmentation fault whenever I compile however. How can I fix this? Thank you!
Comment: I thought I would need to cast those (char *) bytes into int bytes first in order to write an int into that block of memory, but I'm guessing it's wrong.
Comment: There are multiple issues with your code. Why are you iterating from 0 to `sizeof(int)`? Why are you copying values _from_ `arr` back in to `arr`? You have a syntax error with the loop's closing brace - `]` in place of `}`. As requested in the "[how to ask a question](http://stackoverflow.com/help/how-to-ask)" code must be correct.
Answer: The for loop is unnecessary.  I'm not sure what it is trying to accomplish.  The memcpy is ok except that you're taking the address of arr which is already a pointer.  This will work:
char * arr = new char[50];
int num = 9;

memcpy(arr, &num, sizeof(num));

cout<<"Contents of arr: "<< ((int *)arr) <<endl;

Perhaps your for loop was trying to do this:
char * arr = new char[50];
int num = 9;

*((int *)arr) = num;

cout<<"Contents of arr: "<< ((int *)arr) << endl;

That would be ok, too.
Edit: The contents of the array are not printable directly, at least not with any meaning (and may crash because of no zero termination).  Assuming you want it to look like an integer, I've edited the code above.  C++ purists will probably object to using a C style cast instead of reinterpret_cast<>, but that's a separate issue.
Comment: Thank you! So I don't get the segmentation fault any more, but what happens is that my output displays, `"Contents of arr: 0xfc76230"`, (after I change `num` to equal 10). Is there a way to fix this?
Comment: DO not forget to take into account potential aligment issues.
Comment: Yes, alignment is definitely an issue for this method in general.  There isn't any guarantee that new char[50] will be int-aligned, although it will be on most compilers.  It would be better to pull the value back out into an int before using it.  memcpy is a safer way to pull the value in and out of a buffer if you're on a platform that is picky about alignment.

Store int value into char* - C++?


If I have that $X$ is a random variable with CDF $F_X(x) = P(X \leq x)$ and PDF $f_X(x)$, what is $\frac{dP(X \leq -x)}{dx}$?

Question: Suppose $X$ is a random variable with CDF $F_X(x) = P(X \leq x)$ and PDF $f_X(x)$, I am trying to find
$$
\frac{dP(X \leq -x)}{dx}
$$
However, I am not familiar with differentiation of the cumulative distribution function. My intuition is that it works like:
$$
\frac{dP(X \leq -x)}{dx} = \frac{dP(X \leq -x)}{d(-x)}\frac{d(-x)}{dx} = (-1)\cdot f_X(-x) = -f_X(-x)
$$
I am not sure what role the random variable $X$ plays here, could someone tell me how I should view it? thanks.
Comment: what do you mean by the " role the random variable X plays here"?
Comment: @msm I am wondering if the derivative is both a function of $x$ and $X$.
Answer: By definition $$F_X(x)=P(X\le x)$$
 The capital $X$ is there to denote the actual random variable but $F_X(x)$ is a function of $x$.
That said,$$P(X\le -x)=F_X(-x)$$ and since $$\frac{d}{dx}F_X(x)=f_X(x)$$ we can say
$$\frac{d}{dx}P(X\le -x)=\frac{d}{dx}F_X(-x)=\frac{d}{dx}(-x)f_X(-x)=-f_X(-x)$$


posição da div fixed em baixo de outras divs

Question: Ola
eu gostaria de colocar uma div fixed do lado direito da minha div sem que fique por cima dos bonecos.
a medida que vou dando scroll essa div vai acompanhando o scroll mas apenas dentro da div preta! os bonecos sao criados automaticamente com base no numero de casos dentro da DB e gostava que a div fixed nao interferi-se com os bonecos.

#images {
    margin: 4px;
    margin-bottom: 6px;
    position: absolute;
    z-index: 2;
  }

#imagess {
    margin: 4px;
    margin-bottom: 6px;
    position: absolute;
    z-index: 1;
  }

.bordadocontador {
    color: white;
    font-size: 18px;
    border: 2px solid #ffff00;
    border-radius: 4px;
    padding: 7px 12px 7px 12px;
    position: fixed;
    z-index: 3;
    float: right;
   }

 Numero de vítimas

bla bla bla

Comment: De modo geral, elementos com `position:fixed` não respeitam seu elemento pai. Ele é guiado pela janela ou documento.
Answer: Vc tem que avaliar como é sua situação ai, mas vc pode trocar o position:fixed por position:sticky, como isso o elemento fica fixo relativo ao pai e aceita o float etc, e não relativo a janela como um todo...
Repare que eu coloquei uma borda preta no col-, pois ela tem apenas a altura do próprio conteúdo, e quando vc faz o scroll ela pode ou não sair da tela, por isso falei que vc tem que estudar seu caso. De qq forma com o position:sticky vc pode chegar a uma solução.

Seria bom vc tirar uma horinha para estudar os positions do CSS, entendendo como eles funcionam vai te ajudar muito a montar layouts. No seu caso esses position:absolutes ao meu ver são desnecessários e podem acabar mais atrapalhando do que ajudando, pense nisso https://developer.mozilla.org/pt-BR/docs/Web/CSS/position
Segue o código da imagem acima.

<!DOCTYPE html>

 <meta charset="utf-8" />
 <title>Page Title</title>
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="stylesheet" type="text/css" media="screen"
  href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" />
 <link rel="stylesheet" type="text/css" media="screen"
  href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />

 Numero de vítimas

bla bla bla

123

Answer: Você pode usar:
position: fixed;
right: 0;
top: 100px;
Comment: Só uma dica, com right:0 e positin:fixed o elemento vai ficar colado na direita da janela do browser, e não colado na direita do elemento no qual está dentro
Comment: Sim, com o que eu postei o elemento vai ficar mais estatico. Caso a div dos bonecos aumentar, elas ficarão sobrepostas.


Guitar exercises for precision and accuracy

Question: I started with metal guitar a little more than a year ago, and mostly learned all this classic Metallica stuff from the 80's like Master of Puppets. Now I can play it up to speed, I can even play it up to 120% of speed. But even at 100% I have the feeling that I lack some accuracy and precision, do not hit all notes evenly, sometimes getting inaccurate when going large distances on the fretboard. This just happens irregularly, even on passages that I can play. So I want to make my playing more consistent.
Any suggestions for effective exercises or songs to improve precision?
Comment: Lacking accuracy  and precision at 100% of the speed means that you actually _can't_ play it at 100% of the speed, let alone 120% of the speed. It's like saying: "I'm a really fast coder, only if I go fast, I create bugs". Drop down to a speed where you _can_ play it without loss of accuracy and precision. Then work your way up to 100% of the speed.
Comment: @WillemvanRumpt Your conclusion is right. But maybe hoped for more specialised exercises than that.
Comment: Sorry, that's why I posted as a comment. I'm self taught (37 years and counting). I've made a ton of mistakes along the way, and still am making tons of them. On top of the list of those mistakes is, was, and always will be: "play too fast too early", and it's topping the list of people who ask me for advice (my first answer is always: "get a teacher (not me)"). Trying to address that takes time, every time, every piece, every practice round, again and again. And I'm happy to say nowadays, I only fail 50% of the time in doing that ;)
Answer: Take lessons.
The path to accuracy and speed on any instrument is the same formula.  Years of methodical, slow, meticulous practice of basic exercises with a metronome.  There are dozens of great books, DVDs, etc out there for developing technique.  But they are all teaching the same basic thing.  You need to get the movements in your muscle memory and optimize hand movement.  One thing is to never play something faster than you able to.  Messy playing does not fix itself through repetition.  Repeating messy riffs trains your body to play messy.
My recommendation would be get your hands on a copy of Try Stetina's book Speed Mechanics for Lead Guitar.  Again, there are many great ones out there but this one really goes into details that are missing in other books.  There is also The Yng Way (a play on Yngwie Malmestin's name) but that really only covers his technique.  And Intellishred by Kevin Dillard.  Metal and shred sort of go together but the techniques apply to every style.  All these books have countless exercises but Troy's book have descriptions of proper posture and suggestions for how to boost speed methodically and how to track your progress.  Many of the other books just throw exercises at you and say play these faster and faster.  imo Troy's book is a step above the rest in terms of education.
Answer: One highly recommended approach is to play things slower... much slower.  Cut the tempo in half and try to play it all with just as much expression/emotion.  This allows you more time to focus on each note a bit more and forces you to play each note with more intention.  Once you really, truly nail it at a slower tempo, move that tempo up in small increments.  Eventually, you will be playing it at speed (or faster) and you'll be able to nail every note solidly and consistently, with great expression.


How to derive the noninformative prior for location parameters and scale parameter?

Question: I am reading this paper, in it:

I have a lot of confusion reading it, I will list it one by one:

Let $X$ be distributed as $f(x-\theta)$, which is a location invariant density.

Q1: The sentence which is a location invariant density, is this a
  assumption or just a claim? If this is a claim, then Gaussian can be
  written in this form but apparently it is a location dependent
  distribution.)

Since the model is location invariant, the prior distribution should be location invariant.

Q2: why so easily the conclusion is draw: the prior distribution
  should be location invariant because the model is location
  invariant. Why bother introduce $Y$?

Q3: why This lead to $\pi(\sigma)=\frac{1}{c}\pi(\frac{\sigma}{c})$
  but not just $\pi(\sigma)=\pi(\frac{\sigma}{c})$? How it is derived, the above formula has no dependence on $\sigma$ but the below one suddenly has the dependence on it? If I just let $A=\sigma$, then it should be $\pi(\sigma)=\pi(\frac{\sigma}{c})$.
Comment: Just pointing out that there is [no such thing as "the" noninformative prior,](http://rads.stackoverflow.com/amzn/click/0387715983) rather a collection of techniques solely based on the likelihood function to construct a prior.
Answer: Regarding Q1, I think of "invariant" as meaning that the density doesn't change if both the observation and parameter are changed in a "compatible" way. Going back to your example of a Gaussian distribution with a known variance and unknown mean, if you shift both the observation and mean parameter by adding some constant number to both of them, you'll end up with the same density height.
It's just an assumption of a model we're working with. Sometimes, when we are working under the Gaussian assumption, it is useful to assume that the variance parameter is not known.
Q2 is a little trickier. If the likelihood is location invariant, that means it only gives us information regarding how far away the observation is from the center. If we want to use a noninformative prior, it should not give us information about, say, the scale. If it did, then that information would remain "unchecked" after we use Bayes' theorem to go from the prior to the posterior. If it does, then this doesn't seem like the prior is noninformative.
Q3 has to do with the transformation theorem. Keep in mind the difference between the argument to the density function, and the random variable that the density describes. If we have a prior for the random variable $\sigma$, and we plug in argument $\sigma$, we evaluate $\pi(\sigma)$. If we transform $\sigma \to \theta = c\sigma$ for some positive constant $c$, then the density for $\theta$ can be written in terms of the original density as
$$
\pi_{\theta}(t) = \pi_{\sigma}(t/c) \frac{1}{c}.
$$
To verify their claim that the prior should be proportional to $1/c$, just plug some argument into both of the priors, and check that they give you the same density height:
\begin{align*}
\pi_{\theta}(a) &= \pi_{\sigma}(a)  \\
\pi_{\sigma}(a/c) \frac{1}{c} &= \pi_{\sigma}(a) \\
\frac{1}{a/c} \frac{1}{c} &= \frac{1}{a} .
\end{align*}
Comment: For Q3, what is the meaning $\pi(A)=\pi(A/c)$, and why it means $\pi(\sigma)=\pi(\sigma/c)/c$?
Comment: @buzhidao I believe I've answered that. The notation in that paper equivocates between the density for $A$ (which I call $\theta$) and the density for $\sigma$. So I introduced new notation with subscripts that tell you which random variable the density belongs to. The stuff inside the parentheses, on the other hand, is the argument to a density
Answer: The first two questions were answered by Taylor (using natural language), here I only give another answer for Q3, using math formulas.
To reflect scale invariance of density of $X$:
$$p(x|\sigma)=\frac{1}{\sigma}f\left(\frac{x}{\sigma}\right),$$
the prior density of $\sigma$ should assign equal probability mass to an interval $A\le\sigma\le B$ as to a scaled interval $A/c\le\sigma\le B/c,\ c>0$. Thus we have
$$\int_A^B\pi(\sigma)d\sigma=\int_{A/c}^{B/c}\pi(\sigma)d\sigma=\int_A^B\frac{1}{c}\pi\left(\frac{\sigma}{c}\right)d\sigma,$$
where the last equality is change of variable $\sigma'=c\sigma$ in integral and changing the notation of new variable $\sigma'$ back to $\sigma$.
Because this equaltion must hold for any choices of $A$ and $B$, we have
$$\pi(\sigma)=\frac{1}{c}\pi\left(\frac{\sigma}{c}\right), \ c>0$$
due to fundamental theorem of calculus. This is the first part of what is led to in the excerpted paper.
The following derives why the above identity implies $\pi(\sigma)=\sigma^{-1}$. By definition of derivative, we have
$$\pi'(\sigma)=\lim\limits_{\Delta\sigma\to0}\frac{\pi(\sigma+\Delta\sigma)-\pi(\sigma)}{\Delta\sigma}.$$
But,
$$\begin{align*}
\pi(\sigma+\Delta\sigma)&=\pi\left(\bigl(1+\frac{\Delta\sigma}{\sigma}\bigr)\sigma\right)\\
&=\pi\left(\frac{\sigma}{\frac{1}{1+\frac{\Delta\sigma}{\sigma}}}\right)\\
&=\frac{1}{1+\frac{\Delta\sigma}{\sigma}}\pi(\sigma)\\
&=\frac{\sigma}{\sigma+\Delta\sigma}\pi(\sigma),
\end{align*}$$
where we used $\pi\left(\frac{\sigma}{c}\right)=c\pi(\sigma)$ which we have proved and in which $c=\frac{1}{1+\frac{\Delta\sigma}{\sigma}}$.
Plugging the expression for $\pi(\sigma+\Delta\sigma)$ into the definition of $\pi'(\sigma)$, we have
$$\begin{align*}
\frac{\pi(\sigma+\Delta\sigma)-\pi(\sigma)}{\Delta\sigma}&=\frac{\left(\frac{\sigma}{\sigma+\Delta\sigma}-1\right)\pi(\sigma)}{\Delta\sigma}\\
&=-\frac{\pi(\sigma)}{\sigma+\Delta\sigma}.
\end{align*}$$
Taking limit $\Delta\sigma\to0$ on both sides, we have
$$\pi'(\sigma)=-\frac{\pi(\sigma)}{\sigma},$$
or $$\frac{\pi'(\sigma)}{\pi(\sigma)}=-\frac{1}{\sigma}.$$
This simple ODE can be easily solved that $\pi(\sigma)=\frac{1}{\sigma}$ if we ignore the constant, which is the second part of what is led to in the excerpted paper.


Tem algum problema ao jogar a função para variável

Question: Alguém sabe me explicar se tem algum problema ao jogar uma função para a variável, por exemplo, nesse caso eu estou falando do var marcar.
Nesse código esta funcionando, eu não sei se isso causa uma perca de performance ou outra coisa. O marcar só irá ser executado nos momentos que realmente for rodar correto?
    $('input:checkbox#marcar').click(function() {
    var valor_id = $(this).data('valor-id'),
        checked  = $(this).is(':checked');

    var marcar = function() {
        $.ajax({
            url: 'marcar.php',
            data: {'valor_id' : valor_id},
            success: function()
            {
                alert('Sucesso!!!');
            }
        });
    }

    if(checked === false)
    {
        $.ajax({
            url: 'verifica.php',
            data: {'valor_id' : valor_id},
            success: function(retorno) {
                var resp = $.parseJSON(retorno);
                if(resp.success === true)
                {
                    var cont = confirm(resp.msg);
                    if(cont === true)
                    {
                        marcar();
                    }
                    else
                    {
                        $this.prop("checked", true);
                    }
                }
                else
                {
                    marcar();
                }
            }
        });
    }
    else
    {
        marcar();
    }

});

Comment: Não há problema nenhum, Marcelo.
Answer: No Javascript você pode referenciar uma variavel a uma função sem problemas. Porém o comportamento vai ser diferente dependendo dos casos.
Função nomeada:
Quando você define uma função nomeada function nome() {} ela é colocada em todo o escopo de execução, por exemplo:
foo(); // alert('ola')
function foo() { alert('ola'); }

Função anonima:
Já se você definir em uma variavel ele só vai existir a partir do momento em que a variavel passou a ter atribuição da função (a variavel existe desde o inicio do contexto), exemplo:
foo(); // undefined
var foo = function () { alert('ola'); }
foo(); // alert('ola')

Criando referencia de função:
Ainda é possível importar métodos de outros objetos, mas cuidado!
var obj = {
    foo: function () { alert('ola'); }
};
var foo = obj.foo;
foo(); // alert('ola');
obj.foo(); // alert('ola');

Referencia de função que usa contexto:
Mas se o método tiver dependencia de contexto você pode ter problemas fazendo esse tipo de mixin, por exemplo:
var obj = {
    texto: 'ola',
    foo: function () { alert(this.texto); }
};
var foo = obj.foo;
foo(); // alert(undefined);
obj.foo(); // alert('ola');

Neste caso quando jogou obj.foo em foo o contexto mais proximo dela é o objeto ẁindow que no caso não tem a propriedade texto e por isso ele retorna undefined.
var obj = {
    texto: 'ola',
    foo: function () { alert(this.texto); }
};
var obj2 = {
    texto: 'tchau'
};
obj2.foo = obj.foo;
obj2.foo(); // alert('tchau');
obj.foo(); // alert('ola');

Veja que neste exemplo o obj2 tem propriedade texto diferente do obj e a função vai retornar o contexto do objeto onde ela se encontra.
Answer: Marcelo, isso é um dos modos de declarar metodos no javascript. Exemplo:
var myvar = function() {
  return true;
}

Além desse modo, tem esse:
function myfunc() {
  return true;
}

Bem como desse modo, você pode definir objetos e arrays em váriaveis. Exemplo:
var myvar = ['Maçã', 'Morango', 'Uva'];

var myobject = {
  frutas = ['Maçã', 'Morango', 'Uva'],
  carros = ['Gol', 'Uno']
};

Answer: Tanto não existe problema quanto isso é uma prática muito comum.
No artigo Javascript: variável como função e objeto você pode ver detalhadamente como funciona.


Shopify product.price.liquid Math Filters not displayed correct

Question: I've added some code in the product.price.liquid to make a simple math formula:

        {{ variant.price | times: 100.0 | divided_by: variant.weight | money }}/100g

Whole Code of the liquid here
Result: On the Product detail page, the result of the math formula is shown right=> Detail Page, but on the collections page or homepage, there comes "Inf"=> Collection Page
Any Ideas?
Comment: Are you sure that you have access to the `variant` object where you are trying to output this price? I mean are you in the `product.variants` loop or have reassigned the `variant` variable?
Comment: Hey, thank your for your answer :-). I'm not sure but if i wouldnt have access to the variant, why is it shown correctly on product detail page but not on other pages because it's the same snippet for showing price on every site where price is visible.
Answer: The last | money parameter might be confusing. Try like this
{% assign variant_price = variant.price | times: 100.0 %}
{% assign variant_price = variant_price | divided_by: variant.weight %}
{% assign variant_price  | money %}
{{ variant_price }}


Cannot use for tag to iterate through Array List in Pebble Template Engine

Question: I have been trying to iterate through an Array List of items with {% for item in items %} syntax to no avail.
Keeps throwing
java.lang.UnsupportedOperationException
    at java.util.AbstractMap.put(AbstractMap.java:209)
    at com.mitchellbosecke.pebble.template.Scope.put(Scope.java:53)
    at   com.mitchellbosecke.pebble.template.ScopeChain.put(ScopeChain.java:61)
at com.mitchellbosecke.pebble.template.EvaluationContext.put(EvaluationContext.java:162) exception.

Tried with primitive arrays, maps, many types of List implementations, always this is the result. When doing an iterable test, the array list returns true, so I think it should be iterable using the for tag. Am I doing something wrong? Please find the code below.
PebbleTemplate template = pebbleEngine.getTemplate(
  "{% if menuItems is iterable %}{% for menuItem in menuItems %}" +
  " \"{{ menuItem }}\" this" +
  "{% endfor %}{% else %}nope{% endif %}");
StringWriter writer = new StringWriter();

List<String> menuItems = new ArrayList<>();
menuItems.add("menu item1");
menuItems.add("menu item2");
menuItems.add("menu item 3");

template.evaluate(writer, Collections.<String,Object>singletonMap("menuItems", menuItems));
System.out.println(writer);

Answer: It depends on the use of the singleton map.
Use an HashMap instead and should work.
Explanation. The Scope is initialised as follows:
public Scope(Map<String, Object> backingMap, boolean isLocal) {
    this.backingMap = (Map)(backingMap == null?new HashMap():backingMap);
    this.isLocal = isLocal;
}

so it actually reuses the map you are providing. When it calls put over the Map, it throws an exception because it is a singleton.
Comment: @javabot I agree! I do not like this approach at all. It is not defensive enough!
To justify it, I use Spring and also there the model is a Map, that probably cannot be considered immutable.  In fact, with a single controller call it can be passed to a method annotated with `@RequestMapping` but also to several methods annotated with `@ModelAttribute`. If it is provided as immutable, then it cannot be populated dynamically.
Comment: That's weird. Never expected the map I am providing for evaluation of the template to be updated by the for loop mechanism. Anyways works like a charm. This is what I have in the map after the for loop. {loop={length=3, index=2}, menuItems=[menu item1, menu item2, menu item 3], menuItem=menu item 3}


For the family of distributions, $f_\theta(x) = \theta x^{\theta-1}$, what is the sufficient statistic corresponding to the monotone likelihood ratio?

Question: Suppose I have a sequence of iid random variables $X_1, \ldots, X_n$ following the pdf:
$$
f_\theta (x) = \theta x^{\theta-1}
$$
for $\theta >0$ and $0 <x<1$.
I would like to find a sufficient statistic $T(X)$, such that the family $f_\theta (x)$ has a monotone
likelihood ratio (MLR) in $T(X)$.
I do this by having:
$$
\frac{f(x|\theta_1)}{f(x|\theta_2)} = \frac{\prod_{i=1}^{n}\theta_1x_i^{\theta_1-1}}{\prod_{i=1}^{n}\theta_2x_i^{\theta_2-1}} = \left(\frac{\theta_1}{\theta_2}\right)^n \prod_{i=1}^n\left(x_i\right)^{\theta_1-\theta_2} = \left(\frac{\theta_1}{\theta_2}\right)^n \left(\prod_{i=1}^nx_i\right)^{\theta_1-\theta_2}
$$
At this point, is the statistic corresponding to the MLR $\prod_{i=1}^nx_i$? If this is the case, what is the distribution of $\prod_{i=1}^n$ which is HARD to find?
Or would it be:
$$
\frac{f(x|\theta_1)}{f(x|\theta_2)}  = \left(\frac{\theta_1}{\theta_2}\right)^n \left(\prod_{i=1}^nx_i\right)^{\theta_1-\theta_2} = \left(\frac{\theta_1}{\theta_2}\right)^n \left(e^{\sum_{i=1}^n \log(x_i)}\right)^{\theta_1-\theta_2}
$$
and hence the sufficient statistic is $\sum_{i=1}^n \log(x_i)$ which has Gamma distribution?
Comment: One problem you don't explain where y comes from.
Comment: I don't think the function is a density for all theta >0 without further constraint on the range of x.  Maybe that is where y comes in.
Comment: @MichaelChernick Sorry, $y$ should be $x$ here, I fixed it above
Comment: I think that will help a lot.
Answer: You are correct that$$\prod_{i=1}^n x_i$$is sufficient. But since any bijective transform of a sufficient statistic is also sufficient$$\sum_{i=1}^n \log(x_i)=\log\left(\prod_{i=1}^n x_i\right)$$is also sufficient.
You are also correct that$$y=-\log(x)\sim\mathcal{G}a(1,\theta)$$and thus that the sufficient statistic$$-\sum_{i=1}^n \log(x_i)=\sum_{i=1}^n y_i\sim\mathcal{G}a(n,\theta)$$
Comment: This is clearly stated in my answer: any bijective transform like $\log$ is also sufficient, hence there is no unique distribution for a sufficient statistic.
Comment: What is confusing me is that if we instead used the first statistic, $\prod_{i=1}^n x_i$, its distribution will change and no longer be Gamma. How can a monotone likelihood property admit multiple sufficient statistics up to a bijection but also yield different distributions of that sufficient statistic? In other words, why isn't there a unique distribution when asked to find the sufficient statistic for a monotone likelihood property? Thanks!!


Infinite source rectangle to drawImage method

Question: Why do i always get this log, Infinite source rectangle to drawImage method, is this such an error or there's something wrong with the code algorithm. I don't really understand about this, and i can't find any useful information on google. Hope i can find the answer on this site.
sorry, this is my drawRect method :
- (void)drawRect:(NSRect)rect {
    // Drawing code here.

    // drawBackground
    [[NSColor colorWithCalibratedRed:0 green:0 blue:0 alpha:1.0] set];
    [NSBezierPath fillRect:[self bounds]];

    if (myCIImage != nil) {

        //Create the CIContext
        CIContext *context =  [[NSGraphicsContext currentContext] CIContext];

        //scale to fit in view rect
        CIImage *drawnImage;
        if (previewFilter == YES) {
            drawnImage = [previewImage imageByApplyingTransform:[self imageTransformToFitView]];
        } else {
            drawnImage = [myCIImage imageByApplyingTransform:[self imageTransformToFitView]];
        }

        // center in view rect
        NSRect viewBounds = [self bounds];
        CGRect sRect = [drawnImage extent];
        CGRect dRect = sRect;
        dRect.origin.x = viewBounds.origin.x + (viewBounds.size.width - sRect.size.width)/2;
        dRect.origin.y = viewBounds.origin.y + (viewBounds.size.height - sRect.size.height)/2;

        [context drawImage:drawnImage
                    inRect:dRect
                  fromRect:sRect];

    }

}

thanks -
Comment: Help, I wrote this code but it gives wrong result. Honestly, how could anyone help you without seeing the code?
Comment: well, i don't really know which part of my code that resulting this log. I was modified my app to support with the MotionBlur filter. The other filter is works very well but this one. I bind the inputRadius value and inputAngle value with the horizontal sliders, this is the same method as i used for another filter.
Comment: If you get a log message that says you passed an infinite source rectangle to the `drawImage:::` method, it's probably because you passed an infinite source rectangle to the `drawImage:::` method. The next step is to find out why your source rectangle is infinite. Read your code: What have you written that affects the source rectangle?
Comment: have you solved this?
Answer: I think that means the dimensions of sRect contain some infinite numbers.  Have you run this under the debugger and inspected the values in sRect?
Probably the transform you apply to the image is wrong.


How to increase performance of bash scripts called by child_process's

Question: I'm working with pdftotext to extract text from multiple PDF 's in parallel,
using a mix of child_process.spawn and async.mapLimit to limit the number of concurrence.
My question is regarding performance. I get a little lost in relation to CPU intensive work.
I'm opening the processes using Node.js, it means I'm doing CPU intensive
 with Node.js (since it is his child process), or I'm doing with bash?
Is there any way to improve performance? Often the program takes up hours to complete a job, because the amount of files + their size . Frankly I do not know very much about bash, is there anything I can do to improve the parallel processing?
Comment: [GNU parallel](https://en.wikipedia.org/wiki/GNU_parallel)?
Comment: or `xargs`. It also depends on if your system is well balanced in CPU/RAM/Disk AND that the systems are functioning well. If you're relying on a SAN disk array, you'll want to be sure that it is functioning correctly. (Sorry I can't give you an easy test for that, but try benchmarking `gzip -c 1GBfile > /mount/path/1/1GBfile.gz` to numerous subsections of your `/mount` filesystem and note which ones take significantly longer than a local disk. (This is the subject of a multi-part magazine article, so put on your thinking cap ;-) ). Good luck.
Comment: You could try to use .exec .execFile or .fork instead of .spawn. I believe spawn is most appropriate if you have large single tasks.
https://dzone.com/articles/understanding-execfile-spawn-exec-and-fork-in-node
Answer:
You could try to use .exec, .execFile or .fork instead of .spawn. I believe spawn, which you're using, is most appropriate if you have large single tasks.
See: https://dzone.com/articles/understanding-execfile-spawn-exec-and-fork-in-node
Run the system monitor tool top or htop and observe your CPU consumption while the processing is running: are all cores maxed out? This way you can determine if CPU is your current bottleneck.
It may be that pdftotext is inherently slow. Can you find a faster library or switch from Node to something else? An indication of a fast Node library might be that the library is just a set of C bindings.


How to format webpage before it is loaded javascript

Question: Ok. I am making a website on github using html and javascript. Earlier, I was using a template to make simple, formatted webpages. I got it to work, but it has an annoying bug: the unformatted webpage shows up before the formatted one. I am using the latest version of jquery (2.1.4) hosted from google and the javascript below:
var heading = document.getElementById("heading").innerHTML;
var pghead = document.getElementById("pghead").innerHTML;
var pgtext = document.getElementById("pgtext").innerHTML;
var template = function () {
  var tmp = null;
  $.ajax({
      'async': false,
      'dataType': 'html',
      'url': "https://jediguy13.github.io/template.html",
      'success': function (data) {
          tmp = data;
      }
  });
  return tmp.split("derp");
}();
document.write(template[0] + heading + template[1] + pghead + template[2] + pgtext + template[3]);
document.getElementById("heading").innerHTML = "";
document.getElementById("pghead").innerHTML = "";
document.getElementById("pgtext").innerHTML = "";

And here's a sample webpage:

Test

Test

This is some text in the main body of the webpage

As you can see from the 'async': false. line, Jquery is requesting the template webpage at the same time as the main thread. However, there is always a slight delay in the formatting. I'm betting it is because the document.write is called near the end. What is a better way to get the browser to display just the formatted page?
Example page: website
Comment: This is standard. Server side whatevers first, then HTML, then Javascript takes over. If you need Javascript on the server, use Node, otherwise use whatever you are using on the server (PHP, .NET, whatever) to deal with this formatting.
Answer: Okay, so first off I'm going to say you shouldn't rely on JS to format your entire page unless you're hosting a single-page application, and even then... probably not the entire page.
To answer your question, the only way to not show the unformatted page is to hide your content until the page loads. Give your body tag or container style='display:none;' and then when your JS has finished executing, show the content with by calling something like $('body').show().
Answer: Don't use document.write(). Ever. If you have an HTML snippet, just attach it to the desired node like this:
$("body").html(template[0] + ...);

If the page is originally empty and all the content is loaded with AJAX, then you'll see a white page that then is filled with your code.
In your case it will NOT be empty as I can guess, so you have to clear the HTML immediately after you fetch it:
heading = $("#heading").html();
$("#heading").html("");

This will minimize the original exposure of the HTML.
At this point you may want to fade it in slowly, like this:
$("body").hide();
// ... make AJAX call and attach it as shown above
$("body").fadeIn();

The fadeIn() is a touch of class you might as well replace with show().
Make the AJAX call asynchronous and put all of this into the AJAX success() method.
This is all together in a complete rewrite. Just copy+paste and tell me if it's working:
var heading, pghead, pgtext;

$("body").hide();

heading = $("#heading").html();
pghead = $("#pghead").html();
pgtext = $("#pgtext").html();
$("#heading").html("");
$("#pghead").html("");
$("#pgtext").html("");

$.ajax({
  'async': true,
  'dataType': 'html',
  'url': "https://jediguy13.github.io/template.html",
  'success': function (data) {
      template = data.split("derp");
      $("body").html(template[0] + heading + template[1] + pghead + template[2] + pgtext + template[3]);
      $("body").fadeIn();
  }
});

Comment: I also had to use @James G. 's answer to get it to not show text at all. The problem is that the javascript is still running after the page has loaded.
Answer: one of my favourite tricks is to place a loader div and keep the content hidden and the loader visible until all JS based layout changes are completed. provided you have the luxury of using Jquery (or CSS3) you can use an easing effect on the opacity to give it a much better feel.


Django - redirect another client to a specific page

Question: This may be weird. Here is the scenario:
I have a view. And there are 2 clients connected to my django app. what i want is, when client1 sends a request to my view; i want to redirect client2 to another url. for example (pseudo-like) :
def some_view(request, other_clients_username):
    try:
        client2 = UserProfile.objects.get(username=other_clients_username)
    except:
        return HttpResponseNotFound('user not found')

    client2.redirect('/door-screen/')
    return HttpResponse('%s redirected successfully', %client2.username)

client1 sends a request to some_view with a username parameter.
If user exists, the client which is logged in by user should be redirected to door-screen page.
Before this i never needed something like this. I even cant imagine how to do this. Redirecting a user which is not request's owner.
Any kind of help would be great.
Thank you.
Comment: `client1` and `client2` accessing same view doesn't mean both are stored there . both request will be considered as separate and none knew about which client is currently accessing that view . As I understand , you want functionality that at any time only one user is accessing your particular view . is it ?
Comment: @PriyankPatel yes. `client1` and `client2` doesn't have to access to same view at same moment. one of them accesses that view, and redirects other one to some url.
Comment: you need some transaction lock type functionality . I would create one db table (with only one entry) and store current user who is accessing that view in that table . But I believe it will have a negative impact on performance .
Comment: what do you want your client2 to be like? I mean who is the target? how do you want to specificaly refer to this client2? Is it a client with a certain username or email? Is it a client that has the oldest login session? or is it a group of clients? or all the clients?
Comment: @MihaiZamfir all clients are registered and logged in users with an active session. and yes, i can find them by username or their `PK`.
Comment: ok, so you want to redirect all the other users that are logged in, right?
Comment: not all of them. particular ones. one redirection on each request @MihaiZamfir
Comment: which particular one? you have to know which user you want to redirect. how do you target him?
Answer: One solution to your problem would be to use websockets or a library like Pusher. Basically you'd send a message out on the wire within pusher that would tell client2's browser to redirect to a given URL. Obviously this is fairly easy to get around if a user knows that's going to happen.
Anyway, your backend view would look something like this:
p = pusher.Pusher(app_id='your-pusher-app-id', key='your-pusher-key', secret='your-pusher-secret')
p[client2.pusher_channel].trigger('redirect', {'url': '/door-screen/'})

Note that this assumes you're using https://github.com/pusher/pusher_client_python
Your template would need to pass the pusher channel though so client2's browser connects to the right channel. You can do that by either storing the channel id in a hidden input, rendering it as a var in javascript on the template itself, or you could even have it be passed through an ajax call. Though I'd probably go with one of the first two just because it's significantly easier.


CLR question. Why method overloading in C# decides that null is a string?

Question:
Possible Duplicate:
C#: Passing null to overloaded method - which method is called?

Here is a test case
object a = null;
var b = Convert.ToString (null);
var c = Convert.ToString (a);
string d = Convert.ToString (null); // CLR chooses Convert.ToString(string value)
string e = Convert.ToString (a); // CLR chooses Convert.ToString(object value)

The question is why CLR decides that null is interpreted as string in first case? It appears that this question was already answered here
Here is another similar case. None of these ifs are triggered
object x = null;
if (x is object)
{
    Console.Write ("x is object");
}

if (x is string)
{
    Console.Write ("x is string");
}

if (null is object)
{
    Console.Write ("null is object");
}

if (null is string)
{
    Console.Write ("null is string");
}

Comment: Possible Duplicate: http://stackoverflow.com/questions/719546/c-passing-null-to-overloaded-method-which-method-is-called
Comment: I suppose we wait until Jon Skeet wakes up and enlightens us on this one.
Comment: He already has, on the link that CMS posted.
Answer: The answer is because it must choose a reference type (null doesn't work for value types), and every string is an object, but not every object is a string. See Jon Skeet's answer to this question for more information.
In response to your second example, if a variable that is null is passed to is, it will always evaluate to false, no matter what.
Answer: In overload resolution, when faced with a choice of resolving a parameter to a base class or a derived class, the compiler will always choose the most derived class if it fits. This enables overloads which take a derived class not being ambiguous with overloads which take the base class. In this case, since string is dervied from object, string is preferred.
For details, look at Section 7.4.3 in the C# Language Specification.  There's a very complex discussion there, but the basic idea is that there's an algorithm that the compiler uses to define the "best" overload, and one of the things that makes one better than the other is this:

• for at least one argument, the
  conversion from EX to PX is better
  than the conversion from EX to QX.

Reading on:

• If an implicit conversion from T1 to
  T2 exists, and no implicit conversion
  from T2 to T1 exists, C1 is the better
  conversion.

Since there's an implicit conversion from any derived class to its base, but not vice-versa, the rules above mean that any matching dervied-class overload always beats out a base-class parameter in an overload.
Comment: Any reference to source?


Button color changes only at the end of for loop

Question: I am having 13 buttons and need to change the color of the button one by one.In below code "copyview" has button id and  "TextToSpeech"calls the TextToSpeech method. My problem is I am making to speak charter by character in tamil. But the button color changes only when for loop ends. The color of buttons are not changing one by one, at a stretch at the end of for loop all button colors changes to white. But  no problem with audio it play perfect. What I am suppose to do to make the color of button to get changed  one by one..
<code>     for(int i=0;i<Uirkeys.length;i++){
        try {
            TeaxtToSpeach(map.get(Uirkeys[i]));
            copyView.get(i).setBackgroundColor(Color.WHITE);
            Thread.sleep(700);
        } catch (InterruptedException e) {
           e.printStackTrace();
        }
    }
</code>
Comment: it will change immediately if you get rid of  Thread.sleep(700);
Comment: I need to wait for the audio to get complted and after that need to change the btn color.
Comment: I need to make for loop wait for each 700 ms for each increment how can I do that
Comment: NEVER use `Thread.sleep(...)` EVER. In particular you will cause problem locking up the UI when it's used. Instead of waiting for a set time, you should be using `TextToSpeech.OnUtteranceCompletedListener` or `UtteranceProgressListener` if you target API 18 or greater. The callback of the listener is called after the TTS system has finished  'speaking' and you can use it to change the button colour.
Answer: You need to run it in the UI thread because you are running a UI change
this is an example
<code>Activity.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            TeaxtToSpeach(map.get(Uirkeys[i]));
            copyView.get(i).setBackgroundColor(Color.WHITE);
        }
});
</code>


Is derivative always continuous?

Question: Is the derivative of a differentiable function always continuous?
My intuition goes like this: If we imagine derivative as function which describes slopes of (special) tangent lines to points on a curve given by $f(x)$, then that slopes must be gradually bigger or smaller, but also I am not sure if this is true.
I can't find counter example; $(x^2)' = 2x, (\sin{x})'= \cos{x}, (e^x)' = e^x,$ etc. This derivatives are all continuous functions.
Examples, intuition, proofs  - all are welcome.
Comment: The graduality is described by the *mean value property* of the derivative, which is infact true! However, continuity is far too much to demand.
Comment: Study $f(x) = x^2 \sin\frac1x$ with $f(0)=0$.
Answer: Unfortunately, this is not the case. It is true that there cannot be a jump, but there is an other possibility for discontinuities: oscillations. Take for example $f$ defined by
$$
f(x) = x^2\sin(1/x)
$$
for $x\neq 0$ and $f(0)=0$. Then $f$ is differentiable (check it!) but the derivative is not continuous at zero (check it!). In the original function, the oscillations are made insignificant by a scaling around zero, but this can change by differentiation.
Next time, you might want to check the Wikipedia entry on your subject before asking the question here.
Comment: $f$ is not defined at $0$, and hence is not differentiable/continuous at $0$...
Comment: You have to come back to the definition of derivative. It is $\dfrac{f(x)-f(0)}{x-0}=\dfrac{x^2\sin(1/x)}{x}= x\sin(1/x)$. Since $\sin$ is bounded, this goes to zero as $x$ goes to zero. That means that $f$ is differentiable at zero with $f'(0)=0$.
Comment: @DonThousand I had for some reason forgotten the "=0". I have added it now.
Comment: @Mushu Nrek, sorry for late comment but I don't understand how $f$ is differentiable - slopes are going "crazy" in both directions from $x = 0$...

Is derivative always continuous?


Bernoulli Confidence Intervals for p very close to 0

Question: Let's say I have the following observations from many Bernoulli distributions with different p (p1, p2, ..):
Observations from Distribution 1: 10 successes, 100,000 trials, p_hat = 0.0001
Observations from Distribution 2: 0 successes, 100 trials, p_hat = 0
Observations from Distribution 3: 4 successes, 60,000 trials, p_hat = 0.00007
I want to order these distributions by their true probabilities of success and get rid of the ones that have low probability of success. However, because of the inherent nature of these distributions, the probability of success is so low, that if I use a standard Wald and Wilson confidence interval for Bernoulli distributions, the results don't make too much sense.
Is there a standard statistical way to deal with these types of problems? Or do I have to resort to some self defined heuristics to remove distributions with low probability of success?
Comment: Clopper-Pearson binomial CIs (http://en.m.wikipedia.org/wiki/Binomial_proportion_confidence_interval) are an alternative to Wilson's method. There is no simple formula, but most stats software can deal with them. They are exact in the sense that they are never too narrow. It might be an idea to just look at lower confidence limits.
Comment: Btw, these CIs can't fall outside the unit interval.
Comment: Are the sample sizes fixed in advance? If not, you could use inverse binomial samplig, which basically reverses the problem: you set a desired confidence interval and confidence leve, and there's a stopping rule which tells you how long to continue sampling in order to guarantee that confidence interval and confidence level.
Answer: Confidence intervals are great, but

With probabilities near zero, different takes on how to do it have to be considered. The question and discussion so far mention various possibilities. The paper by Brown and friends in Statistical Science 2001
remains the best guide I know for 21st century statisticians and data analysts.

With sample sizes this different, overlap of intervals is inevitable and a clear ordering a little elusive.

The leading evidence arguably remains the point estimates.

Putting your cases in different order, of the point estimates 0.0001, 0.00007, 0, Stata gives for 95% confidence intervals:

Exact          0.0000480         0.0001839
Agresti        0.0000515         0.0001869
Jeffreys       0.0000514         0.0001774
Wald           0.0000380         0.0001620
Wilson         0.0000543         0.0001841

Exact          0.0000182         0.0001707
Agresti        0.0000192         0.0001781
Jeffreys       0.0000225         0.0001585
Wald           0.0000013         0.0001320
Wilson         0.0000259         0.0001714

Exact          0.0000000         0.0362167
Agresti        0.0000000         0.0444121
Jeffreys       0.0000000         0.0247453
Wald           0.0000000         0.0000000
Wilson         0.0000000         0.0369935

Notes: "Exact" here means Clopper-Pearson. Stata is explicit that it clips at 0 (or 1).
Normally I would add a graph, but its main point would be that the intervals for the $n = 100$ sample are massively larger, and logarithmic scale is not appropriate here.
If the samples were from quite different populations, you would have to take all the samples seriously. Otherwise one possible conclusion is that the sample of $n = 100$ is far too small to take seriously compared with the other samples.
Answer: One possibility is to use a Jeffreys Interval, which has a Bayesian derivation. One nice feature is that you're guaranteed to get values between 0 and 1. When using a Wald interval on similar problems I got negative lower bounds, which made no sense.
The confidence intervals are found by computing the $\alpha$ quantiles of a $\text{Beta}(x + 1/2, n – x + 1/2)$ distribution. Where $x$ is the number of successes and $n$ is the number of trials. Computing these quantiles must be done numerically, but it's no problem in something like R.
Comment: This has a frequentist interpretation too.


Parallel image processing with MATLAB

Question: I have written a MATLAB program which performs calculations on a video. I think it is a perfect candidate to adapt to multiple cpu cores as there is a lot of averaging done. I am just sturggling with the first bit of sending each section of frames to each lab. Say (for simplicity) it is a 200 frame file. I have read some guides and using SPMD gotten this.
spmd
limitA = 1;
limitB = 200;
a = floor(((limitB-limitA)/numlabs)*(labindex-1)+limitA);
b = floor((((limitB-limitA)/numlabs)*(labindex-1)+limitA)+(((limitB-limitA)/numlabs)));
fprintf (1,'Lab %d works on [%f,%f].\n',labindex,a,b);
end

It successfully outputs that each worker will work on their respective section (Eg Lab 1 works on 1:50, Lab 2 50:100 etc).
Now where I am stuck is how do actually make my main body of code work on each Lab's section of frames. Is there a tip or an easy way to now edit my main code so it knows what frames to work on based on labindex? Adding spmd to the loop results in an error hence my question.
Thanks
Answer: Following on from what you had, don't you simply need something like this:
spmd
    % each lab has its own different values for 'a' and 'b'
    for idx = a:b
        frame = readFrame(idx); % or whatever
        newFrame = doSomethingWith(frame);
        writeFrame(idx, newFrame);
    end
end

Of course, if that's the sort of thing you're doing, you may need to serialize the frame writing (i.e. make sure only one process at a time is writing).
Comment: Hey, That helps a lot. I just couldn't get my head around controlling each individual lab to work on its frame sections. But now I see that as you say, each lab sees its own "a and b". Should be able to get something going from here. Thanks.

Parallel image processing with MATLAB


Own method displayed in django template

Question: I wrote my / sample method and want to show it in the django template.
I am trying to {{filter.my_method}} and nothing it does not give.
Below my model with the method and view.
My model and my method:
class MyModel(models.Model):
    user = models.ForeignKey(User, blank=True, null=True)
    name = models.CharField(max_length=255, blank=True, null=True)

    def __unicode__(self):
        return self.user

    def my_method(self):
        return self.name

My view
class Index(ListView):

    template_name = "index.html"
    context_object_name = 'users'

    def get(self, request):
        filter = Filter(request.GET, queryset=MyModel.objects.all())
        return render(request, self.template_name, {'filter': filter})

Answer: You should call this method not on the filter but on the model instance:
{% for obj in filter %}
    {{ obj.my_method }}
{% endfor %}

Comment: Filter.objects.all() returns a list when evaluated while your method is running on single instances. This answer will let you run your method on every instance in that queryset.
Comment: @cdvv7788 and catavaran - Thanks :)

Own method displayed in django template


Sorting JavaScript object arrays based on arbitrary lenght of properties

Question: I have a JavaScript sort array function which takes a string I provide it, which is the name of the property I want to sort by and it sorts my array by that property name.
Thus:
function sortProp(myArr, prop) {
    return myArray.sort(function (a, b) {
        return a[prop] < b[prop];
    }
}

What I would like, is for this sort function to continue taking this string but can read it as an arbitrary length of properties to sort by; this is probably explained easier in an example below:
I have a JavaScript array of objects which takes the following structure (this is just an example to show multi-level nesting I have):
{
    {
        "Name" : "John Smith"
        "Address" : {
            "Line 1" : "123 Some Street"
            "Line 2" : "Some Neighbourhood"
            "Town" : "Some Town"
            "PostCode" : "ST1 1ST"
            "Contract" : {
                "Name" : "CON1"
                "Hours" : 24
            }
        }
    },

    {
        "Name" : "Mary Jones"
        "Address" : {
            "Line 1" : "321 Some Other Street"
            "Line 2" : "Some Other Neighbourhood"
            "Town" : "Some Other Town"
            "PostCode" : "SO1 1OS"
            "Contract" : {
                "Name" : "CON2"
                "Hours" : 48
            }
        }
    }
}

On my user interface, I have a dropdown which certain values to the properties in this array; thus I might have sort by:

"Name"
"Address.PostCode"
"Address.Contract.Hours"

However, at the moment my sort function has to decode how many '.' there are by splitting at it, then I can sort based on arr[prop1] or arr[prop1][prop2] or arr[prop1][prop2][prop3] which means I have to explicitly state the array depth I'm referring to.
Ideally what I'd like, is to provide it that string, then the function works out the level of nesting it needs - but I can't figure out how to do that since I'm not sure of any other way other than explicitly stating the array indexes.
Is there something that can be achieves, so I can pass my sort function some of the following, and it works out the nesting required without me having to write hardcode the array depths, e.g.:
sort(myArray, "Name")
sort(myArray, "Address.PostCode")
sort(myArray, "Address.Contract.Hours")
sort(myArray, "Address.Contract.ExampleProp1")
sort(myArray, "Address.Contract.ExampleProp1.ExampleProp2.ExampleProp3")

Thus, so I can provide it an argument of any sized property length and it figures that out.
Hope that makes sense :) thanks.
Edit 1: changed the title
Edit 2: corrected my first
Answer: Use cmp from Grouped sorting on a JS array and ref from Convert string in dot notation to get the object reference ;)
prop = "Address.Contract.ExampleProp1"
ary.sort(function(a, b) {
    return cmp(ref(a, prop), ref(b, prop))
})


How to connect headphone output to a "balanced" monitor speaker?

Question: It seems complicated to connect a digital piano's headphone output to a monitor speaker which takes a "balanced" input.  How is it done?
It seems what a "balanced input" is, is to use 3 wires to send a signal, so that no matter how long the cable is (such as 25 feet), the noise can be canceled out. Some info here, here, and here.
So then, if we get one of these speakers, such as the Yamaha HS5 or HS8, then how do we connect a digital piano's headphone output to it?  There are TRS to XLR cables that connect Tip and Ring together... but will it work? (because if one signal is subtracted from another, then it becomes 0).  If we use the "pure" TRS to TRS or TRS to XLR cables, is it true that it won't work?  Or do we need a mixer to do that, because if we do, it may seem like the easiest way is to use a regular computer speaker pair.  Also, the cable I use is merely 5 foot long, so it is not like it really needs a "balanced" connection. One possible way a cable can work is, if the ring is totally disconnected, then when the "balanced" signal is obtained, the positive is subtracted from the negative (which is always 0), and we still get the positive signal to output to the speaker. (but so far I have not seen such cable being sold on Amazon). If we connect Tip and Ring, then they subtract to become 0 and should not work. (Amazon does sell cables that connect Tip and Ring together).
The question is, what if we want to connect the digital piano's headphone output to a studio monitor like the Yamaha HS5 with balanced input, how is it done? (and is it a good choice to do that?)
Comment: Headphone outs are not well-suited to connecting to line-in, even if you make up a cable to unbalance it. They will be impedance & voltage mis-matched.
Comment: I tried to provide an answer, but I'd need some more details to be more specific: 1. what piano model (perhaps it has line outputs as well?) 2. Do you want to connect to Yamaha HS5 specifically, or some other speaker? 3. Do you want to use two speakers or only one? It may not be obvious, but digital piano signal is stereo.
Comment: I do have a couple of digital pianos (some are like $200 such as the Casio CT-S1, but this one probably doesn't need an external speaker as it sounds good AS IS)... but my concern is mainly headphone out, because such as the P125, I think it has no Line Out, but just headphone out and headphone out is more universal... also, I am ok for mono for now... as I just want to spend $200 on one HS5... but it makes me wonder if I want stereo, how is the TSR cable going to make it stereo with one cable needing to output to two HS5?
Answer:
Yamaha HS5 has both balanced and unbalanced input, you can simply use the latter.

If you're looking for other devices, some of them have a "combo" inputs, which may seem like XLR at first, but in fact allow also to connect an unbalanced 1/4" jack. Check your device spec sheet.

I agree, piano headphone or line output should be quite strong and should work fine with an unbalanced connection. Give it a try. The worst thing I can think of are ground loops which may add some noise.

As you wrote with a properly made cable you can connect an unbalanced output to a balanced input, but the connection will be still unbalanced. It might be good enough for you.

For a truly balanced connection you indeed need to convert the signal. You could use a mixer, as you proposed, but a more typical tool for the job is a DI box.
Comment: It will - it will also knock your headphone output by 6dB. I'd still make darn sure you drop the volumes before doing it. It's not something I've ever tried but it just doesn't sound like a good idea to me. [My monitors are 200W each with no input attenuation… not going to plug those into anything at random ;))
Comment: @nonopolarity if you plug a TS jack into a TRS balanced mono output you'll get an unbalanced signal. But phone output is unbalanced _stereo_.
Comment: The jacks on the HS5 are also balanced, TRS… & the 'worst' thing that can happen if you whack a headphone out into a line in without attenuating hard is "bang, there go the cones."
Comment: Manual has this, for both types - https://i.stack.imgur.com/yDW7r.png - only figure it gives is Input Sensitivity / Impedance: -10 dBu/10k ohms [Manual link](https://jp.yamaha.com/files/download/other_assets/4/793644/hs8i_en_om_c0.pdf)
Comment: @Tetsujin Thanks, I didn't realize. But at least it makes the connection easier, you can just plug an unbalanced TS jack it for an unbalanced connection.
Comment: yeah, the HS5 specs say it is balanced input, but the product description says it is for balanced and unbalanced input, so confusing.  Now, the "Ring" is just 0 type of cable may exist: it is the TS to XLR cable... so the "Ring" is missing and is always 0, therefore when the subtraction is done, we only get one signal. But right now, since HS5 takes unbalanced input, so I will just use TSR to TSR cables and there should be no problem with it
Comment: Also, I think this cable works for unbalanced to balanced: get a TSR to TS + TS cable. Then now, plug the TSR into digital piano's headphone out, and feed the TS to the monitor speaker. The speaker takes the positive signal and subtract from the negative, but it is the same as ground, which is 0, so now the speaker just takes the unbalanced signal as if it is balanced and can still play some sound. The same should go for, if the TS is plugged into piano's headphone out, and the TSR is plugged into the monitor speaker
Comment: @nonopolarity yes, you need a TSR to TS+TS cable like that. If you tried to connect the headphone out to a single HS5 with a TRS-TRS cable, the monitors would subtract left and right channels, which would result in cancellation of big portion of your sound.
Comment: oh my goodness... so I got the wrong cable (again)... I need a TS to TS cable? (or a TSR to TS + TS cable). I thought HS5 can handle unbalanced input AS IS (its built in circuitry can handle that), but no... it is through a hack of "nothing for you to subtract"?  It is like the stone age...
Comment: @nonopolarity yes, but in the headphone output you get "something" to subtract – the right channel in the "ring"
Comment: a bit interesting... it is like "balanced" cable is a better world, but to have backward compatibility, simply use a mono TS to TS cable... so that R is the same as S and nothing for the T to subtract... it is like utf-8 is a more advanced character system, and it is backward compatible with all the ASCII (I think 7 bit ASCII) algorithms we have in the past...
Answer: If you can convince your keyboard to pan everything hard to the left (namely with the right channel being silent), you get output that is pretty suitable for a balanced input by just using a normal balanced TRS cable (the difference to a stereo cable is subtle: a balanced cable has a defined twist of both signal wires): a balanced input works by interpreting the difference between its two inputs, and the difference to a signal that is zero is just the non-zero signal.  How does this differ from an unbalanced connection?  For one, the shield is not running signal current.  For another, the source impedances of both "signals" are the same since they are from the same headphone circuit.
Some balanced outputs are actually implemented that way (with a matched resistor pair from ground and a low-impedancy output connecting to return and signal wires) while the "proper" way is sending an inverted signal on the return wire.  That gives a higher SNR ratio but otherwise is indistinguishable on a balanced input and may get better results on an unbalanced input.
Answer: If the piano is mono, then the signals on the Tip and Ring will be the same.
If you connect either the Tip or Ring to one of the balanced lines, then the Sleeve to both the other balanced line and the ground, then it should work.
Turn the headphone output volume down to a moderate volume to ensure it's not above normal line levels.  The most appropriate approach would be to set the speaker to a moderate volume level, then adjust the volume at the headphone output.


Default language not working properly

Question: I have a site with 2 languages: English and Spanish and Path prefix: en and es respectively. Then Spanish language is set to default (see image 1)

And the Language negotiation is set to: Path prefix with language fallback  (see image 2)

Everything works as expected but there is one problem: when the site is loaded it takes the English as default language. Then if I change language (with the Language Switcher) everything works fine.
To be clear, it the url is:
www.mysite.com (landing page is loaded in english) I need this to be in spanish
www.mysite.com/en/home (landing page is loaded in english)
www.mysite.com/es/home (landing page is loaded in spanish)
I can't fix this..Any help please?
Comment: In case this is for Drupal 6 and happens only for anonymous users, it could be [this bug](https://www.drupal.org/node/339958). Some people report the same for D7 though.
Answer:
goto: Home » Administration » Configuration » Regional and language » Languages.
select the 'DETECTION AND SELECTION' tab.
Un-check all except 'URL' and 'default'. Keep 'URL' on top of 'default'
Answer: The description given in the settings page reports what exactly the option you selected means:

Path prefix with language fallback. The presentation language is determined by examining the path for a language code or other custom string that matches the path prefix (if any) specified for each language. If a suitable prefix is not identified, the display language is determined by the user's language preferences from the My Account page, or by the browser's language settings. If a presentation language cannot be determined, the default language is used.

You are accessing the page without any page prefix (the URL is just www.mysite.com); in that case, the language is set basing on what the logged in users have selected in their user profiles, or what the settings for their browsers are.
I would try setting the front page to www.mysite.com/es/home, but in that case, the front page would always be in Spanish. As alternative, one of the modules of the Internationalization project should correctly set the language for the front page.
Comment: I have the Internationalization module installed. How can I set the language for the front page?
Answer: You can try the Language Selection Page module. (The module is a sandbox project: use it at your own risk.)
Answer: If you want to stick to the "Path prefix with language fallback" mechanism, you cannot use the "Path prefix and default language" mechanism proposed by @user392795, which otherwise is great.
However, there are also solutions for this:
First case: You don't need Drupal's default feed on the front page
This is the simpler case, as we can exploit the shortcoming that Drupal will not do language negotiation when setting the "Default front page" field at /admin/config/system/site-information. So just set it to a URL of a node or view etc. that is in Spanish. This solution is also dealt with in this question.
Just make sure the "Default front page" does not say "This is a multilingual variable." below it, because that adds language dependent front pages which are not available in Drupal out of the box. If this is the case, you can get rid of it by following this process in reverse.
Second case: You also want to keep the Drupal default feed on the front page
In this case, Drupal's language selection mechanisms govern the front page, so you have to make sure that users arrive at the frontpage always with the path prefix for Spanish. Else, the language fallback mechanism would kick in and determine the language from the profile preference or browser language, as explained by @kiamlaluno already..
So, set up a URL forwarder that will do this redirect. For example with the Apache mod_alias mechanism in .htaccess:
Redirect 301 / /es/home

This one should also work, bit nicer:
Redirect 301 / /es

(If this does not work in your case, see some details.)

Default language not working properly


FInd the value of 'n' for $^nC_0-^nC_1+^nC_2+...+(-1)^r.^nC_r=28$

Question: If $^nC_0-^nC_1+^nC_2+...+(-1)^r.^nC_r=28$. Then find the value of $n$.
Comment: For these type of question where we have alternate positive or negative value , how do we calculate upto 'r' terms
Comment: [Vandermonde](https://en.wikipedia.org/wiki/Vandermonde%27s_identity) gives $$ \begin{align} \sum_{k=0}^r(-1)^k\binom{n}{k} &=(-1)^r\sum_{k=0}^r\binom{-1}{r-k}\binom{n}{k}\\ &=(-1)^r\binom{n-1}{r} \end{align} $$
Answer: The alternating truncated binomial sum has the following closed form
\begin{eqnarray*}
\sum_{i=0}^{r} (-1)^i \binom{n}{r}= (-)^r \binom{n-1}{r}.
\end{eqnarray*}
So we just need to find binomial coeffeicient where $\binom{n-1}{r}=28$ and $r$ is even.
By inspection $ \binom{8}{2} = \binom{8}{6} = 28$ is the only solutions. (You still need to check other values of $r$ to be certain of this).
So the possible solutions are $(n,r)= \color{red}{(9,2)} \text{ & } \color{red}{(9,6)}$.
Answer: Coefficient of $x^r$ in
$$(1-x)^n (1 + x + x^2 + ...) = (1-x)^{n-1}$$
So for $r \lt n$ it is $$(-1)^r\binom{n-1}{r}$$
Answer: One approach:
$r=1$: $1-n=28 \Rightarrow n=-27$ - not an acceptable answer.
$r=2$: $1-n+\frac{n(n-1)}{2}=28 \Rightarrow 2-2n+n^2-n=56$
This gives $n^2-3n-54=0$ which has one positive integer root.
But you presumably want an answer that is more general in terms of $r$?
Comment: Yes can I get this answer by some accurate method


CakePHP - Related models in a relationship table, displaying in a drop down?

Question: Given the following table structures:
Registered Participant model:
<?php
class RegisteredParticipant extends AppModel {
var $name = "RegisteredParticipant";
var $primaryKey = "id";
var $belongsTo = array(
  'EventLocation' => array('className' => 'EventLocation'),
  'RegistrationStatus' => array('className' => 'RegistrationStatus'),
  'Specialty' => array('className' => 'Specialty')
);
var $hasMany = array(
  'DietaryRestriction' => array('className' => 'DietaryRestriction')
);
}
?>

Event Location model:
<?php
class EventLocation extends AppModel {
   var $name = 'EventLocation';
   var $primaryKey = 'id';
   var $belongsTo = array(
      'Event' => array('className' => 'Event', 'foreignKey' => 'event_id'),
      'Location' => array('className' => 'Location', 'foreignKey' => 'location_id')
   );
}
?>

When I do this in my view:
     echo $form->input('RegisteredParticipant.EventLocation.moderator');
It returns a dropdown list of the EventLocation.ids, not the EventLocation.moderators like I expected. Any ideas what it could be?
Answer: nobody mentioned adding the $displayField to the model like this.
class EventLocation extends AppModel {
    var $name = 'EventLocation';
    var $displayField = 'moderators';
    var $primaryKey = 'id';
    var $belongsTo = array(
        'Event' => array('className' => 'Event', 'foreignKey' => 'event_id'),
        'Location' => array('className' => 'Location', 'foreignKey' => 'location_id')
    );
}

Answer: Duh. $this->RegisteredParticipant->EventLocation->find() wasn't using 'all' as it's param.
Answer: You can use find('list') for dropdowns. E.g:
$locations = $this->RegisteredParticipant->EventLocation->find('list', array(
    'fields' => array('some_fields')
));
$this->set('locations', $locations);

You will get back an array like:
array(
    'id_1' => 'some_field_contents',
    'id_2' => 'some_field_contents',
    'id_3' => 'some_field_contents'
);

Which can be handled on your view automatically by the Form helper.


How can bind StrokeDashArray property in MVVM pattern wpf

Question: I have WPF application where I have in one canvas some lines to be need to be dotted line, and some is need to be normal line. My question is what exactly type is StrokeDashArray . In msdn I see is use DoubleCollection but is from  System.Windows.Media.
How can make property for StrokeDashArray used good practice in MVVM pattern.
Answer: If you want to bind to the dash array then it's a DoubleCollection, so you do something like this:
<code>    private DoubleCollection _Dashes = new DoubleCollection { 1, 2 };
    public DoubleCollection Dashes
    {
        get { return this._Dashes;}
        set { this._Dashes = value; RaisePropertyChanged(); }
    }
</code>
And then in XAML:
<code>    <Line Stroke="Black" StrokeThickness="2" StrokeDashArray="{Binding Dashes}" X1="0" Y1="50" X2="100" Y2="50"/>
</code>
If you're creating a dynamic array of Canvas elements then you'll need to create an ItemsControl and set ItemsControl.Panel to be a Canvas. Then you'll usually use Item.Template to declare the line for each element along with a Style that chooses between your different line/dash types using Data Triggers.
Comment: Is good practice to use DoubleCollection, because is in namespace System.Windows.Media who is in assembly PresentationCore.dll
Comment: If you don't want to use DoubleCollection then it's easy enough to use a converter to create one from double[] or whatever else you want to use.


Computing $\int_0^\infty \frac{\sin(u)}{u}e^{-u^2 b} \, du$

Question: I want to compute
$\int_0^\infty u^{-1}(1-e^{\frac{-u^2 t}{2}})\sin(u(|x|-r))\,du$ and so ,as shown below, I want to compute
$$\int_0^\infty \frac{\sin(u)}{u}e^{-u^2 b} \, du$$
Attempt
We split the first integral into two:

$\displaystyle \int_0^\infty u^{-1} \sin(u(|x|-r))\, du=\frac{\pi}{ 2}$
$\displaystyle \int_0^\infty u^{-1} e^{\frac{-u^2 t}{2}}\sin(u(|x|-r))\,du = \int_0^\infty \frac{\sin(z)}{z} e^{-z^2 b} \, dz$

where $b=\dfrac{t}{2(|x|-r)^2}$ is a positive real constant.
any suggestions?
How to show that the value is $\frac{\pi}{2}erf(\frac{1}{2\sqrt{b}})$?
Given that I can swap integral and sum we have
$\sum_{-1}^{\infty}\frac{(-i)^{n}+(i)^{n}}{2(1+n)}\int_{0}^{\infty}x^{n}e^{-bx^{2}}dx=\sum_{-1}^{\infty}\frac{(-i)^{n}+(i)^{n}}{2(1+n)} \frac{\Gamma(\frac{n+1}{2})}{2b^{\frac{n+1}{2}}}.$
Answer: Are you wanting just an answer or the full solution.  Assuming $b$ is positive and Real, Mathematica says:
$$
\int_0^\infty \frac{\sin{u}}{u}e^{-u^2 b}du\quad= \quad\frac{1}{2}\pi \,Erf(\frac{1}{2\sqrt{b}})
$$
Where $Erf$ is the error function.
Comment: @TKM, there is a chapter in the book I mentioned above describing Feynman's Favorite Trick and it discusses (among others) an integral that looks very similar to your integral.  Instead of $sin(u)$ it is a $cos(tu)$ but the exponential is close enough that the solution method, or a variant of it might work.  Unfortunately, I don't have time to pursue it myself but you might consider this book as it is full of tricks for doing bizarre definite integrals.
Comment: I should get mathematica, wolfram wasn't computing it. But I wonder how can I find that? maybe by expanding sinx/x and using gaussian integral.
Comment: I used Mathematica at work but now that I am retired I bought the Home Edition.  I think the price is fair at $199 or something like that.  I bought a copy for both my Macbook Pro laptop and my iMac-24 desktop.
Comment: thanks, I actually meant the integral. sorry
Comment: @TKM actually I knew you meant the integral but thought I would give a pointer to the Home Edition anyway.  I am lazy these days so usually do integration via Mathematica when it is right here at my finger tips.  For the joy of doing it by hand, I am reading the book "Inside Interesting Integrals" by Paul J. Nahin.
Answer: Hint. Here is an approach.
Let $b$ be a real number such that $b>0$ and set
$$
f(b):=\int_0^\infty \frac{\sin{u}}{u}e^{-u^2 b}du. \tag1
$$ We are allowed to write that
$$
\begin{align}
f'(b) &=-\int_0^\infty u\sin{u}\: e^{-u^2 b}du \tag2 \\\\
&=\frac{1}{2b}\left[\sin{u}\:e^{-u^2 b}\right]_{0}^{\infty} -\frac{1}{2b}\int_0^\infty \cos{u}\: e^{-u^2 b}du\\\\
&=0-\frac{1}{4b}\Re \int_{-\infty}^\infty  e^{-u^2 b-iu}du\\\\
&=-\frac{e^{-\frac{1}{4b}}}{4b}\Re \int_{-\infty}^\infty  e^{-\left(\sqrt{b}\:u+\dfrac{i}{\sqrt{b}}\right)^2}du\\\\
&=-\frac{e^{-\frac{1}{4b}}}{4b} \int_{-\infty}^\infty  e^{-U^2}\frac{dU}{\sqrt{b}}\\\\
&=-\frac{e^{-\dfrac{1}{4b}}}{4b}\frac{\sqrt{\pi}}{\sqrt{b}} \tag3\\\\
\end{align}
$$ and, since from $(1)$ we have $\displaystyle \lim\limits_{b\to +\infty}f'(b)=0 $, then from $(3)$ we obtain
$$
\begin{align}
f(b) &=-\frac{\sqrt{\pi}}{4}\int_b^\infty \frac{e^{\large -\frac{1}{4\:t}}}{t\sqrt{t}}dt \tag4 \\\\
&=\sqrt{\pi}\int_0^{\large \frac{1}{2\sqrt{b}}} e^{-x^2}dx \qquad \left(x:=\frac{1}{2\sqrt{t}},\quad dx:=-\frac{1}{4\:t\sqrt{t}}dt\right)\\\\
&=\frac{\pi}{2}{\rm{erf}}\left(\frac{1}{2\sqrt{b}}\right)
\end{align}
$$ as desired.
Answer: Let $I(a)=\displaystyle\int_0^\infty\cos(au)~e^{-bu^2}~du$, and evaluate it using Euler's formula, completing the square, and the value of the Gaussian integral. Then express your integral in terms of $\displaystyle\int I(a)~da$ and let $a=1$. The final result will be a simple error function in b.
Answer: $\newcommand{\angles}[1]{\left\langle\, #1 \,\right\rangle}
 \newcommand{\braces}[1]{\left\lbrace\, #1 \,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\, #1 \,\right\rbrack}
 \newcommand{\ceil}[1]{\,\left\lceil\, #1 \,\right\rceil\,}
 \newcommand{\dd}{{\rm d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\dsc}[1]{\displaystyle{\color{red}{#1}}}
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}
 \newcommand{\fermi}{\,{\rm f}}
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}
 \newcommand{\half}{{1 \over 2}}
 \newcommand{\ic}{{\rm i}}
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}
 \newcommand{\Li}[1]{\,{\rm Li}_{#1}}
 \newcommand{\norm}[1]{\left\vert\left\vert\, #1\,\right\vert\right\vert}
 \newcommand{\pars}[1]{\left(\, #1 \,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\vphantom{\large A}\,#2\,}\,}
 \newcommand{\sech}{\,{\rm sech}}
 \newcommand{\sgn}{\,{\rm sgn}}
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}
 \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}$
\begin{align}&\color{#66f}{\large%
\int_{0}^{\infty}{\sin\pars{u} \over u}\,\expo{-u^{2}b}\,\dd u}
=\half\int_{-\infty}^{\infty}\expo{-u^{2}b}\,{\sin\pars{u} \over u}\,\dd u
=\half\int_{-\infty}^{\infty}\expo{-u^{2}b}\
\overbrace{\half\int_{-1}^{1}\expo{\ic k u}\,\dd k}
^{\ds{=\ \dsc{\sin\pars{u} \over u}}}\
\,\dd u
\\[5mm]&={1 \over 4}\int_{-1}^{1}
\int_{-\infty}^{\infty}\exp\pars{-b\bracks{u^{2} - {\ic k \over b}u}}
\,\dd u\,\dd k
\\[5mm]&={1 \over 4}\int_{-1}^{1}
\int_{-\infty}^{\infty}
\exp\pars{-b\braces{\bracks{u - \ic\,{k \over 2b}}^{2} + {k^{2} \over 4b^{2}}}}
\,\dd u\,\dd k
\\[5mm]&={1 \over 4}\int_{-1}^{1}\exp\pars{-\,{k^{2} \over 4b}}
\int_{-\infty - \ic k/\pars{2b}}^{\infty - \ic k/\pars{2b}}\exp\pars{-bu^{2}}
\,\dd u\,\dd k
\\[5mm]&=\half\,\pars{2\root{b}}\int_{0}^{1/\pars{\root{2}b}}\exp\pars{-k^{2}}
{1 \over \root{b}}\ \overbrace{\int_{-\infty}^{\infty}\exp\pars{-u^{2}}\,\dd u}
^{\dsc{\root{\pi}}}\ \,\dd k
\\[5mm]&=\dsc{\root{\pi}}{\root{\pi} \over 2}\bracks{{2 \over \root{\pi}}
\int_{0}^{1/\pars{\root{2}b}}\exp\pars{-k^{2}}\,\dd k}
=\color{#66f}{\large{\pi \over 2}\,\,{\rm erf}\pars{1 \over \root{2b}}}
\end{align}


How do I make it so catch stops looping and goes back to the beginning of the loop

Question: When running this code once it catches an exception it will keep repeating "The file was not found". How do I make it so it goes back to the beginning of the loop instead?
    private static List<Party> FindData(string exactpath)
    {
        bool validInput = false;
        while(validInput==false)
        {
            try
            {
                // Store values in a list of string
                List<string> file = File.ReadAllLines(exactpath).ToList();
                List<Party> parties = new List<Party>();
                foreach (string line in file.Skip(3))
                {
                    string[] items = line.Split(',');
                    Party p = new Party(items[0], Convert.ToInt32(items[1]), items.Skip(2).ToArray());
                    parties.Add(p);
                }
                return parties;
            }
            catch (FileNotFoundException)
            {
                Console.WriteLine($"The file was not found");

            }
        }
        return null;
    }

Example when not finding the file:
Comment: It should already be doing that; since `validInput` is never set to `true`, your `while` loop should never exit.
Comment: Try putting `return null;` in your `catch` block.
Comment: And as I see in your screenshot, that's *exactly* what it is doing.
Comment: It *is* going back to the beginning of the loop.  You aren't fixing the exception, so it just re-throws, forever and ever.
Comment: Do you mean the beginning of the _inner_ loop?
Comment: You need to do something to fix the exception in the `catch` block, this will then go back to the top of the loop and `try` it again, no pun intended
Answer: Break; should do the trick. Is it what you are looking for?
private static List<Party> FindData(string exactpath)
    {
        bool validInput = false;
        while(validInput==false)
        {
            try
            {
                // Store values in a list of string
                List<string> file = File.ReadAllLines(exactpath).ToList();
                List<Party> parties = new List<Party>();
                foreach (string line in file.Skip(3))
                {
                    string[] items = line.Split(',');
                    Party p = new Party(items[0], Convert.ToInt32(items[1]), items.Skip(2).ToArray());
                    parties.Add(p);
                }
                return parties;
            }
            catch (FileNotFoundException)
            {
                Console.WriteLine($"The file was not found");
                break;
            }
        }
        return null;
    }

Comment: Although, what's the whole point of `validInput` then?