How to fix QPropertyAnimation "starting an animation without end value" error

Question: I'm trying to port qt example from c++ to pyqt/pyside2. This example shows hide/show action with a textedit field using QPropertyAnimation.
It doesn't seem to be complicated, but I still can't figure out why it is not working properly
The main idea is: textEdit widget "collapses" by pressing ">" button and returns back on pressing the button again.
Here's my python code:
import PySide2
from PySide2.QtWidgets import *
from PySide2.QtCore import *
from PySide2.QtGui import *
import sys

class myWidget(QWidget):
    def __init__(self):
        super(myWidget, self).__init__()

        self.m_deltaX = 0
        self.m_isClosed = False

        self.btn = QPushButton(self)
        self.btn.setText(">")
        self.btn.setCheckable(True)
        self.btn.setFixedSize(QSize(25, 25))
        self.btn.connect(SIGNAL("clicked()"), self.closeOpenEditor)

        self.text1 = QTextEdit(self)
        self.text1.setText("some sample text")

        self.text2 = QTextEdit(self)

        self.layout_btn = QVBoxLayout()
        self.layout_btn.addWidget(self.btn)

        self.layout_m = QHBoxLayout()
        self.layout_m.addWidget(self.text1, 10)
        self.layout_m.addSpacing(15)
        self.layout_m.addLayout(self.layout_btn)
        self.layout_m.setSpacing(0)
        self.layout_m.addWidget(self.text2, 4)

        self.setLayout(self.layout_m)
        self.resize(800, 500)

    def closeOpenEditor(self):
        self.m_isClosed = self.btn.isChecked()

        animation1 = QPropertyAnimation(self.text2, b"geometry")

        if self.m_isClosed:
            self.text2.setMaximumWidth(self.text2.width())
            text2Start = int(self.text2.maximumWidth())

            self.m_deltaX = text2Start
            text2End = int(3)

            animation1.setDuration(250)
            animation1.setStartValue(text2Start)
            animation1.setEndValue(text2End)

            self.btn.setText("<")
        else:
            text2Start = int(self.text2.maximumWidth())
            text2End = int(self.m_deltaX)

            animation1.setDuration(250)
            animation1.setStartValue(text2Start)
            animation1.setEndValue(text2End)

            self.btn.setText(">")

        animation1.start()

    def resizeEvent(self, event:QResizeEvent):
        if not self.m_isClosed:
            self.text2.setMaximumWidth(QWIDGETSIZE_MAX)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = myWidget()
    w.show()
    sys.exit(app.exec_())

I will also add c++ code:
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QTextEdit>
#include <QPushButton>
#include <QHBoxLayout>

class MyWidget : public QWidget
{

    Q_OBJECT

    QTextEdit       *m_textEditor1;
    QTextEdit       *m_textEditor2;
    QPushButton     *m_pushButton;
    QHBoxLayout     *m_layout;
    QVBoxLayout     *m_buttonLayout;

    int              m_deltaX;
    bool             m_isClosed;

public:

    MyWidget(QWidget * parent = 0);
    ~MyWidget(){}

    void resizeEvent( QResizeEvent * event );

private slots:
    void closeOrOpenTextEdit2(bool isClosing);

};

#endif // MAINWINDOW_H

main.cpp
#include <mainwindow.h>
#include <QPropertyAnimation>
#include <QApplication>
#include <QIcon>

MyWidget::MyWidget(QWidget * parent):QWidget(parent),m_deltaX(0)
{

  m_pushButton = new QPushButton(this);
  m_pushButton->setText(">");
  m_pushButton->setCheckable(true);
  m_pushButton->setFixedSize(25,25);
  //m_pushButton->setStyleSheet("background-color: yellow;");
  connect(m_pushButton, SIGNAL(clicked(bool)), this, SLOT(closeOrOpenTextEdit2(bool)));

  m_textEditor1 = new QTextEdit(this);
  m_textEditor1->setText("И рвется в пляс душа моя, головой я выбиваю дверцы...");

  m_textEditor2 = new QTextEdit(this);

  m_buttonLayout = new QVBoxLayout();
  m_buttonLayout->addWidget(m_pushButton);
  m_buttonLayout->addItem( new QSpacerItem(1, 1, QSizePolicy::Minimum, QSizePolicy::Expanding) );

  m_layout = new QHBoxLayout;
  m_layout->addWidget(m_textEditor1, 10);
  m_layout->addSpacing(15);
  m_layout->addLayout(m_buttonLayout);
  m_layout->setSpacing(0);
  m_layout->addWidget(m_textEditor2, 4);

  setLayout(m_layout);
  resize(800,500);
}

void MyWidget::closeOrOpenTextEdit2(bool isClosing)
{
    m_isClosed = isClosing;
    QPropertyAnimation *animation1 = new QPropertyAnimation(m_textEditor2, "maximumWidth");

    if(isClosing) //close the second textEdit
    {
        m_textEditor2->setMaximumWidth(m_textEditor2->width());

        int textEdit2_start = m_textEditor2->maximumWidth();

        m_deltaX = textEdit2_start;
        int textEdit2_end = 3;

        animation1->setDuration(250);
        animation1->setStartValue(textEdit2_start);
        animation1->setEndValue(textEdit2_end);

        m_pushButton->setText("<");

    }
    else //open
    {

        int textEdit2_start = m_textEditor2->maximumWidth();
        int textEdit2_end = m_deltaX;

        animation1->setDuration(250);
        animation1->setStartValue(textEdit2_start);
        animation1->setEndValue(textEdit2_end);

        m_pushButton->setText(">");
        //m_pushButton->setIcon()

    }

    animation1->start();

}

void MyWidget::resizeEvent( QResizeEvent * event )
{
    if(!m_isClosed)
        m_textEditor2->setMaximumWidth( QWIDGETSIZE_MAX );
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MyWidget w;
    w.show();

    return a.exec();
}

In my rewritten code it doesn't want to start an animation. You ought to press the button twice and after that it will collapse the widget permanently without any animation. So you can't open it again.
Also i recieved some errors:

QPropertyAnimation::updateState (geometry, QTextEdit, ): starting an animation without end value

and

NameError: name 'QWIDGETSIZE_MAX' is not defined
Answer: Your code has the following errors:

The property that is modified in the C++ code is maximumWidth but in your python code you use geometry, in the case of maximumWidth an integer is expected but geometry expects a QRect so you get the error message since the endValue is of an incorrect type so it is not established by noting that it did not establish a value.
In Python a local variable is deleted when its scope ends, except in the case of PyQt if the local variable is a QObject that has as a parent another QObject with a larger scope. In the case of C++ in addition to using the parent to extend the life cycle is to use pointers.
QWIDGETSIZE_MAX is not defined in PySide2 (but it is defined in PyQt5: QtWidgets.QWIDGETSIZE_MAX) so you must define a variable that takes the value it takes in C++.

from PySide2 import QtCore, QtWidgets

# https://code.qt.io/cgit/qt/qtbase.git/tree/src/widgets/kernel/qwidget.h#n873
QWIDGETSIZE_MAX = (1 << 24) - 1

class MyWidget(QtWidgets.QWidget):
    def __init__(self):
        super(MyWidget, self).__init__()
        self.m_deltaX = 0
        self.btn = QtWidgets.QPushButton(
            ">", checkable=True, clicked=self.closeOpenEditor
        )
        self.btn.setFixedSize(QtCore.QSize(25, 25))

        self.text1 = QtWidgets.QTextEdit()
        self.text1.setText("some sample text")

        self.text2 = QtWidgets.QTextEdit()

        layout_btn = QtWidgets.QVBoxLayout()
        layout_btn.addWidget(self.btn)

        lay = QtWidgets.QHBoxLayout(self)
        lay.addWidget(self.text1, 10)
        lay.addSpacing(15)
        lay.addLayout(layout_btn)
        lay.setSpacing(0)
        lay.addWidget(self.text2, 4)

        self.resize(800, 500)

        self.m_animation = QtCore.QPropertyAnimation(
            self.text2, b"maximumWidth", parent=self, duration=250
        )

    def closeOpenEditor(self):
        if self.btn.isChecked():
            self.text2.setMaximumWidth(self.text2.width())
            text2Start = int(self.text2.maximumWidth())
            self.m_deltaX = text2Start
            text2End = 3
            self.m_animation.setStartValue(text2Start)
            self.m_animation.setEndValue(text2End)
            self.btn.setText("<")
        else:
            text2Start = int(self.text2.maximumWidth())
            text2End = self.m_deltaX
            self.m_animation.setStartValue(text2Start)
            self.m_animation.setEndValue(text2End)
            self.btn.setText(">")

        self.m_animation.start()

    def resizeEvent(self, event: "QResizeEvent"):
        if not self.btn.isChecked():
            self.text2.setMaximumWidth(QWIDGETSIZE_MAX)

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = MyWidget()
    w.show()
    sys.exit(app.exec_())


How to order and make space between items in flexbox?

Question: Inside a container, we have 3 boxes (A, B, C). Currently, they all are in floating left positions. But we need them in a position where Box A will be the left, B will be the middle, and C will be the right side of the container. See the image below. How can we achieve this layout? (Please submit your answer with complete CSS. Use .container class name for container and .A .B .C for the boxes)
enter image description here
I fixed this by
.container {
  display: flex;
  justify-content: space-between;
}

.A {
  order: 1; /* Box A is on the left */
}

.B {
  order: 2; /* Box B is in the middle */
}

.C {
  order: 3; /* Box C is on the right */
}

Now I can not solve this.
On mobile layout, we need to swap the positions of these 3 boxes. We need Box C on the left side of the container and the Box A and Box B on the right side of the container. See the image above. How can we achieve this layout?
enter image description here
I have tried this code
@media (max-width: 767px) {
    .A, .B, .C {
        order: 0; /* Reset the order for all boxes */
    }

    .C {
        order: 1; /* Box C left */
    }

    .A, .B {
        order: 2; /* Box A right */
    }

    .B {
        order: 3; /* Box B right */
    }
}

But I am getting this
enter image description here
I am expecting this
enter image description here
My code here

.box {
  width: 100px;
  height: 100px;
  background-color: red;
  color: white;
  font-size: 24px;
  margin: 4px;
}

.container {
    display: flex;
    justify-content: space-between;
}

.A {
    order: 1; /* Box A right */
}

.B {
    order: 2; /* Box B right */
}

.C {
    order: 3; /* Box C left */
}

@media (max-width: 767px) {
    .A, .B, .C {
        order: 0; /* Reset the order for all boxes */
    }

    .C {
        order: 1; /* Box C left */
    }

    .A, .B {
        order: 2; /* Box A right */
    }

    .B {
        order: 3; /* Box B right */
    }
}

    A

    B

    C

Comment: You can use the `gap` css property. For example `gap: 2rem` inside your `.container` selector.
Comment: But still there is one item in the middle. That's not what I want to do.
Comment: Hmm can you include your HTML code as I'm not sure I'm correctly understanding the issue
Comment: Edited my question is it ok now?
Comment: Yes, but A and B should be on the right side and C on the left. On my code A comes in the middle. I don't want any box in the middle. Hope you understands.
Comment: Ohh, so you want A and B to be further away from C and not equally spaced?
Comment: Yes, but HTML code should not be changed.
Comment: Is the extra spacing some particular value? Or does C just have to look further away?
Comment: I added a reference image on my question. Can you please check? And this the challenge that I mentioned in my question "On mobile layout, we need to swap the positions of these 3 boxes. We need Box C on the left side of the container and the Box A and Box B on the right side of the container. See the image above. How can we achieve this layout?"
Comment: Yes, i have checked the image but the nature of the dynamic layout has not been clarified. Check my answer to see if it solves your problem.
Answer: If you cannot change the HTML at all, I would add a margin-right to .C inside of the CSS media query. That way the other two boxes are pushed right:

.box {
  width: 100px;
  height: 100px;
  background-color: red;
  color: white;
  font-size: 24px;
  margin: 4px;
}

.container {
    display: flex;
    gap: .25rem;
    justify-content: space-between;
}

.A {
    order: 1; /* Box A right */
}

.B {
    order: 2; /* Box B right */
}

.C {
    order: 3; /* Box C left */
}

@media (max-width: 767px) {
    .A, .B, .C {
        order: 0; /* Reset the order for all boxes */
    }

    .C {
        order: 1; /* Box C left */
        margin-right: auto;
    }

    .A, .B {
        order: 2; /* Box A right */
    }

    .B {
        order: 3; /* Box B right */
    }
}

    A

    B

    C

You can play with the margin-right value (here it is auto, you can set it to eg 30%) and find the optimal spacing. But auto should do the best job;
However if you can change the HTML just a little bit, you could place the boxes inside of their own wrappers, and change the width of the wrapper of C to make it push the other boxes away. Making it take up 50% of the width would make the other two boxes be pushed to the other half of the screen:

.box {
  width: 100px;
  height: 100px;
  background-color: red;
  color: white;
  font-size: 24px;
  margin: 4px;
}

.wrapper {
  outline: 2px solid hotpink;
}

.container {
    display: flex;
    justify-content: space-between;
}

.A {
    order: 1; /* Box A right */
}

.B {
    order: 2; /* Box B right */
}

.C {
    order: 3; /* Box C left */
}

@media (max-width: 767px) {
    .wrapper.a, .wrapper.b, .wrapper.c {
        order: 0; /* Reset the order for all boxes */
    }

  .wrapper.c {
      width: calc(50% - 4px);
    }

    .wrapper.c {
        order: 1; /* Box C left */
    }

    .wrapper.a, .wrapper.b {
        order: 2; /* Box A right */
    }

    .wrapper.b {
        order: 3; /* Box B right */
    }
}

      A

      B

      C

You can remove the outline of .wrapper as it is for testing purposes.
Comment: I think that the one. Thank a lot man.
Comment: We can't predict 30% work in all resolutions with content. See my code for future purpose.
Comment: Yes you are right. I used .C {
        order: 1; /* Box C left */
        margin-right: auto;
    }
Answer:

.box {
  width: 100px;
  height: 100px;
  background-color: red;
  color: white;
  font-size: 24px;
  margin: 4px;
}

.container {
    display: flex;
    justify-content: space-between;
}

.A {
    order: 1; /* Box A right */
}

.B {
    order: 2; /* Box B right */
}

.C {
    order: 3; /* Box C left */
}

@media (max-width: 767px) {
    .container{
      gap: 25px;
    }

    .A, .B, .C {
        order: 0; /* Reset the order for all boxes */
    }

    .C {
        order: 1; /* Box C left */
    }

    .A, .B {
        order: 2; /* Box A right */
    }

    .B {
        order: 3; /* Box B right */
    }

    .A {
         margin-left: auto;
    }
}

    A

    B

    C


if $a+ b = 9 $and $ab = 1$. what will be the $a^3 + b^3 =$?

Question: How can I solve this? Or, is it given properly?
If $a + b = 9$ and $ab = 1$. What is $a^3 + b^3 = $?
Comment: @TonyK thank you :) thats more easier. Yet I'm growing.
Answer: You can start with the fact that $$a^3+b^3=(a+b)(a^2-ab+b^2) $$
$$(a+b)^2 = a^2+2ab+b^2$$
And see if you can use some substitutions, additions and subtractions.
Comment: The LHS of your first equation should be $a^3 + b^3$
Comment: whoops. thanks.
Answer: Hint: $a^3 + b^3 = (a+b)((a+b)^2 - 3ab)$
Comment: That's somewhat more than a hint....
Answer: Hint: Express  $a^3+b^3$ as function of $ab$ and $a+b$.
Answer: $a + b = 9 => a = 9 - b$ and then you solve $b$: $ab = 1 => (9 - b)b = 1$; solving $a$ is easy now. (then $a^3 + b^3 = ...$ is easier)
Comment: @Rufat, why did you choose the least helpful answer to accept?
Comment: @TonyK Just I understand them, the second one was more easier than the first one. Thank you!
Answer: $$a^2+b^2=(a+b)^2-2ab$$ $$a^3+b^3=(a+b)^3-3ab(a+b)$$ $$a^4+b^4=(a+b)^4-4ab(a+b)^2+2a^2b^2$$ $$a^5+b^5=(a+b)^5-5ab(a+b)^3+5a^2b^2(a+b)$$


I want to get the real password(not md5 encryption) when edit the account profile via user profile form and save. how to do that?

Question:
Possible Duplicate:
How can I get the real password via hook_user_update()?

I want to change the current user password, and get the new password(the real password, not md5 encryption) when edit the account profile via user profile form(e.g.: example.com/user/1/edit) and save. would anyone can tell me how to do that? I tried using hook_user_update(), but it didn't succeed.
Comment: I mean I want to change the current user password, and I want to get the new password.
Comment: sorry, I dont know, how to delete this question?
Answer: You cannot decrypt the password due to security reasons. Drupal 7 uses SHA512 by default with a salt. It will perform multiple hashes on the password. It's highly impossible to decrypt password.
See the better explanation provided here.
To reset the password see the solution provided here.
Comment: You can form alter the widget form and get the value using $form_state['values'], call the additional submit function to sync to another system . But, it's a not recommended to read user passwords, ideal way is to encrypt passwords and store them in another system too !
Comment: you need to write a custom module, and define the function MYMODULE_form_user_register_form_alter(), where MYMODULE is the name of your module.  It actually implements hook_form_FORM_ID_alter, (the form_id for the form can be found in a hidden field, in this case it's user_register_form) as found here: http://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_form_FORM_ID_alter/7.
Comment: I just want to receive the new password via form widget (drupal 7 this widget's id is :edit-pass-pass1), and use this password to single sign on with other system.  In order to make data synchronization,when password has changed, another system will changed at the same time.
Comment: Do you mean to use hook_form_alter()?
Comment: Yes, Use hook_form_alter, but i strongly recommend encrypting passwords in another system too.. !
Comment: thanks Anil Sager, would you tell me how to use hook_form_alter? this page is call user_profile_form.


How to get the coordinates of a vertex of a tetrahedron with only the lenghts of the edges?

Question: I need the coordinates of E and have the coordinates of A, B, C and the distance to them from E.
It should be possible, in 2D I got it like  with a rotation matrix.
But in 3D the angles of the edges are not parallel to axis so I cant really use the same principle can I ?
Comment: One way is to write out the three distance equations in $x,y,z$ (the coordinates of $E$) and then solve for each coordinate.
Comment: Can you please elaborate on that? Which distance equations ?
Comment: The distance between two points in space is $$\sqrt{ (x_1 -x_2)^2 + (y_1 -y_2)^2 + (z_1 - z_2)^2 }$$
Comment: i see :) but isnt that a non linear equation system then ?
Comment: Exactly, which means there may be multiple points which are candidates for $E$, so there's not enough information to determine one fixed point.
Comment: Essentially, you're computing the [intersection of three spheres](https://math.stackexchange.com/q/786489/265466).
Comment: what if I say that E is always above the plain of ABC ? would that help ?
Comment: Not necessarily. You may want to refer to amd's comment.
Answer: Thanks to @amd and @Tavish !
The problem is often not to find a solution but to ask the right question.
Indeed I was really just searching for the intersection of 3 spheres and wikipedia had the answer. https://en.wikipedia.org/wiki/True_range_multilateration#Three_Cartesian_dimensions,_three_measured_slant_ranges
Here is a simple implementation in python:
<code>def calculate_position(distances):

# Find the intersections of the three spheres created with three radii
# Implementation based on https://en.wikipedia.org/wiki/True_range_multilateration

A = (0, 0, 0)
B = (10, 0, 0)
C = (5, 10, 0)
V_SQ = C[0] ** 2 + C[1] ** 2
r1, r2, r3 = distances

x = (r1 ** 2 - r2 ** 2 + B[0] ** 2) / (2 * B[0])
y = (r1 ** 2 - r3 ** 2 + V_SQ - 2 * C[0] * x) / (2 * C[1])
z1 = sqrt(r1 ** 2 - x ** 2 - y ** 2)
if z1 >= 0:
    return x, y, z1
return x, y, -z1
</code>


Suppose that $f − \frac{1}{2}m||x||^2$ is convex where $f$ is differentiable.

Question: Suppose that $f − \frac{1}{2}m||x||^2$ is convex where $f$ is differentiable.

Show that:

$f(αx + (1-α)y) ≤ αf(x) + (1-α)f(y) - \frac{α(1−α)m}{2}||x−y||^2$,
$α∈(0,1)$
To start, I tried to apply the definition of convexity to the given function but I am not sure how to do that?

Show the following without assuming the existence of the Hessian:

$f(y) ≥ f(x) + ∇f(x) · (y − x) + \frac{m}{2} ||y - x||^2$
What does it mean when the question states without assuming the existence of Hessian. Does it mean I cannot add $∇^2f$ into the inequality?

Then, prove that $f$ has a global minimzer.

$[∇f(x) - ∇f(y)] · (x - y) ≥ m||x - y||^2$
I tried using the proof of contradiction where I suppose $f$ does not have a global minimizer, but I am not sure.
Answer: Assume $m>0$. Some hints:
For 1: Let $g(x) = f(x) - \frac12 m \vert x \vert^2$. Since $g$ is convex, for all $\alpha \in [0,1]$, we have that $$g(\alpha x + (1-\alpha) y)\leqslant \alpha g(x) +(1-\alpha ) g(y). $$ Expand out the definition of $g$ - group the terms coming from $f$ together and the terms coming from the $-\frac12 m \vert x \vert^2$ together. Using that $\vert x-y\vert^2=\vert x \vert^2-2 x \cdot y + \vert y \vert^2$ the terms coming from $-\frac12 m \vert x \vert^2$ simplify to give you the required identity.
For 2: Given that $f$ is differentiable, recall that for any $v\in \mathbb R^n \setminus \{ 0\}$, $$ \nabla f(x) \cdot v = \lim_{h \to 0} \frac{f(x+hv)-f(x)}h . $$ If $x=y$ then your identity is trivial, so assume $y\neq x$ and take $v=y-x$. Then $$ f(x+hv)=f((1-h)x+h y) ,$$ so apply Part 1 with $\alpha = 1-h$.
For 3: First, assuming that there is a global minimiser, can you prove uniqueness? Let $x,y\in \mathbb R^n$ be global minimisers. From Part 2, $$ 0 \leqslant \frac12 m \vert x-y\vert^2 \leqslant f(y)-f(x)-\nabla f(x) \cdot (y-x). $$ What is the value of $\nabla f(x)$? Can you bound $f(y)-f(x)$ from above? Remember $y$ is a global minimiser of $f$.


show a subset of $\mathbb R^n$ is compact if it is closed and bounded

Question: Use the two lemmas to prove that a subset of $\mathbb R^n$ is compact if it is closed and bounded.
Lemma 1: A closed subset of a compact space is compact
Lemma 2: If $X$ and $Y$ are compact then $X\times Y$ is compact.
I had an idea, but that was quickly shown to be wrong by the answers in this thread
https://math.stackexchange.com/questions/1026318/a-closed-and-bounded-subset-of-rn/1026334#1026334
Thanks
Answer: Your idea from the previous thread was almost correct.
HINT: Show that if $A\subseteq\Bbb R^n$ is closed and bounded, then it is a subset of some product of closed intervals (in fact, you can use the same interval!).
Comment: Sorry can you be a bit clearer on 'you can use the same interval'? Thanks
Comment: Well, your set *is* bounded, isn't it?
Comment: I'm confused now. Can you explain a bit more in symbols
Comment: please help just a bit more.
Comment: Ignore that comment about the same interval if it confuses you.


Angle plane makes with semi-meridian on sphere

Question: (doCarmo, Exercise 2, Sec. 2-5) Let $ \textbf{x}(\phi,\theta) = (\sin \theta \cos \phi, \sin \theta \sin \phi, \cos \theta)$ be a parametrisation of the unit sphere $S^2$. Let P be the plane $x=z\cot \alpha$, $0 < \alpha < \pi$, and $\beta$ be the acute angle which the curve $P \cap S^2$ makes with the semimeridian $\phi = \phi_0$. Compute $\cos \beta$.
I assumed the basis $\{{\textbf{x}_{\theta},\textbf{x}_{\phi}}\}$ and computed the components of the two curves in terms of these and used the standard formula for the inner product to get $$\cos \beta = \frac{1}{\sqrt{1+\cot^2 \alpha + \cos^2 \phi_0}}.$$ Would just like to confirm the answer with someone else - thanks in advance.
Answer: HINT:
Trying to check your result in alternate trig form
$$ \tan ^2 \beta = 1/ \tan ^2 \alpha + \cos ^2 \phi_0 ^2 $$
At equator meridian should cut great circle at complementary angles.
At max polar angle it should cut at angle  $\beta = \pi/2. $
Best way is to check by using Claraut's Law, not so sure/comfortable about notation..
$$  \sin \theta \sin \beta = ..\cos (\alpha).. $$
EDIT1:
I derived to obtain a result which in your nomenclature is:
$$ \tan \beta = \frac{ \cot \alpha \sin \theta - \cos \theta \sin \phi }{ \cos \phi} $$
It should be checked and perhaps be further simplified, using your given conditions by division
$$ \cot \alpha = \tan \theta \cos \phi $$
Comment: Right, I think you need to check it out. A rough sketch even by hand is helpful in marking out all the 4 angles showing meridian cutting in between extreme positions of the great circle.
Comment: Thanks a lot for this. I'm fairly new to this stuff so I had to graph this out to visualise. Allow me to make a rough translation of your assessment and perhaps you could tell me if this reflects accurately: Look at the case where the plane is cutting at an angle of $\frac{\pi}{2}$ (corresponding to $\alpha=\frac{\pi}{2}$), then $\beta$ should be $\frac{\pi}{2}$ but this violates the formula I gave. Is this correct?


While loop not working properly in C

Question: The loop in this program unexpectedly fails to terminate. When I test with inputs t=4 and s="qi", the value of t that gets printed when the program runs is 0 rather than the expected value 4. What's going wrong?
#include<stdio.h>

int main()
{
    int t,flag=0;
    char s[2];
    scanf("%d ",&t);
    while(t)
    {
        scanf("%s",s);
        if(s[1]=='i')
        {
            if(flag==0)
                flag=1;
            else
                flag=0;
        }
        else if(s[1]=='b')
        {

        }
        else if(s[1]=='r')
        {

        }
        printf("%d\n",t);
        t=t-1;
    }
}

Comment: @user1336087: it is not necessary to have else
Comment: @OliverCharlesworth Agreed, already deleted it. As I said, rusty :)
Answer: Array s has the size of 2. This means it can hold only one character. You input two characters, "qi", and the null terminator is written in adjacent memory, overwriting whatever is there.
This will cause undefined behaviour. You got unlucky and apparently overwritten the first byte of variable t, which will set it to 0( in your case ) on a little endian machine.
The solution is to enlarge the string to at least 3 elements, and restrict the input in scanf() to a maximum of two characters.
Answer: The problem is that you are overwritting memory beyond array char s[2]; When you enter "qi" with scanf then there is stored three characters that is the terminating zero is appended to characters "qi". This terminating zero overwrites memory occupied by t. Enlarge array s at least as
char s[3].

Also it would be better to use a for loop then the while loop in this case
for ( ; t; --t )

because it is difficult to see that t is changed at the end of the while loop.
Answer: Since your character array is of size 2 and your input string "qi" will need 3 characters including a null, which causes overflow. Due to this your program terminates abruptly.
Answer: One obvious syntactical error I noticed was:
printf("%d\n");

should be
printf("%d\n",t);

Since I Suppose you Wish to print the value of t at every iteration.

While loop not working properly in C


The socle of an almost simple group

Question: By definition an almost simple group is a group $G$ with
$$T \cong \mathrm{Inn}(T)\trianglelefteq G \leq \mathrm{Aut}(T),$$
where $T$ is a non-abelian simple group. How would one show that in this case the socle of $G$ is equal to $\mathrm{Inn}(T)$?
I have seen one argument in a book which says that from the above we get $C_{G}(\mathrm{Inn}(T))=1$ (the centraliser in $G$ of $\mathrm{Inn}(T)$) and thus $\mathrm{Inn}(T)$ is the unique minimal normal subgroup of $G$ from which the result follows. The only part of this argument I fail to understand is how we obtain $C_{G}(\mathrm{Inn}(T))=1$ from the definition.
Comment: What is a "socle"?
Comment: @MarkFischler The socle of $G$ is the subgroup of $G$ generated by all its minimal normal subgroups.
Answer: Suppose $g\in C_G(\mathrm{Inn}(T))$. Then $g^{-1}\varphi_tg = \varphi_t$ for any $t\in T$. For any $x\in T$, we have
\begin{equation*}
t^{-1}xt = x^{\varphi_t} = x^{g^{-1}}\varphi_tg = (t^{-1}(x^{g^{-1}})t)^g = (t^g)^{-1}xt^g
\end{equation*}
and so $x = t(t^g)^{-1}xt^gt^{-1}$, which implies $t(t^g)^{-1}\in Z(T) = \{1\}$. Therefore, $t = t^g$ for any $t\in T$. So $g$ is trivial in $\mathrm{Aut}(T)$ and in $G$.

The socle of an almost simple group


Access Thread.CurrentPrincipal when binding with NInject in Owin context

Question: I need to access my claims when binding my services, but appears that Ninject bind occurs before HttpMessageHandlerAdapter sets the Thread.CurrentPrincipal so I cannot access my claims when I'm binding my services. I tried this
kernel.Bind<IMyService>().ToMethod(x => GetMyService());

private static IMyService GetMyService()
{
    var principal = Thread.CurrentPrincipal;
    var userId = [GetUserIdFromPrincipalClaims]
    return new MyService(userId);
}

But the claims list is empty, if I access Thread.CurrentPrincipal claims list from any action I can get an userId. How can I access my claims list  when binding?
Answer: Since identity claims are a run-time value, I would say it can't be done (easily). However, one approach involving the decorator pattern and an abstract factory might look like this:
class MyServiceDecoraptor : IMyService
{
    private readonly IMyServiceFactory _myServiceFactory;
    public MyServiceDecoraptor(IMyServiceFactory myServiceFactory)
    {
        _myServiceFactory = myserviceFactory
    }

    public void MyServiceMethod()
    {
        var principal = Thread.CurrentPrincipal;
        var userid = GetUserId(principal);
        _myServiceFactory.Create(userid).MyServiceMethod();
    }
    //more code here
   }


Upgrading .Net 2.0 to .Net 3.5

Question: Will this require a reboot? Even if I include all the security patches as well.
NB This will not be to .Net 3.5 SP1.
Answer: It's not an upgrade, per se.  Different versions of the .NET framework are a side-by-side install.  Usually it does require a reboot because the 3.5 installer will service pack 2.0 and it's not unusual for something to have 2.0 framework files locked.
Answer: It's not an upgrade, they are two different products that can coexist. And yes, it will require a reboot.

Upgrading .Net 2.0 to .Net 3.5


How to play this rhythm precisely?

Question:
Could someone please teach me how to play this rhythm?
The Medium Swing, two eighth notes equal to quarter note and eighth note triplet.
Comment: why not just listen to it?
Answer: Instead of playing the eighth notes 'straight' you make them swing by making the note on the beat a bit longer and the next note a bit shorter.  This is called tripletizing.  As your first notes are off the beat (the C# and G#), those notes would be the shorter or slightly delayed ones.  The D and A being on the beat, would be the elongated notes (equalling a triplet quarter note length).  Sounds more complicated than it needs to.  I believe that's the opening of The Pink Panther.  Take a listen to it and you will straight away understand about giving it some swing.
Comment: Here's a link to it for listening: [The Pink Panther Theme](https://www.youtube.com/watch?v=9OPc7MRm4Y8) (Youtube).
Answer: If it helps to count, imagine each crotchet divided into three. In a whole bar, there would be a count of twelve (4x3), emphasising 123 456 789 10 11 12. The notes in question come on 9, 10 and 12, with 10 being cut short and bounced off.
Sometimes, it's helpful to say a phrase that's in the same timing. Here, count '1, 2, 3and that shallot' or '1, 2, 3and that's yer lot' with 'lot' landing on the top line B. Those phrases will, if they fit nicely, stay with you a long time - I sometimes write one out on the music if it's a tricky one I don't play often.
Certainly sounds like Mancini, as noted by Jomiddnz.
Answer: Think of each beat divided into triplets, for a total of 12 'sub-beats'. The three notes are played at 9, 10, and 12.
<code>1        2        3        4        | 1        2

1  2  3  4  5  6  7  8  9  10 11 12 | 1  2  3  4  5  6 . . . .

-  -  -  -  -  -  -  -  X  X  -  X  | X––––––––––––––– . . . .
</code>

How to play this rhythm precisely?


Cytoscape : multiple instances and no graph display

Question: I want to display several instances of cytoscape in a single page, in a time sequence: first one set of nodes are displayed on the graph, the user must interact with it (create edges), then he moves to a second graph (#cy0 is :hidden and #cy1 is :visible).
For code optimisation sake I wish to use the same initialisation function to display different successive sets of nodes. My initialisation function works fine in the first instance, but the graph is not created (cy.initrender() == false) in the second session. A command is probably missing, I tested a couple, but I don't see what to do.
Here is my code:
//elements
$(function(){ // on dom ready
var elesJson = {
nodes: [
  { data: { id: 'S', faveShape: 'rectangle',} }
   ...
  ],

edges: [
    { data: { id: 'loan', source: 'B', target: 'U' } },
    ...
        ],

};
// instance index
    var indexLevel=0;
// cy initialisation
$("#cy"+indexLevel).cytoscape({

style: cytoscape.stylesheet()...

elements: elesJson,
ready: function(){
    window.cy = this;});

// jQuery command to move from one instance to the other.
$('#next').click(function(){
$("#cy"+indexLevel).css("visibility","hidden");
indexLevel++;
$("#cy"+indexLevel).css("visibility","visible");
cy.load(elesJson);
cy.ready();
console.log(cy.initrender());
});

I am able to generate my node.collection, it is not empty, but the canvas element is not created and/or displayed within the #cy div, and cy.initrender() returns "false".
Any solution to this?
Comment: Well, I've found the answer: load the successive graphs in a single #cy div...
Answer: As noted in the docs for init, you must call cy.resize() if you play around with the cy div's display or position: http://js.cytoscape.org/#core/initialisation
cy.resize() : http://js.cytoscape.org/#core/viewport-manipulation/cy.resize
Edit: You may want to use z-index instead to simplify things...


Tools for testing the validity of stocks market indicators

Question: I need references on tools for testing the validity of technical analysis indicators on stocks market.
The tools I want could be anything, the technical analysis indicators are a list of values built from some stocks market parameters, such as price and volume - from these newly built indicators, there are some rules "if n happens, sell it, if b happens, buy it etc" these rules suposedly have "earning money" as their objective, is there something that could help me to test the connection between the rules and the objective?
Comment: (+1) As reformulated, **this is a great question**: the world is chock full of "technical indicators" designed to help make investment decisions in markets. Most of them are self-serving BS, based on illusions stemming from overfitting, lack of cross-validation, lack of confirmation, and so on. For instance, how would a statistician go about testing the ["head and shoulders" indicator](http://www.trade10.com/Head_Shoulders.html) so beloved of "chartists"? (To begin with, it's impossible to find any unambiguous definition of this pattern, a sign that pseudo-statistics is in play.)
Comment: I think you will need to be a little more specific to turn this into the sort of statistical question that people can help you with.  The two questions that would be particularly helpful are: which stock market indicators (or at least type of indicators); and what do you mean by "validity".
Comment: @whuber Yes. I started to think: "How can I define such a pattern?" the after exaustive trials, I started to doubt about it.
Comment: Validity: It being true or not?
Comment: The issue being, that something like the Dow Jones index is just an average of some sort of various stock prices, so it is by definition "true" for that particular average of stock prices.  What is the underlying concept you want the index to be a valid sign of?  What would it mean for the Dow Jones index to be "true" or not? - for example, it doesn't claim to have predictive power.  I'm assuming you're not concerned about whether there is deception involved in the various published indices.
Comment: I want to find methods for testing [technical analysis](http://en.wikipedia.org/wiki/Technical_analysis) indicators.
Comment: Oh, it's not about indexes, it's about technical indicators and the rules associated with them.
Comment: The tools I want could be anything, the technical analysis indicators are a list of values built from some stocks market parameters, such as price and volume - from these newly built indicators, there are some rules "if n happens, sell it, if b happens, buy it etc" these rules suposedly have "earn money" as their objective, is there something that could help me to test this?
Answer: Now that the question is a little less vague I think I can guess at what you are driving at and give a suggestion.  Test you indicator using regression or correlation with the outcome they are suppose to predict.  If they lack correlation then by your terms they are not valid.
Comment: Sorry for the vague question, I naively/unconsciously presumed that you knew about the technical analysis indicators.
Answer: Why not backtest them against a benchmark (e.g. for US stocks, how did it compare to the S&P500 in terms of risk/return)? If the indicator requires past data like moving averages, or has numeric terms, just make sure you're only calculating on previous data using a rolling window function to avoid 'data snooping'.
Simplest way is to use a software package like R (or excel for simpler things) and have a dummy variable in your data that equals 1 for a long position, 0 for no position and -1 for a short position. Then you can run calculations like sum, mean and standard deviation on the log returns of the actual asset multiplied by this dummy variable; and compare it against your benchmark. If it 'beats the market', its worth investigating further while paying close attention to transaction costs/market depth (if there is very little liquidity at the historical price point, you would likely have gotten a much worse price as your trade would have affected the market price adversely).


Can't enable logging for Bind 9 on Red Hat

Question: When I enable logging for Bind, I get a permissions denied error which is due to Bind running in chroot/selinux (avc denied write). I can't figure out how to reconfigure selinux to allow the log file to be writeable. Please could someone help?
Thank you!!
Comment: What did you try?
Answer: Try restoring the context on the file (as root):
<code>touch /var/log/file # if it doesn't already exist
restorecon -v /var/log/file
</code>
For more info, this should help: http://wiki.centos.org/HowTos/SELinux


Contagem de Resultados na BD para paginação

Question: Estou com um problema, eu quero saber quantos dados existem na Base de Dados, mas com este código está a retornar -1 já utilizei este código para outros trabalhos (só que com mysql), neste caso é com SQL Server
$pag = (isset($_GET['pag'])) ? strip_tags((int)$_GET['pag']) : '1';

                                $maximo = '6';//produtos por pagina

                                $stmt2 = $conn->prepare("SELECT * FROM cl");
                                $stmt2->execute();
                                $totalRegistros2 = $stmt2->rowCount();
                                $paginas2 = ceil($totalRegistros2/$maximo);

                                if(isset($_GET['pag'])){
                                    if (($_GET['pag']>$paginas2)||($_GET['pag']<1)){
                                        $pag=1;
                                    }
                                }

                                $inicio = ($pag * $maximo) - $maximo;
                        echo $totalRegistros2;
                        echo $count;

Answer: Da documentação do PHP em relação à função rowCount()

If the last SQL statement executed by the associated PDOStatement was
  a SELECT statement, some databases may return the number of rows
  returned by that statement. However, this behaviour is not guaranteed
  for all databases and should not be relied on for portable
  applications.

Se a última instrução for um SELECT não é garantido que o rowCount() devolva o número de registos. Depende do SGBD.
Se queres saber o número total de registos podes sempre fazer
$sql = "SELECT count(*) AS total_records FROM cl";
$rs_result = $db_connection->query($sql);
$total_records = $rs_result->fetch_assoc()['total_records'];

Comment: Muito Obrigado pela ajuda.
Answer: Você pode usar SELECT count(*) FROM cl para saber quantas linhas/registros essa tabela possui.
Answer: Aqui fica direitinho com PDO
$stmt2 = $conn->prepare("SELECT count(*) AS total_records FROM cl");
$stmt2->execute();
$total_records = $stmt2->fetch(PDO::FETCH_ASSOC)['total_records'];


SSH console losing original keyboard layout after killing a .Net Core console app

Question: I am currently developing a C# embedded project on a Yocto/Arm32 platform.  It was working just fine with Dotnet Core v3.1, but I just got one annoying problem moving to DotNetCore v6:  When running the software with console output and then killing the process with Control-C, the keyboard layout ended changed!
My questions are:

How can prevent this from happening, either by changing some DotNet software properties or by adding some command lines to my start script?
What is so special about DotNetv6 (or v5) that create this change of behavior?

Technical details:

In the runtimeconfig.json file, we already have "System.Globalization.Invariant": true

In a custom dotnet.sh file, we also have "export DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1"

The service scripts use the SysV format.

The service scripts run as "root".

Using the defaut "root" user configuration (if any).

We use a PuTTY SSH console with its default settings.

Using bash command line.

Using C# v8

The C# Trace setup code:
Trace.AutoFlush = true;
Trace.Listeners.Add(new ConsoleTraceListener());

The startup command line (from my bash script):
/opt/dotnet-runtime-6.0.13-linux-arm/dotnet  /opt/mystuff/myapp.dll

I observed no problem if the console output is sent to /dev/null

Downgrading to a lower C# version has no impact.  The only delta is the DotNet upgrade.

Changing the App "Assembly neutral language" from "en-US" to "none" did not help.

I found no cue on how getting the current keybord layout on this stripped Yocto OS (provided by a third-party). The (desperate) plan was to manually restore it after the app kill.

Thanks
Comment: I'd also be very curious to know how this can be related to.net 6 migration.
Comment: You mean you login to remote device via ssh, start your .net app, kill it with ctrl+c and then your keyboard layout changes?
Comment: @Evk: Exactly.  Also, I log as "admin", then log as "root" (e.g. "su - root"), start and kill the app, and then the keybord layout change (may be the layout change at the app start, but there is no way to tell).  Also, logging out from "root" (e.g. fallback to "admin") and login back again as root does not restore the original layout.  I have to start a new SSH session to get the original layout.  Frankly, I do not see the link with migrating to DotNetv6!
Comment: @Evk:  Testing with the Rider default "Hello World!" console application:   1) DotNet v3.1 + SSH PuTTY --> OK;

2) DotNet v6.0 + SSH PuTTY --> BAD;

3) DotNet v6.0 + SSH MobaXterm--> OK;

===> Conclusion: The DotNet v6.0 introduce a new  behavior that PuTTY cannot handle by default, but other SSH tool can.
Answer: One possible solution is to change the keyboard settings in PuTTY:

Click the PuTTY icon in the upper-left corner of the window.
From the drop-down menu, click "Change Settings".
Go to the "Terminal" item, and then the "Features" sub-item.
Under "Enabling and disabling advanced terminal features", check
"Disable application keypad mode".
Click "Apply".


Nonlinear manifold learning and distances between projected points

Question: If I use a manifold learning method to project some data points into a low dimensional space, what will be the distances between the projected points? Can I use Euclidean distance? If the distances will not be Euclidean, what kind of distance metric do I have to use and how?
Answer: It would depend on the manifold learning technique, I think.
DrLIM, for instance is Euclidean, but I've seen other metrics.  Section 6 of this paper used cosine distance, and I've seen Hamming distance as well.
Which method did you have in mind?
Comment: I wanted to use http://www.aaai.org/ocs/index.php/AAAI/AAAI10/paper/view/1924.
Comment: @Hossein Equation 2 seems to suggest that they're using Euclidean distance, but I'm not sure.
Comment: That norm is because of this : "Each point of an n-dimensional manifold has a neighbourhood that is homeomorphic to the Euclidean space of dimension n.", -from wikipedia!


Como fazer algo assíncrono com jQuery, busca no MySQL com PHP?

Question: Eu estou tendo muito problema com essa parte. Eu quero simplesmente fazer a uma busca no banco de dados e passar para o meu programa principal, isso sem dar um refresh. Eu sei fazer toda a parte do PHP e MySQL, entretanto a parte do jQuery já não é minha área, sei o básico de JS.
Seguinte: a pesquisa que quero é SELECT questoes_resolvidas FROM dados_usuario WHERE id = id_usuario;. Isso eu sei fazer. Mas o grande problema é pegar esse resultado e mandar para o meu index.php. Eu não quero mandar o resultado pra dentro de uma variável no index.php. Pode ser uma variável do próprio JavaScript mesmo.
Já tentei passar por $_SESSION mas não dá, pois tenho que atualizar a página para o $_SESSION pegar os valores atualizados. Eu não quero atualizar a página, mas a variável com a resposta do comando MySQL vai ser atualizada a todo momento que eu chamar a função try_it().
Me ajudem, por favor. Já tentei aprender esse jQuery mas acredito que preciso aprofundar em JS primeiro, e não tenho tempo pra isso no instante.
Comment: Está usando algum framework?
Comment: somente o bootstrap mas uso muito pouco
Comment: No lado do servidor é PHP puro então?
Comment: sim, eu so quero retornar uma string da uma olhada nesse outro topico, é o mesmo problema e eu detalhei lá http://pt.stackoverflow.com/questions/180156/como-buscar-valores-em-um-arquivo-php-com-jquery-ajax/180165#180165
Answer: Você pode criar uma webservice para fornecer esses dados. Basicamente um arquivo que vai retornar apenas estes dados.
Primeiro crie um arquivo, ajax.php, por exemplo. Nele vc faz a consulta e escreve o resultado. Para facilitar para vc recomendo que imprima os dados parseados em JSON.
Dps disso, no jquery vc usa o método Ajax $.ajax(options, callback)
Assincronamente ele faz uma requisicao na URL q vc passar e quando terminado chama o callback. Quando cair no callback vc trata os dados que recebeu, ou uma eventual falha
Comment: Mano me desculpa mas a unica coisa que entendi é ajax.php, não tem como você me mostrar em codigo como fazer não?
Answer: Tu vai ter que ter uma página para receber essa requisição ajax.
Exemplifiquei abaixo, a conexão com o banco é fictícia, só para ilustrar.
ajax.php
// Apenas para exemplificar uma conexão com o DB
include("conexao_db.php");

$sql = <<<SQL
    SELECT *
    FROM minha_tabela
    WHERE minha_condicao = 1;
SQL;

$resultado = $db->query($sql);
$dados = $resultado->fetchAll();
// - - - - - - - - - - - - - -

// Parte importante
header("content-type: application/json");
echo json_encode($dados);

Aí no teu HTML tu vai fazer uma requisição AJAX para a página recém criada e inclui na página atual.
index.html

Meus dados

Comment: Não quer funcionar, tá retornando NULL 5 vezes
Answer: Depois de muito tempo (nem lembrava mais dessa pergunta) descobri com algumas buscas no Google. É bem simples:
$.ajax({
    type: "GET",//Tipo da requisicao, pode ser GET, POST, etc...
    data: {dado1: "Dado 1",dado2: "Dado 2"},
    url: "url_do_arquivo_que_faz_as_coisas.php",
    beforeSend: function(){
        console.log("Isso executara antes da requisicao");
    }
    success: function(responses){
        console.log(responses);//Aqui são os dados vindos do PHP
    }
});

Se la no PHP tivessemos algo assim
echo $_GET['dado1'].' - '.$_GET['dado2'];

Teriamos o seguinte no nosso console apos fazer a requisicao AJAX:
Dado 1 -Dado 2

Espero ter ajudado quem precisa como eu precisava na época. Alem do mais, você deve colocar o código do JS em um função pq dai você chama quando quiser e quantas vezes quiser, o resto e só modificar...


sunspot solr search by multiple terms

Question: I am using the sunspot_rails gem, and I am trying to do a search like:
search users where name is Mary or Sally
But I can't figure out how to do the or. If I do something like:
search = Users.search do
  fulltext 'Mary Sally'
end

or
search = Users.search do
  fulltext 'Mary'
  fulltext 'Sally'
end

I get no results...but if I do either one, and not both, I get the expected results:
search = Users.search do
  fulltext 'Mary' #or fulltext 'Sally'
end

will return the single item.
Is this even possible with sunspot?
-------Solution-------
search = Users.search do
  fulltext 'Mary Sally' do
    minimum_match 1
  end
end

Answer: Add minimum_match 1 to your search block because default setting is to match all words, so searching for Mary Sally would return records only with those both names included.

sunspot solr search by multiple terms


react load svg image from url

Question: I am loading an svg image from a url passed in via the src prop.
The trouble I'm having is that I am storing the svg into state but when the url changes the image displayed will be the previous image clicked and not the current image
I can see that the image stored in state is always the last image selected
I believe it is how it is fetching the image from the api and storing it in to state here but I don't quite understand how this works and how it updates the state with the svg
).then(
   svg => this.state.image = svg
);

How can I change this so that state updates with the correct image?
SVG Component
import React from 'react';
import fetch from 'isomorphic-fetch';
import $ from 'jquery';

class InlineSVG extends React.Component {
  state = {
    image: '',
  };

  componentDidUpdate(prevProps) {
    this.loadSVG();
  }

  loadSVG() {
      fetch(this.props.src)
        .then(
          response => {
            if (!response.ok) return Promise.reject(new Error('Server
Error'));
            return response.text();
          }
        ).then(
          svg => this.state.image = svg
        );
  }

  render() {
    return (

    );
  }
};

export default InlineSVG

Answer: Never mutate state directly. You are mutating state directly and that's why you don't see the Updated image. When you mutate the state directly your component won't re-render and that's why updated image isn't shown
Wrong
).then(
    svg => this.state.image = svg);

Right
 ).then(
    svg => this.setState({ image:  svg});

PS:- to modify React state value you need to use setState so that your component will re render with the updated data
Comment: this works but because it's used in the ComponentDidUpdate it constantly loops, how can I prevent this?
Comment: I added a check to see if the src was different to the previous src `prevProps.src !== this.props.src && this.loadSVG()` now works :)
Comment: Cool enjoy playing with React :)

react load svg image from url


How to fix Each then() should return a value or throw

Question: I'm trying to build my server for firebase notifications, and I've watched a youtube video that showed how to write that javascript code, and I copied and pasted the code, while adjusting some paths to match my firebase database, but I have no idea what went wrong and I kind of don't know how to write in javascript.
So this is the code:
'use strict'

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.sendNotification = functions.database.ref('/Notifications/{receiver_user_id}/{notification_id}')
.onWrite((data, context) => {
    const receiver_user_id = context.params.receiver_user_id;
    const notification_id = context.params.notification_id;

    console.log('We have a notification to send to :' , receiver_user_id);

    if (!data.after.val()) {
        console.log('A notification has been deleted :' , notification_id);
    }

    const sender_user_id=admin.database().ref('/Notifications/${receiver_user_id}/${notification_id}').once('value');
    return sender_user_id.then(fromUserResult => {
        const from_sender_user_id=fromUserResult.val().from;
        console.log('you have a notification from :',sender_user_id);
        const userQuery=admin.database.ref('/Users/${receiver_user_id}/messaging_token`').once('value');
        return userQuery.then(userResult => {
            const senderUserName=userResult.val();
            return null;
        });

        const DeviceToken = admin.database().ref(`/users/${receiver_user_id}/messaging_token`).once('value');

        return DeviceToken.then(result => {
            const token_id = result.val();

            const payload = {
                notification: {
                    from_sender_user_id:from_sender_user_id,
                    title: "New Chat Request",
                    body: `${senderUserName} offered you a lesson, Please Check.`,
                    icon: "default"
                }
            };

            return admin.messaging().sendToDevice(token_id, payload)
            .then(response => {
                    console.log('This was a notification feature.');
            });
        });
    });
});

And these are the errors and warnings I'm getting:
26:44  warning  Unexpected template string expression  no-template-curly-in-string
31:38  warning  Unexpected template string expression  no-template-curly-in-string
32:10  warning  Avoid nesting promises                 promise/no-nesting
38:3   error    Unreachable code                       no-unreachable
40:10  warning  Avoid nesting promises                 promise/no-nesting

Any help would be really appriciated :)
Comment: The linting errors are all pretty self-explanatory... have you tried changing your code to fix them?
Comment: @CertainPerformance I would if I knew how, I don't really get the reasons for the failures, I have tried some stuff but the errors keep on coming in different forms... I mean, I literaly copied what the tutorial said, but the unreachable statement shouldn't appear, since it worked in the video
Comment: You have `return`s followed by further statements in the same block - clearly, those further statements will never be reached, because the function will have necessarily returned before then. If a video had this code, the video would be wrong, following your linting rules
Comment: @CertainPerformance Yeah I understood why it wouldn't work, but for some weird reason every one in the comment section were quite thankful for the code writer, meaning they compiled it w/out errors... So I'm wondering if you have any suggestion as to how would it work and reach the following statements
Answer: The first two warnings are caused by this line:
const sender_user_id=admin.database().ref('/Notifications/${receiver_user_id}/${notification_id}').once('value');

And this line:
const userQuery=admin.database.ref('/Users/${receiver_user_id}/messaging_token`').once('value');

In both cases you're using ${...} in the string to use a value from your code while building the path. This is known as expansion of a template literal. But your strings are enclosed in single quotes ', which means that it's not interpreted as a template string.
The solution is to use backticks in the code. So:
const sender_user_id=admin.database().ref(`/Notifications/${receiver_user_id}/${notification_id}`).once('value');

And:
const userQuery=admin.database.ref(`/Users/${receiver_user_id}/messaging_token`').once('value`);

Note that you shouldn't use backticks in the line that declares the Cloud Function (exports.sendNotification = functions.database.ref('/Notifications/{receiver_user_id}/{notification_id}')), as that string is what literally should be passed to the firebase-functions module.
For more on this error, see the ESLint documentation for the error message. I recommend that you find the explanation for each warning/error you get and try to fix it yourself first, as it will prevent getting downvoted.


Turf.js and PostGIS 'difference' function giving unexpected result

Question: I have a polygon and a multipolygon.  I want to create a geometry that is the area where the 2 geometries do not intersect.  The result I get (red outline in the example) seems to have something like an extra point in the southmost and northmost part of the geometries and I don't understand why.
Can anyone help me figure out how I can get the result of having the red outline exactly around the purple area?
As a side note, I can get the result I'm looking for if I use PostGIS and do exactly ST_Difference(ST_SnapToGrid(poly1, 0.0000000001), ST_SnapToGrid(poly2, 0.0000000001)) from MYTABLE; however I don't comprehend why this works and it seems like it may be a brittle solution.  Any decimal difference in 0.0000000001 doesn't work (0.000001 for example gives me the same result as the turfjs result).

var map = L.map("map").setView([19.42, -155], 9);

L.tileLayer('https://stamen-tiles.a.ssl.fastly.net/toner-lite/{z}/{x}/{y}.png', {
  attribution: '© OpenStreetMap contributors'
}).addTo(map);

var poly1 = turf.polygon([[[-155.253325763,19.424193039],[-155.140558658,19.206650122],[-154.752533025,19.515649896],[-154.933670824,19.645287706],[-155.253325763,19.424193039]]]);
var poly2 = turf.multiPolygon([[[[-154.975609356,19.338005611],[-155.140558658,19.206650122],[-155.240053913,19.398589856],[-155.021104033,19.34867505],[-154.975609356,19.338005611]]],[[[-154.9542326,19.63106581],[-154.933670824,19.645287706],[-154.904729907,19.624575093],[-154.9542326,19.63106581]]]]);
var difference = turf.difference(poly1, poly2);

var myStyle = {weight: 0, fillOpacity: 0.3, fillColor: '#0000ff'};
L.geoJSON(poly1, {style: myStyle}).addTo(map);

myStyle.fillColor = '#00ff00';
L.geoJSON(poly2, {style: myStyle}).addTo(map);

myStyle = {weight: 1, opacity: 1, color: 'red', fillOpacity: 0.05, fillColor: '#ff0000'};
L.geoJSON(difference, {style: myStyle}).addTo(map);
#map {
  height: 200px;
}

<link href="https://email@example.com/dist/leaflet.css" rel="stylesheet"/>

Answer: Precision are a common problem when working with geometries. Have to use  ST_SnapToGrid or other techniques to fix topological issues before use a geoprocess is no rare
So answering one of your questions, use ST_SnapToGrid is not a bad solution. For sure it will be better that the original data exactly match but that is not always possible.
Also, just a matter of taste, but usually I found more "understable" dump multi geometries to simple geometries and operate on that, that working directly with the multi. I find easy to debug problems when using simple versions.
To fix the precision issue in turf you can try to play with truncate
var options = {precision: 4};
var poly1 = turf.truncate(poly1, options);
var poly2 = turf.truncate(poly2, options);

Comment: I found that turf/truncate still gave me the odd northmost & southmost point.  I ended up doing a string match regex to keep only the first 6 decimal places.  It seemed like the Math.round part of the turf/truncate function was still causing me to have the same problematic output.
Comment: http://jsfiddle.net/5vpnhb2a/6/
Comment: Hard to say how to fix this cliend side. I think that your solution is good enougth. I don't know your use case, but if it's possible, probably I will store the geometries already "snapped" with a trigger in the database


How to package EJB3 with external domain-jar

Question: I am facing another problem in my little test-webapp.
I have an EJB module (created via maven-pom) that basically wraps the data-access, so all it does is some DAOs implemented as Stateless-SessionBeans. My domain-model (simple POJOs with JPA2 annotations) is located in another, simple java, project that will be packaged as jar-file.
When I create the enterprise-archive, maven only puts the webapp and the ejb-module into the application.xml and even when I change this manually the ejb-module cannot find the classes from the domain-module at deployment time.
I read something about that an ejb has to have all its dependent jars within its own archive but I cant believe that since this domain-module is used by other projects as well.
How would I package this (or set it up in maven) so my ejb can load classes from an external jar?
thanks
Answer: If I remember well, simply generate a manifest with a Class-Path entry  in your EJB-JAR:
<plugins>
  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-ejb-plugin</artifactId>
    <configuration>
      <ejbVersion>3.0</ejbVersion>
      <archive>
        <manifest>
          <addClasspath>true</addClasspath>
        </manifest>
      </archive>
    </configuration>
  </plugin>
  ...
</plugins>

And add your external jars to the EAR. To do so, declare them as jarModule in the Maven EAR plugin configuration. See modules configuration.
Comment: Could it be the same problem as here: https://glassfish.dev.java.net/issues/show_bug.cgi?id=10592? Does your `web.xml` reference 2.5 schema?
Comment: Thanks, but now I am getting the next error that is related to this (the ClassNotFoundException is gone): Unable to load EJB module. DeploymentContext does not contain any EJB Check archive to ensure correct packaging.
Comment: Yes, that was it. Getting another error now, because my web-xml seems not valid any more but I got passed the described point. Thanks a lot.


Executar requisição ao mudar valor em uma select

Question: Não estou conseguindo executar a função ao mudar o valor do select, segue o código abaixo.
index.php

            Estado

        <select class="custom-select" id="cmb_estado_site"></select>

            Cidade

        <select class="custom-select" id="cmb_cidade_site">
            <option selected="TODAS" >TODAS</option>
        </select>

function.js
$(document).ready(function() {

    $('#cmb_estado_site').click(function () {
        var estado = $('#cmb_estado_site').val();
        $.post('/lib/php/function.php',{action:'load-cidade', estado:estado},function (data) {
            $('#cmb_operadora_site').html(data);
        });
    });
}

o retorno da requisição post está correto, testei pelo postman, pelo debug não está entrando na função, alguém poderia me informar o que estou fazendo de errado?
Comment: Consegui resolver, o erro estava na forma como eu carregava a pagina, estava pegando de outro arquivo o código destas combos, isto depois de já ter carregado o script, por isso acho que não estava acionando o evento, mas obrigado pela atenção.
Comment: Mostra como é o formato da resposta do $.post, (o que aparece se eu der um console.log(data) dentro do método `done `) para que a gente possa construir uma resposta mais completa.
Answer: Use o change() ao invés do click()

EDIT
Como apontado nos comentários pelo José Guilherme Oliveira, o ID que recebe os dados é #cmb_operadora_site, mas aparentemente deveria ser #cmb_cidade_site
Comment: E o ID que recebe os dados é #cmb_operadora_site, mas não deveria ser #cmb_cidade_site?
Comment: exatamente José Guilherme Oliveira, já mudei tantas vezes esse código que até na hora de copiar copiei errado.

```javascript
$('#cmb_estado_site').change(function () {
        var estado = $('#cmb_estado_site').val();

        $.post("/lib/php/function.php", {action: "load-cidade", estado: estado})
            .done(function( data ) {
                $('#cmb_operadora_site').html(data);
            })
            .fail(function() {
                alert( "Ocorreu um erro!" );
            });
    });
```
mesmo desta maneira não está funcionando
Comment: parece não estar entrando na função, coloquei um breakpoint dentro da função e ele não está sendo acionado
Answer: Recomendo você usar o método done() para usar o dado vindo do seu endpoint e também usar o método fail() para tratar algum possível erro que possa ocorrer, como um erro de conexão. Além disto, troque o listener de click() para change(). Faça assim:
$(document).ready(function() {
    $('#cmb_estado_site').change(function () {

    $.post("/lib/php/function.php", {action: "load-cidade", estado: estado})
        .done(function( data ) {
            $('#cmb_operadora_site').html(data);
        })
        .fail(function() {
            alert( "Ocorreu um erro!" );
        });
    });
}


Translate the circle on image while zooming in/out the image

Question: I have one image and had a circle(drawn using css3) in it.
Now when I zoom in/out the image, I want to keep the position of the circle at the same location in the image, so that when image zoom in/out the circle will translate, but I am unable how to calculate the co-ordinates by which I need to translate the circle on image zoom in/out. Any suggestion!!
The image and the circle are the sibling elements in HTML
Comment: How do you zoom the image? Could you show us your code?
Comment: Besides the zoom, here is the best answers you can find to keep an floating element in position on a background image: http://stackoverflow.com/questions/35942014/scale-element-proportional-to-background-cover-with-jquery ... even a CSS only solution at this post: http://stackoverflow.com/a/36097410/2827823
Comment: @Tresdin, I am using css scaling feature
Answer: It took me a while but I wrote something that can be used with  tag and another element with position:absolute;.

$(document).ready(function() {
  function setDimentions(first) {
    IW = $('.img_container img').width();
    IH = $('.img_container img').height();
    PW = $('.pointer').outerWidth();
    PH = $('.pointer').outerHeight();
    pointerL = Number($('.pointer').css('left').replace('px', ''));
    pointerT = Number($('.pointer').css('top').replace('px', ''));
    if (first) {
      Lperc = pointerL * 100 / IW;
      Tperc = pointerT * 100 / IH;
      Wperc = PW * 100 / IW;
      Hperc = PH * 100 / IH;
    }
    Lpx = Lperc * IW / 100;
    Tpx = Tperc * IH / 100;
    Wpx = Wperc * IW / 100;
    Hpx = Hperc * IH / 100;
  }
  setDimentions(true);
  $(window).on('resize', function() {
    setDimentions();
    $('.pointer').css({
      'width': Wpx,
      'height': Hpx,
      'top': Tpx,
      'left': Lpx
    })
  })
});
* {
  margin: 0;
  box-sizing: border-box;
}
.img_container {
  width: 80%;
  margin: 0 10%;
  position: relative;
}
img {
  max-width: 100%;
}
.pointer {
  width: 30px;
  height: 30px;
  border-radius: 999px;
  border: thin solid red;
  position: absolute;
  left: 35%;
  top: 16%;
}


How to Choose the Best Alternate Tuning

Question: This is essentially a generalized version of this question for fingerstyle guitar, and I'm surprised I can't find it on this website: how do I find the most optimal alternate tuning for a guitar/bass(/banjo/ukulele/mandolin)/etc. piece?
There's got to be a way, I believe: for example, Jonny Atma is convinced that "You Will Know Our Names" from Xenoblade Chronicles is written in Drop D#, at least according to his page on his remix of that boss theme. Especially since Drop D# is such a rare tuning that he didn't want to retune any of his guitars to that tuning, he's got to have reached that conclusion about the optimal tuning for good reason.
Comment: @Dekkadeci D#-A#-D#-G#-C-F is actually just drop-D with capo 1.
Comment: Is there ever a "best" alternate tuning? Guitarists can't even seem to agree whether standard tuning or all-fourths tuning is better. Hint: it's standard tuning ;)
Comment: I guess drop D#/Eb is downtuning the bottom string just one fret. Is that such a big deal that it can't be done in seconds - and retuned/returned in the same time, to standard tuning?
Comment: @Tim - Jonny Atma actually gives Drop D# as D#-A#-D#-G#-C-F on that web page, and he opted to play "You Will Know Our Names" with D# Standard tuning instead, despite finding it suboptimal for the piece, because he had a guitar already tuned in that.
Comment: @leftaroundabout - It's probably a sign that I've never noticed a capo on an electric guitar or bass in a Jonny Atma GaMetal video.
Comment: So does that mean everything was dropped by one semitone - like Jimi and SRV used to do?
Comment: Pretty sure Jung, like all other guitarists, chooses alternate tunings on a song-to-song basis. I doubt there's a secret formula, but if the original used a different tuning, you probably should too...
Comment: Is there a point in 'drop D#' - 'drop D with capo 1'? I can't think of one.
Comment: @DavidBowling - I don't think there's a best overall alternate tuning--just the best alternate tuning for a given piece. I bet Jonny Atma used a different tuning for his remix of the Tetris A theme (for example).
Answer: It is my experience that each individual guitar player has their own preference when it comes to alternate tunings. That leads me to believe that the selection process used by most is a trial and error process used to eliminate alternate tunings that are uncomfortable for the performer to play, or maybe the fingering patterns are a little more confusing for the player so they avoid certain tunings. I would expect the style of playing would also be a factor to consider, whether it be blues, finger-style, slide etc.
As best I can tell, the magic bullet you seem to be looking for is different for each individual and requires study and experimentation in order to discover its existence.
I'm open to being proven wrong1
Answer: The main purpose of alternative tunings on guitar is to allow for unusual chord voicings, especially to have a particular "mood sound" from the open strings alone. This applies also somewhat to other instruments, in particular scordatura on cello or violin, but doesn't really make much sense for bass because open strings are so low-pitched that using them for any chords gives little more but musically useless sub-rumble. Bass is usually played mostly monophonically, and for that switching between tunings accomplishes little but messes with muscle/scale memory. The only alternative tuning that's really common is drop-D, and basically its only purpose is to extend the bottom range on a 4-string bass. Same with drop-E♭: you'd use it if a piece benefits from having a low E♭ but you want to change as little as possible about the instrument or effects.
That said, for virtuoso bassists alternative tunings do become interesting: some use chords on unfretted strings a lot, but not so much on open strings as flageolett harmonics. There's a lot of interesting options here, in fact far too many to fit them in an SO post. There's a lot you could just try and experiment, which is probably how most guitarists go about this as well. For example, the one piece I wrote for scordatura guitar is heavily based around the mysterious-misty sound of the sus4♭69 chord, in this case D-G-♭B-E. It's used mostly in harmonics, which is what you'd probably also do on bass.
Comment: @TimBurnett-Bassist I mean generally any nonstandard tuning that is not all-fourths. Changing all the strings by the same interval is obviously just transposition, and may only be a problem if you have perfect pitch!
Comment: "for that switching between tunings accomplishes little but messes with muscle/scale memory"  - I assume you mean in the case of down-tuning only one of the strings? (Like dropping the E to Eb or D?) Perhaps it's obvious that it shouldn't be the case if one tunes down all the strings of a bass... but, I'd agree that there would be little to no use in ever actually doing that
Answer: I think it's worth mentioning here that a major reason that guitarists and other stringed instruments use an alternate tuning is to accommodate a singer's voice. Though I believe you are referring specifically to instrumental music given your example, this fact also supports the case that D# tuning (usually called Eb tuning) is not that rare at all, at least in pop-music. It's fairly common knowledge that artists like Jimi Hendrix, Black Sabbath, and Led Zeppelin used Eb tuning.
As previously stated, it is common to use an alternate guitar tuning to create a heavier/darker mood and/or increase the ability to bend the strings (by tuning lower than standard.) However, I have also heard the virtuoso instrumentalists, like Steve Vai and Joe Satriani, sometimes tune to a semitone higher or lower for the explicit purpose of making their riffs and licks more difficult to understand and replicate.
And considering that the determining the "best" of anything is highly subjective in nature, I'd have to agree with the other answers in that it is all about what you want to get out of the music. Using an alternate tuning exposes you to a different spread of sound which could potentially even contribute to inspiring a new song or three...
To expound on leftaroundabout's answer, another alternate bass tuning, for 5 and 6 string basses, is to drop to Bb on the low string; essentially used for the same reasons as dropping down to Eb. In my own experience, this can come in handy when accompanying and/or replicating an 808 in hip-hop or reggae. But, dropping the low B any more than that tends to make the sound way too muddy.
EDIT
See this question and this question for similar inquiries and responses...

How to Choose the Best Alternate Tuning


Summation of integrals over odd and even parts

Question: Let the function $f: [0,1]\rightarrow \mathbb{R}$ be continuous.
For $n\in \mathbb{P}$, partition $[0,1]$ into $2n$ equal pieces, and add up the integrals over the odd and even parts separately.
$$A_{n}=\sum_{k=1}^{n}\int_{\frac{2k-2}{2n}}^{\frac{2k-1}{2n}}f(x)dx$$
$$B_{n}=\sum_{k=1}^{n}\int_{\frac{2k-1}{2n}}^{\frac{2k}{2n}}f(x)dx$$
Prove the following:
$$\lim_{n\rightarrow \infty }A_{n}=\lim_{n\rightarrow \infty }B_{n}=\frac{1}{2}\int_{0}^{1}f(x)dx$$
This is a problem from my analysis class. I am not sure how to approach the problem. Here are some of my thoughts:
Since the function is continuous on a compact set $[0,1]$, it is therefore integrable, and the integral over the closed interval $[0,1]$ is well-defined.
It is easy to show that $$\forall n\in \mathbb{P},A_{n}+B_{n}=\int_{0}^{1}f(x)dx$$
Therefore it suffices to show
$$\lim_{n\rightarrow \infty }A_{n}=\lim_{n\rightarrow \infty }B_{n}$$
Any suggestions on what to do next?
Thanks!
Comment: It suffices to show that $ \exists N \in \Bbb N$ such that $n \ge N \implies |A_n - B_n| < \epsilon$
Comment: To add to Santosh's comment, use the fact that continuous on compact implies uniformly continuous.
Answer: Since $f$ is a continuous function, we can apply the Mean Value Theorem for Integrals to find points $\xi_k \in [\frac{2k-2}{2n},\frac{2k-1}{2n}]$ and  $\xi_k' \in [\frac{2k-1}{2n},\frac{2k}{2n}]$ such that
$$A_{n}=\sum_{k=1}^{n}\int_{\frac{2k-2}{2n}}^{\frac{2k-1}{2n}}f(x)dx = \frac{1}{2n}\sum_{k=1}^{n} f(\xi_k), \\\ B_{n}=\sum_{k=1}^{n}\int_{\frac{2k-1}{2n}}^{\frac{2k}{2n}}f(x)dx = \frac{1}{2n}\sum_{k=1}^{n} f(\xi_k').$$
where $|\xi_k - \xi_k'| \leq \frac{1}{n}$.
As $f$ is uniformly continuous on $[0,1]$, for each $\epsilon > 0$ there exists $\delta >0$ such that for all sufficiently large integers $n$ we have
$$|\xi_k - \xi_k'| \leq \frac{1}{n}< \delta, \\\ |f(\xi_k) - f(\xi_k')| < 2\epsilon $$.
Hence, for sufficiently large $n$ it follows that
$$|A_n - B_n| \leq \frac{1}{2n}\sum_{k=1}^{n} |f(\xi_k)-f(\xi_k')|<\frac{1}{2n}n(2\epsilon)= \epsilon,$$ and
$$\lim_{n\rightarrow \infty }[A_{n}-B_{n}]=0.$$
Since $A_n+ B_n = \int_{0}^{1}f(x)dx$, it follows that
$$\lim_{n\rightarrow \infty }A_{n}=\lim_{n\rightarrow \infty }B_{n}= \frac{1}{2}\int_{0}^{1}f(x)dx.$$
Comment: Now that I'm thinking about it, I'm having anxiety that you also need to show that $\lim A_n$ and $\lim B_n$ both exist and are finite.
Comment: @Callus:  Good to think about these things. As I showed the limit of the difference $(A_n-B_n)$ is $0$ and we know the sum $A_n+B_n$ equals the integral, we get the desired result. Note that $2A_n = (A_n-B_n)+(A_n+B_n)$ so the individual limits exist. Furthermore, using IVT we see that $A_n$ and $B_n$ are themselves Riemann sums with a factor of $1/2$ that converge as the norm of the partition goes to $0$ -- hence, we really did not have to use the uniform continuity.
Comment: Right, agreed.  And good point on seeing the sums as half the Riemann sum, that's cleaner.
Comment: @Callus: Thank you for the useful comments


Distance between a point and a circle circumference given angle from point

Question: Let us assume that I have a circle with radius $r$ and centre $C$ and a point $P$. How can I find the length of the line segment starting from $P$ with a specific angle $\theta$, ending on the circumference of the circle (assuming that I chose the angle so that is the case). If the line intersects twice (that is if it is not a tangent), I want the distance to the closest point.
I know that I can easily find the angle and distance between the points, but I am not sure how it will help me. I also assume that the approach consists of finding the point where the line and circle intersects in order to find the distance between the points.
UPDATE:
$P$ can be where ever in the plane as long as it is outside the circle.
$\theta$ is measured according to the x-axis (I'm not sure that is a very accurate description, ask if you do not understand)
Comment: I am not sure I get what you are asking, lulu. But it is no problem for me finding the (euclidean) distance between the centre of the circle and the point.... Oh you updated your question. I don't have X, that is my problem. The angle is from the point not on the circl.e
Comment: How do you define the $\theta$ angle the line makes with the circumference, and are there conditions on $P$?
Comment: Presumably you are given something like $d(P,C)$?  If $X$ is the point on the circle then however you define $\theta$ you can use it to compute $\angle CXP$, no?  So you can invoke the law of cosines.
Comment: Oh, I think i was just being stupid, I see what you mean now. I will check it out, and if it makes sense for me I will accept your answer.
Answer: The equation of the line can be written
$$
\mathbf{X}(t) = \mathbf{P} + t(\cos\theta, \sin\theta)
$$
If $\mathbf{P} = (a,b)$, then this becomes
\begin{align}
x &= a + t \cos\theta  \\
y &= b + t \sin\theta  \\
\end{align}
Suppose the circle center is at $\mathbf{C} = (h,k)$ and its radius is $r$. Then it's equation is
$$
(x-h)^2 + (y-k)^2 = r^2
$$
Substitute $x$ and $y$ from above into this equation, and you'll get a quadratic in $t$.  Find its real roots $t_1$ and $t_2$ (if any). Then the intersection points are $\mathbf{P} + t_i(\cos\theta, \sin\theta)$ for $i=1,2$.
Answer: On an $x,y$ Cartesian plane,
suppose we are given the coordinates of a point $C$, the radius $r$ of
a circle around $C$, the coordinates of a point $P$ outside the circle,
and a ray $\overrightarrow{PQ}$ starting at $P$ at an angle of $\theta$ clockwise from the $x$-axis. (The coordinates of $Q$ need not be known;
it is used here just as a way to name a particular ray starting at $P$.)
Find the distance $d$ from $P$ to $C$ and
the direction $\theta_0$ (clockwise from the
$x$-axis) of the ray $\overrightarrow{PC}$ from $P$ through $C$.
Compute the angle $\alpha$ between the rays $\overrightarrow{PQ}$ and $\overrightarrow{PC}$;
it is $\lvert \theta - \theta_0 \rvert$,
$\lvert \theta - \theta_0 + 2\pi \rvert$,
or $\lvert \theta - \theta_0 - 2\pi \rvert$,
whichever is smallest.
If $\alpha \geq \frac\pi2$ then there is no intersection, so we're done.
In all of the discussion below, assume that $\alpha < \frac\pi2$.
If $M$ is the point on ray $\overrightarrow{PQ}$ closest to $C$,
the triangle $PMC$ is a right triangle with a right angle at $M$
and the angle $\alpha$ at $P$.
Therefore the distance $CM = d \sin \alpha$
and the distance $PM = d \cos\alpha$.
(Note that we compute all of this without needing to find the coordinates of $M$.)
If $d \sin \alpha > r$ then there is no intersection.
If $d \sin \alpha = r$ then the ray $\overrightarrow{PQ}$ is tangent to the circle, $M$ is the point of tangency and is one endpoint of the line segment, and the distance $PM$ is $d \cos \alpha$.
If $d \sin \alpha < r$ then ray $\overrightarrow{PQ}$ intersects the circle in two points.
One of these points is between $P$ and $M$; call that point $X$.
Then $XMC$ is a right triangle with hypotenuse $XC = r$
and leg $CM = d \sin \alpha$; the length of the other leg is
therefore $XM = \sqrt{r^2 - d^2 \sin^2 \alpha}$.
Therefore
$$PX = PM - XM = d \cos \alpha - \sqrt{r^2 - d^2 \sin^2 \alpha},$$
which is the distance we were to find.


How to get started with applying item response theory and what software to use?

Question: Context
I have been reading about item response theory, and I find it fascinating. I believe I understand the basics, but I am left wondering how to apply statistical techniques related to the area. Below are two articles that are similar to the area I would like to apply ITR in:

http://www.jstor.org/stable/4640738?seq=7
http://www.ncbi.nlm.nih.gov/pubmed/21744971

The second being the one I would actually like to extend at this point in time.
I have downloaded a free program called jMetrik, and it seems to be working great. I think it may be too basic as far as IRT goes, but I am unsure.
I know the "best" way would likely involve learning R; however, I don't know if I can spare the time to tackle that learning curve. Note that we have some funding to purchase software, but from what I see, there doesn't seem to be any great IRT programs out there.
Questions

What are your thoughts on the effectiveness of jMetrik?
How would you suggest I go forward in applying IRT?
What are the best programs for applying IRT?
Do any of you use IRT regularly? If so, how?
Comment: Does it work in a script mode? If you only have a GUI, then your results will be very difficult to reproduce. A script mode is a must for any serious software.
Comment: what software do you currently use?
Comment: I have been using jMetrik. It is quite new it looks like and has been doing a lot of the things I am interested in!
Comment: It has a log export feature.
Answer: As a good starter to IRT, I always recommend reading A visual guide to item response theory.
A survey of available software can be found on www.rasch.org.
From my experience, I found the Raschtest (and associated) Stata command(s) very handy in most cases where one is interested in fitting one-parameter model. For more complex design, one can resort on GLLAMM; there's a nice working example based on De Boeck and Wilson's book, Explanatory Item and Response Models (Springer, 2004).
About R specifically, there are plenty of packages that have become available in the past five years, see for instance the related CRAN Task View. Most of them are discussed in a special issue of the Journal of Statistical Software (vol. 20, 2007). As discussed in another response, the ltm and eRm allow to fit a wide range of IRT models. As they rely on different method of estimation---ltm used the marginal approach while eRm use the conditional approach---choosing one or the other is mainly a matter of the model you want to fit (eRm won't fit 2- or 3-parameter models) and the measurement objective you follow: conditional estimation of person parameters has some nice psychometric properties while a marginal approach let you easily switch to mixed-effects model, as discussed in the following two papers:

Doran, H., Bates, D., Bliese, P. and Dowling, M. (2007). Estimating the Multilevel Rasch Model: With the lme4 Package. Journal of Statistical Software, 20(2). See also Doug Bates's slides on R-forge
De Boeck, P., Bakker, M., Zwitser, R., Nivard, M., Hofman, A., Tuerlinckx, F., and Partchev, I. (2011). The Estimation of Item Response Models with the lmer Function from the lme4 Package in R. Journal of Statistical Software, 39(12). See also the aforementioned De Boeck's handbook and this handout

There are also some possibilities to fit Rasch models using MCMC methods, see e.g. the MCMCpack package (or WinBUGS/JAGS, but see BUGS Code for Item Response Theory, JSS (2010) 36).
I have no experience with SAS for IRT modeling, so I'll let that to someone who is more versed into SAS programming.
Other dedicated software (mostly used in educational assessment) include: RUMM, Conquest, Winsteps, BILOG/MULTILOG, Mplus (not citing the list already available on wikipedia). None are free to use, but time-limited demonstration version are proposed for some of them. I found jMetrik very limited when I tried it (one year ago), and all functionalities are already available in R. Likewise, ConstructMap can be safely replaced by lme4, as illustrated in the handout linked above.
I should also mention mdltm (Multidimensional Discrete Latent Trait Models) for mixture Rasch models, by von Davier and coll., which is supposed to accompagny the book Multivariate and Mixture Distribution Rasch Models (Springer, 2007).
Comment: Fantastic! Thank you for the very comprehensive answer! Both of these answers will help me nicely, as well as anyone else who is curious in pursuing this area I'm sure. I do suggest you take a look at jMetrik again, and perhaps give me your thoughts. It has Rasch modelling now, ICC curves, some IRT curves, IRT equating (1PT, 2PT, 3PT models), and more.
Comment: I will look at the updated version. But, honestly, what @Stask said is worth to remember if you plan to do anything serious beyond parameters estimation and visual reporting. To get an idea of what I mean, look at [An introduction to psychometric theory with applications in R](http://personality-project.org/r/book/). (It covers more than just what some call "modern" psychometrics.)
Comment: @chi - I got very different results when I ran IRT analyses in R using ltm compared to when I ran the same analysis in Mplus and then in Multilog (whereas analysis in Mplus and Multilog were identical). I tried to work out why with the author of ltm, but did not receive any responses. Have you had any similar experiences with discrepant results from different software packages?
Comment: @Tormod Very different in what sense? Running the `ex5.5` example in Mplus and R/ltm, I got approx. the same results. Some variations depending on software being used are to be expected, though. Usually, what I've found is related to the choice of the parametrization (logit/probit), whether it's $\theta_p-\beta_i$ ($i=1,\dots,k$ items, $p=1,\dots,n$ persons) or $\beta_i-\theta_p$ that is modeled, and the estimation method (marginal vs. conditional likelihood), and for 2+ parameter models whether thresholds are centered or not.
Comment: @chi - sorry for the delay in response, I haven't noticed your comment. Don't know if this is still relevant, but I got differences varying from 0.184 - 1.429 for the discrimination parameters (a). For example, Mplus gave an a=5.084 whereas ltm gave the same item an a=3.655. Overall, ltm gave smaller a's than mplus. (Running the same analyses in multilog gave a's corresponding to the a's from Mplus). The b's were more similiar.
Comment: @Tormod Will check again and come back to you asap.
Answer: To the first question, I don't have any information about jMetrick.
In applying IRT, (as with any other statistical procedure) the first step is to use it with as many different kinds of data as possible. There is a learning curve, but I believe that it is worth it.
One important feature of IRT is the differentiation between Rasch models and IRT models. They were developed by different people for different purposes. That being said, IRT models are a superset of Rasch models.
Rasch models are one parameter models - they assume that all items on a questionnaire are equally predictive of the latent trait.
IRT models, however are two parameter models which allow the questions to differ in their ability to provide information about the ability of participants.
In addition, there are three parameter models which are like the IRT models, except that they allow for a guessing parameter to account for participants ability to get the right answer by chance (this is more of a concern in ability rather than personality tests).
In addition, there is multidimensional IRT which estimates multiple latent abilities at once. I don't know much about this, but its an area which I intend to learn more.
There is also a distinction between dichotomous and polytomous IRT methods. Dichotomous IRT models are those used in ability tests, which have a right and wrong answer. Polytomous IRT models are used in personality tests, where there are multiple answers, which are equally right (in the sense that there is no correct answer).
I personally use R for item response theory. There are two main packages that I have used, eRm which fits Rasch models only, and ltm which fits item response theory models (two and three parameter models). Both have similiar functionality, and both provide more routines for dichotomous IRT models. I don't know if R is the "best" for IRT, it does not have all of the multitude of IRT models available, but it is certainly the most extensible, in that one can program these models relatively easily.
I use IRT almost exclusively for polytomous models, in R. I typically start with non parametric IRT methods (provided in the package mokken) to test the assumptions, and then proceed with a rasch model, adding more complexity as required to get good fit.
For multidimensional IRT, there is the package `mirt', which provides this functionality. I have not used it so I cannot really comment.
If you do install these packages into R, and call the 'vignette("packagename")' function then you should get some useful vignettes (definitely for eRm and mokken, possibly for the others) which may prove useful for you (depending on your level of mathematical sophistication).
Finally, there are a number of good books available for rasch and irt models. Item response theory for psychologists is often used (though I didn't like the style), and further up the technical sophistication chain, there are two extremely comprehensive and useful textbooks - the Handbook of Modern Item Response Theory and Rasch Models:Foundations, Recent Developments and Applications.
I hope this helps.
Comment: Thank you! That is much appreciated. I would also like to hear more about software options if someone has some knowledge in the area.
Answer: jMetrik is more powerful than you may think. It is designed for operational work where researchers need multiple procedures in a single unified framework. Currently you can estimate IRT parameters for the Rasch, partial credit and rating scale models. It also allows for IRT scale linking via the Stocking-Lord, Haebara and other methods. Because it includes an integrated database, the output from the IRT estimation can be used in scale linking without the need to reshape data files. Moreover, all output can be stored in the database for use with other methods in jMetrik or external programs like R.
You can also run it with scripts instead of the GUI. For example, the follwing code will (a) import data into the database, (b) score items with an answer key, (c) estimate Rasch model parameters, and (d) export data as a CSV file. You can use the final output file as input into R for further analysis, or you can use R to connect directly to the jMetrik database and work with the results.
#import data into database
import{
     delimiter(comma);
     header(included);
     options(display);
     description();
     file(C:/exam1-raw-data.txt);
     data(db = testdb1, table = EXAM1);
}

#conduct item scoring with the answer key
scoring{
     data(db = mydb, table = exam1);
     keys(4);
     key1(options=(A,B,C,D), scores=(1,0,0,0), variables=  (item1,item9,item12,item15,item19,item21,item22,item28,item29,item30,item34,item38,item42,item52,item55));
     key2(options=(A,B,C,D), scores=(0,1,0,0), variables=(item4,item6,item16,item18,item24,item26,item32,item33,item35,item43,item44,item47,item50,item54));
     key3(options=(A,B,C,D), scores=(0,0,1,0), variables=(item3,item5,item7,item11,item14,item20,item23,item25,item31,item40,item45,item48,item49,item53));
     key4(options=(A,B,C,D), scores=(0,0,0,1), variables=(item2,item8,item10,item13,item17,item27,item36,item37,item39,item41,item46,item51,item56));
}

#Run a Rasch models analysis.
#Item parameters saved as database table named exam1_rasch_output
#Residuals saved as a databse table named exam1_rasch_resid
#Person estimates saved to original data table. Person estimate in variable called "theta"
rasch{
     center(items);
     missing(ignore);
     person(rsave, pfit, psave);
     item(isave);
     adjust(0.3);
     itemout(EXAM1_RASCH_OUTPUT);
     residout(EXAM1_RASCH_RESID);
     variables(item1, item2, item3, item4, item5, item6, item7, item8, item9, item10, item11, item12, item13, item14, item15, item16, item17, item18, item19, item20, item21, item22, item23, item24, item25, item26, item27, item28, item29, item30, item31, item32, item33, item34, item35, item36, item37, item38, item39, item40, item41, item42, item43, item44, item45, item46, item47, item48, item49, item50, item51, item52, item53, item54, item55, item56);
     transform(scale = 1.0, precision = 4, intercept = 0.0);
     gupdate(maxiter = 150, converge = 0.005);
     data(db = testdb1, table = EXAM1);
}

#Export output table for use in another program like R
export{
     delimiter(comma);
     header(included);
     options();
     file(C:/EXAM1_RASCH_OUTPUT.txt);
     data(db = testdb1, table = EXAM1_RASCH_OUTPUT);
}

The software is still in its early stages of development. I am currently adding exploratory factor analysis and more advanced item response models. Unlike many other IRT programs, jMetrik is open source. all of the measurement procedures use the psychometrics library which is currently available on GitHub, https://github.com/meyerjp3/psychometrics. Anyone interested in contributing is welcomed.
Answer: Many important developments have been made in item response theory (IRT) software since you first asked your question, so an updated answer may be in order. This being said, a visual guide to item response theory remains a great reference, so I second @chl's recommendation$^1$.
Software packages mentioned above can be categorized as either IRT specialized software (e.g., BILOG/MULTILOG, Xcalibre, jMetrik, and R packages such as ltm) or more general purpose statistical software (e.g., MPLUS, SAS, STATA, and R packages such as lme4). While these packages differ in important ways, most can accommodate the most commonly used IRT models such as the two-parameter logistic (2PL) model, graded response model (GRM), Rasch/one-parameter logistic (1PL) model, & generalized partial credit model (GPCM)$^2$.
While opinions may vary, the state of the art IRT software packages today are flexMIRT - a proprietary software package that specializes in IRT models and related methods, and mirt an R package. Both packages not only can accommodate the IRT models mentioned above, they are also the most up to date when it comes to state of the art estimation algorithms and model fit information. For example, both implement the Metropolis-Hastings Robbins-Monro (MHRM) algorithm (Cai 2010a, & Cai 2010b), which allows for efficient estimation of high dimensional IRT models. Additionally, both incorporate recent developments in global model fit (e.g., see Cai, Chung, & Lee, 2023; and  Maydeu-Olivares 2014 for more information) and piecewise model fit. For these reasons, flexMIRT and mirt are the IRT packages I use the most.
$^1$ A number of good books have also recently been published. Bonifay (2019) is a good introduction for readers new to IRT, and Bock & Gibbons (2021) is a good reference for individuals with more experience with psychological measurement and/or statistics.
$^2$ See Thissen & Steinberg (1986) for a great overview of IRT models.
References
Bock, R. D., & Gibbons, R. D. (2021). Item response theory. John Wiley & Sons.
Bonifay, W. (2019). Multidimensional item response theory. Sage Publications.
Cai, L. (2010). High-dimensional exploratory item factor analysis by a Metropolis–Hastings Robbins–Monro algorithm. Psychometrika, 75, 33-57.
Cai, L. (2010). Metropolis-Hastings Robbins-Monro algorithm for confirmatory item factor analysis. Journal of Educational and Behavioral Statistics, 35(3), 307-335.
Cai, L., Chung, S. W., & Lee, T. (2023). Incremental model fit assessment in the case of categorical data: Tucker–lewis index for item response theory modeling. Prevention Science, 24(3), 455-466.
Maydeu-Olivares, A. (2014). Evaluating the fit of IRT models. In Handbook of item response theory modeling (pp. 111-127). Routledge.
Thissen, D., & Steinberg, L. (1986). A taxonomy of item response models. Psychometrika, 51(4), 567-577.
Answer: You have quite a broad list of questions here, but quite relevant for many researchers!
I highly recommend you go forward in IRT, but only if your situation meets the requirements.  For example, it fits well with the types of tests you use, and probably most importantly that you have the necessary sample sizes.  For dichotomous multiple-choice data, I recommend the 3PL model (the Rasch argument of "objective measurement" is strikingly uncompelling), and 500-1000 is generally the minimum sample size.  Dichotomous data without guessing, like psychological surveys that have Y/N responses to statements, work well with the 2PL.  If you have rating scale or partial credit data, there are polytomous models designed specifically for those situations.
IMHO, the best program for applying IRT is Xcalibre.  It is relatively user-friendly (simple GUI as well as some command-line batch-type if you want it for some reason) and produces highly readable output (MS Word reports with extensive tables and figures).  I recommend against using R for the opposite reasons.  The drawback, of course, is that it is not free, but you tend to get what you pay for as they say.  Full description, example output, and a free trial are available at www.assess.com.
Comment: Would you like to elaborate on why the argument on "objective measurement" sensu Rasch (or more correctly the possibility of specific objective comparisons) is "strikingly uncompelling"?
Answer: In the mean time there has published a new book by Frank Baker, Baker Frank B. , Seock-Ho Kim. The Basics of Item Response Theory Using R. Springer International Publishing (2017). It does not make use of R packages but offers snippets.
A (crowded) list of R packages for IRT with succinct description is available on CRAN.