qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
list | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
1,941,044 | >
> $\mathbf{a}\times \mathbf{b}$ follows the right hand rule? Why not left hand rule? Why is it $a b \sin (x)$ times the perpendicular vector? Why is $\sin (x)$ used with the vectors but $\cos(x)$ is a scalar product?
>
>
>
So why is cross product defined in the way that it is?
I am mainly interested in the right hand rule defintion too as it is out of reach? | 2016/09/25 | [
"https://math.stackexchange.com/questions/1941044",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/363952/"
]
| There's a whole algebra ("Geometric Algebra", or Clifford algebra) behind the concept of multiplying vectors. Look there to find out where the handedness comes from, why $ \cos \theta $ for $a \cdot b$ but $\sin \theta$ for $a \times b$, and many other gems. [Here](http://faculty.luther.edu/~macdonal/GA&GC.pdf)'s a great reference.
Essentially, the cross product is a vector that describes a plane. A plane is described by two vectors (in any number of dimensions), but in $\mathbb{R}^3$ we have the handy situation that a plane can also be described by a vector. So, in 3-d only, vector $c = a \times b$ describes the plane described by $a$ and $b$. Since a plane has two sides, there's a two-fold arbitrariness ("orientation") that the choice of sign handles.
The $\sin$ and $\cos$ bit is slightly more complicated, but not much. Check out the reference. | The real reason is because it is convention to use a right-handed coordinate system. If you switched to a left-handed coordinate system for some reason (I'm not sure why), then you would need to do your cross-products using a left-hand rule to get the same answers. That's really as simple as it gets. It's a result of our conventions in defining our coordinates the way we do. |
1,941,044 | >
> $\mathbf{a}\times \mathbf{b}$ follows the right hand rule? Why not left hand rule? Why is it $a b \sin (x)$ times the perpendicular vector? Why is $\sin (x)$ used with the vectors but $\cos(x)$ is a scalar product?
>
>
>
So why is cross product defined in the way that it is?
I am mainly interested in the right hand rule defintion too as it is out of reach? | 2016/09/25 | [
"https://math.stackexchange.com/questions/1941044",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/363952/"
]
| As far as $\sin \theta$ and $\cos \theta$ are concerned,
Using the law of cosines,
\begin{align}
\|\overrightarrow{v\_2}\|^2 + \|\overrightarrow{v\_1}\|^2
-2\|\overrightarrow{v\_2}\| \, \|\overrightarrow{v\_1}\| \cos \theta
&= \|\overrightarrow{v\_2} - \overrightarrow{v\_1}\|^2
\\
2x\_1 x\_2 + 2y\_1 y\_2 + 2z\_1 z\_2
&= 2\|\overrightarrow{v\_2}\|\, \|\overrightarrow{v\_1}\| \cos \theta
\\
\cos \theta &= \dfrac{x\_1 x\_2 + y\_1 y\_2 + z\_1 z\_2}
{\|\overrightarrow{v\_2}\| \, \|\overrightarrow{v\_1}\|}
\\
\cos \theta &= \dfrac{\overrightarrow{v\_2} \circ \overrightarrow{v\_1}}
{\|\overrightarrow{v\_2}\| \, \|\overrightarrow{v\_1}\|}
\end{align}
And so, $\overrightarrow{v\_1} \circ \overrightarrow{v\_2}
= \|\overrightarrow{v\_2}\| \, \|\overrightarrow{v\_1}\| \cos \theta$
Note that $\sin \theta$ is non negative for all $0 \le \theta \le \pi$.
So
\begin{align}
\sin^2 \theta &= 1 - \cos^2 \theta \\
&= 1 - \dfrac{(x\_1 x\_2 + y\_1 y\_2 + z\_1 z\_2)^2}
{\|\overrightarrow{v\_2}\|^2 \, \|\overrightarrow{v\_1}\|^2}
\\
&= \dfrac{\|\overrightarrow{v\_2}\|^2 \, \|\overrightarrow{v\_1}\|^2
- (x\_1 x\_2 + y\_1 y\_2 + z\_1 z\_2)^2}
{\|\overrightarrow{v\_2}\|^2 \, \|\overrightarrow{v\_1}\|^2}
\\
&= \dfrac{x\_2^2 y\_1^2 - 2x\_1 x\_2 y\_2 y\_1 +
x\_1^2 y\_2^2 + x\_2^2 z\_1^2 +x\_1^2 z\_2^2 - 2 x\_1 x\_2 z\_1 z\_2
+y\_1^2 z\_2^2-2 y\_2 y\_1 z\_1 z\_2+y\_2^2 z\_1^2}
{\|\overrightarrow{v\_2}\|^2 \, \|\overrightarrow{v\_1}\|^2}
\\
&= \dfrac{(-y\_2 z\_1+y\_1 z\_2)^2+(x\_2 z\_1-x\_1 z\_2)^2+(-x\_2 y\_1+x\_1 y\_2)^2}
{\|\overrightarrow{v\_2}\|^2 \, \|\overrightarrow{v\_1}\|^2}
\\
&= \dfrac
{\|\overrightarrow{v\_1} \times \overrightarrow{v\_2} \|^2}
{\|\overrightarrow{v\_2}\|^2 \, \|\overrightarrow{v\_1}\|^2}
\end{align}
And we conclude, for purely formal reasons,
$\|\overrightarrow{v\_1} \times \overrightarrow{v\_2} \|
= \|\overrightarrow{v\_2}\| \, \|\overrightarrow{v\_1}\| \sin \theta$ | As a complement to Bye\_World's illuminating answer, which defines $b \times\ c$ as the vector whose dot product with $a$ equals $\det(a, b, c)$, $\|b\|\|c\|\sin(\theta)$ is the surface of the parallelogram formed by vectors $b$ and $c$. If $a$ is a unit vector orthogonal to the $b$-and-$c$ plane, then $\det(a, b, c)$, which is the (signed) volume of the parallelepiped formed by the 3 vectors, equals the surface of the $b$-and-$c$ parallelogram. In this case, i.e.$\|a\|=1$ and angle from $a$ to $b$ (and to $c$) equal to positive $\pi/2$, one can picture $b \times c$ as $a$ times the surface of the parallelogram. |
1,941,044 | >
> $\mathbf{a}\times \mathbf{b}$ follows the right hand rule? Why not left hand rule? Why is it $a b \sin (x)$ times the perpendicular vector? Why is $\sin (x)$ used with the vectors but $\cos(x)$ is a scalar product?
>
>
>
So why is cross product defined in the way that it is?
I am mainly interested in the right hand rule defintion too as it is out of reach? | 2016/09/25 | [
"https://math.stackexchange.com/questions/1941044",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/363952/"
]
| As far as $\sin \theta$ and $\cos \theta$ are concerned,
Using the law of cosines,
\begin{align}
\|\overrightarrow{v\_2}\|^2 + \|\overrightarrow{v\_1}\|^2
-2\|\overrightarrow{v\_2}\| \, \|\overrightarrow{v\_1}\| \cos \theta
&= \|\overrightarrow{v\_2} - \overrightarrow{v\_1}\|^2
\\
2x\_1 x\_2 + 2y\_1 y\_2 + 2z\_1 z\_2
&= 2\|\overrightarrow{v\_2}\|\, \|\overrightarrow{v\_1}\| \cos \theta
\\
\cos \theta &= \dfrac{x\_1 x\_2 + y\_1 y\_2 + z\_1 z\_2}
{\|\overrightarrow{v\_2}\| \, \|\overrightarrow{v\_1}\|}
\\
\cos \theta &= \dfrac{\overrightarrow{v\_2} \circ \overrightarrow{v\_1}}
{\|\overrightarrow{v\_2}\| \, \|\overrightarrow{v\_1}\|}
\end{align}
And so, $\overrightarrow{v\_1} \circ \overrightarrow{v\_2}
= \|\overrightarrow{v\_2}\| \, \|\overrightarrow{v\_1}\| \cos \theta$
Note that $\sin \theta$ is non negative for all $0 \le \theta \le \pi$.
So
\begin{align}
\sin^2 \theta &= 1 - \cos^2 \theta \\
&= 1 - \dfrac{(x\_1 x\_2 + y\_1 y\_2 + z\_1 z\_2)^2}
{\|\overrightarrow{v\_2}\|^2 \, \|\overrightarrow{v\_1}\|^2}
\\
&= \dfrac{\|\overrightarrow{v\_2}\|^2 \, \|\overrightarrow{v\_1}\|^2
- (x\_1 x\_2 + y\_1 y\_2 + z\_1 z\_2)^2}
{\|\overrightarrow{v\_2}\|^2 \, \|\overrightarrow{v\_1}\|^2}
\\
&= \dfrac{x\_2^2 y\_1^2 - 2x\_1 x\_2 y\_2 y\_1 +
x\_1^2 y\_2^2 + x\_2^2 z\_1^2 +x\_1^2 z\_2^2 - 2 x\_1 x\_2 z\_1 z\_2
+y\_1^2 z\_2^2-2 y\_2 y\_1 z\_1 z\_2+y\_2^2 z\_1^2}
{\|\overrightarrow{v\_2}\|^2 \, \|\overrightarrow{v\_1}\|^2}
\\
&= \dfrac{(-y\_2 z\_1+y\_1 z\_2)^2+(x\_2 z\_1-x\_1 z\_2)^2+(-x\_2 y\_1+x\_1 y\_2)^2}
{\|\overrightarrow{v\_2}\|^2 \, \|\overrightarrow{v\_1}\|^2}
\\
&= \dfrac
{\|\overrightarrow{v\_1} \times \overrightarrow{v\_2} \|^2}
{\|\overrightarrow{v\_2}\|^2 \, \|\overrightarrow{v\_1}\|^2}
\end{align}
And we conclude, for purely formal reasons,
$\|\overrightarrow{v\_1} \times \overrightarrow{v\_2} \|
= \|\overrightarrow{v\_2}\| \, \|\overrightarrow{v\_1}\| \sin \theta$ | The real reason is because it is convention to use a right-handed coordinate system. If you switched to a left-handed coordinate system for some reason (I'm not sure why), then you would need to do your cross-products using a left-hand rule to get the same answers. That's really as simple as it gets. It's a result of our conventions in defining our coordinates the way we do. |
1,941,044 | >
> $\mathbf{a}\times \mathbf{b}$ follows the right hand rule? Why not left hand rule? Why is it $a b \sin (x)$ times the perpendicular vector? Why is $\sin (x)$ used with the vectors but $\cos(x)$ is a scalar product?
>
>
>
So why is cross product defined in the way that it is?
I am mainly interested in the right hand rule defintion too as it is out of reach? | 2016/09/25 | [
"https://math.stackexchange.com/questions/1941044",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/363952/"
]
| The cross product originally came from the *quaternions*, which extend the complex numbers with two other 'imaginary units' $j$ and $k$, that have noncommutative multiplication (i.e. you can have $uv \neq vu$), but satisfy the relations
$$ i^2 = j^2 = k^2 = ijk = -1 $$
AFAIK, this is the exact form that Hamilton originally conceived them. Presumably the choice that $ijk = -1$ is simply due to the convenience in writing this formula compactly, although it could have just as easily been an artifact of how he arrived at them.
Vector algebra comes from separating the quaternions into scalars (the real multiples of $1$) and vectors (the real linear combinations of $i$, $j$, and $k$). The cross product is literally just the vector component of the ordinary product of two vector quaternions. (the scalar component is the negative of the dot product)
The association of $i$, $j$, and $k$ to the unit vectors along the $x$, $y$, and $z$ axes is just lexicographic convenience; you're just associating them in alphabetic order. | This may be a bit too deep but let $V$ be a finite dimensional vector space with basis $v\_1,...,v\_n$. We say $(v\_1,...,v\_n)$ is an oriented basis for $V$. We can define an equivalence class on orientations of $V$ by $[v\_1,...,v\_n] \sim [b\_1,...,b\_n] \iff [v\_1,...,v\_n] = A[b\_1,...,b\_n]$ (where $A$ is the transition matrix) and $\textbf{det}(A)>0$. Therefore, orientations are broken up into two classes, positive and negative. If we let $\textbf{e}^1,...,\textbf{e}^n$ be the standard basis for $\mathbb{R}^n$ then if we wish to check that $[b\_1,...,b\_n] \sim [\textbf{e}^1,...,\textbf{e}^n]$ then we simply have to look at;
$$\textbf{det}\left(\begin{bmatrix} b\_1 & b\_2 & \cdots & b\_n \end{bmatrix}\right) >0$$
Since $A = [b\_i]$ is the change of basis matrix.
$$\\$$
Edit (1): Above gives a generalization of determining orientation. In your case you would have $E=[\textbf{e}^1,\textbf{e}^2, \textbf{e}^3]$ which gives positive orientation and the ''right hand rule'' should be thought of as a geometric property that one can check without knowing all the information I presented above.
Edit (2): In regards to your question about why $\sin \theta, \cos \theta$ are used in certain situations is also because of geometry. The area of a parallelogram is base $\times$ height $= |\vec{a} \times \vec{b}| \sin \theta$ where $\vec{a}, \vec{b}$ span the parallelogram. |
1,941,044 | >
> $\mathbf{a}\times \mathbf{b}$ follows the right hand rule? Why not left hand rule? Why is it $a b \sin (x)$ times the perpendicular vector? Why is $\sin (x)$ used with the vectors but $\cos(x)$ is a scalar product?
>
>
>
So why is cross product defined in the way that it is?
I am mainly interested in the right hand rule defintion too as it is out of reach? | 2016/09/25 | [
"https://math.stackexchange.com/questions/1941044",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/363952/"
]
| The cross product originally came from the *quaternions*, which extend the complex numbers with two other 'imaginary units' $j$ and $k$, that have noncommutative multiplication (i.e. you can have $uv \neq vu$), but satisfy the relations
$$ i^2 = j^2 = k^2 = ijk = -1 $$
AFAIK, this is the exact form that Hamilton originally conceived them. Presumably the choice that $ijk = -1$ is simply due to the convenience in writing this formula compactly, although it could have just as easily been an artifact of how he arrived at them.
Vector algebra comes from separating the quaternions into scalars (the real multiples of $1$) and vectors (the real linear combinations of $i$, $j$, and $k$). The cross product is literally just the vector component of the ordinary product of two vector quaternions. (the scalar component is the negative of the dot product)
The association of $i$, $j$, and $k$ to the unit vectors along the $x$, $y$, and $z$ axes is just lexicographic convenience; you're just associating them in alphabetic order. | the Gibbs Vector Algebra Cross Product Right Hand Rule is a Convention
Any description of the (nominally) Euclidean 3 dimensional world we perceive runs into Chirality, the distinction between Right and Left handedness, the difference in a Mirror Reflection.
<https://en.wikipedia.org/wiki/Chirality>
A Mathematical System describing this world has to have a Convention for coordinate order, orientation.
Justifications for the Right Hand Rule for the Vector Cross Product are a consequence of the choice of Chirality in the the "Standard Basis" and are circular, not deep - you just have to choose.
In fact the other choice has been used:
<http://web.stanford.edu/class/me331b/documents/VectorBasisIndependent.pdf>
>
> The right-hand rule is a recently accepted universal convention, much like driving
> on the right-hand side of the road in North America. Until 1965, the Soviet Union used
> the left-hand rule, logically reasoning that the left-hand rule is more convenient because
> a right-handed person can simultaneously write while performing cross products.
>
>
> |
1,941,044 | >
> $\mathbf{a}\times \mathbf{b}$ follows the right hand rule? Why not left hand rule? Why is it $a b \sin (x)$ times the perpendicular vector? Why is $\sin (x)$ used with the vectors but $\cos(x)$ is a scalar product?
>
>
>
So why is cross product defined in the way that it is?
I am mainly interested in the right hand rule defintion too as it is out of reach? | 2016/09/25 | [
"https://math.stackexchange.com/questions/1941044",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/363952/"
]
| I have answers for your question. If it was defined relative to the left-hand rule, you'd currently be asking why not the right-hand rule. It's how we deal with ambiguity: by establishing conventions. Depending on how you choose the definition of cross product, the result could be one of two different vectors. This led to the establishment of a convention. If there were no conventions with cross products, things would get very confusing because some people would be coming up with vectors in the opposite direction from other people, and their results would be different, which would lead to confusion. It's also likely that some theorems wouldn't work out because they're based on one definition and not the other, etc; one would keep having to convert between definitions all the time; and it would get very annoying.
The answer to your second questions? Upon establishing the definition of cross product, it just happened that the geometry worked out with sine and not cosine. It's just the behaviors of geometry in light of the constraints placed on it as a result having decided on a definition.
The same answer goes for the scalar product. Once the definition was made, that's how the geometry worked out.
However, it could be, though that the definitions were made so that they'd coincide with sin and cosine the way they did to unite a variety of approaches to the same set of problems, some people using trig, others using algebra to attack the same set of problems until some brilliant person united all the approaches with one definition. Such a thing often happens in mathematics, as anyone who's familiar with the concept of research might tell you.
Hope that helps. | The real reason is because it is convention to use a right-handed coordinate system. If you switched to a left-handed coordinate system for some reason (I'm not sure why), then you would need to do your cross-products using a left-hand rule to get the same answers. That's really as simple as it gets. It's a result of our conventions in defining our coordinates the way we do. |
1,941,044 | >
> $\mathbf{a}\times \mathbf{b}$ follows the right hand rule? Why not left hand rule? Why is it $a b \sin (x)$ times the perpendicular vector? Why is $\sin (x)$ used with the vectors but $\cos(x)$ is a scalar product?
>
>
>
So why is cross product defined in the way that it is?
I am mainly interested in the right hand rule defintion too as it is out of reach? | 2016/09/25 | [
"https://math.stackexchange.com/questions/1941044",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/363952/"
]
| The cross product doesn't actually follow any such rule. It is defined arithmetically as a determinant:
$$\mathbf{u\times v} = \begin{vmatrix}
\mathbf{i}&\mathbf{j}&\mathbf{k}\\
u\_1&u\_2&u\_3\\
v\_1&v\_2&v\_3\\
\end{vmatrix}$$
There is no hand rule there. The right hand rule comes from the conventions about how we visualize the result in 3-D vector space.
Firstly, the resulting scalar value is assigned as the length of a vector which is orthogonal to $\mathbf{u}$ and $\mathbf{v}$. That does not give us a right hand rule yet.
If we identify the first vector component with the $x$ axis, the second with the $y$ axis and the third with the $z$ axis, such that the positive ray of the $x$ axis shoots left, $y$ shoots upward, and $z$ points out of the page toward us, then we end up with the right hand rule.
Why? Because the cross product of a unit vector lying in the positive $x$ axis direction, with a unit vector similarly lying in positive $y$ produces a unit vector lying in positive $z$.
Based on how we laid out the axes, this gives us the right hand rule: if we extend our thumb in the direction of $z$, then the fingers curl from $x$ to $y$.
Your question is really about why we lay out the axes this way, and that is merely a convention, like driving on the right side of the road (in the majority of the world's countries, not all, obviously).
The important thing about conventions is only a) to have them and b) have them be consistent. The choice between two equivalent conventions, like whether to choose one system or its exact mirror image, is unimportant; there is no external reason to go one way or the other. | The real reason is because it is convention to use a right-handed coordinate system. If you switched to a left-handed coordinate system for some reason (I'm not sure why), then you would need to do your cross-products using a left-hand rule to get the same answers. That's really as simple as it gets. It's a result of our conventions in defining our coordinates the way we do. |
1,941,044 | >
> $\mathbf{a}\times \mathbf{b}$ follows the right hand rule? Why not left hand rule? Why is it $a b \sin (x)$ times the perpendicular vector? Why is $\sin (x)$ used with the vectors but $\cos(x)$ is a scalar product?
>
>
>
So why is cross product defined in the way that it is?
I am mainly interested in the right hand rule defintion too as it is out of reach? | 2016/09/25 | [
"https://math.stackexchange.com/questions/1941044",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/363952/"
]
| If the right hand rule seems too arbitrary to you, use a definition of the cross product that doesn't make use of it (explicitly). Here's one way to construct the cross product:
Recall that the (signed) volume of a [parallelepiped](https://en.wikipedia.org/wiki/Parallelepiped) in $\Bbb R^3$ with sides $a, b, c$ is given by
$$\textrm{Vol} = \det(a,b,c)$$
where $\det(a,b,c) := \begin{vmatrix}a\_1 & b\_1 & c\_1 \\ a\_2 & b\_2 & c\_2 \\ a\_3 & b\_3 & c\_3\end{vmatrix}$.
Now let's fix $b$ and $c$ and allow $a$ to vary. Then what is the volume in terms of $a = (a\_1, a\_2, a\_3)$? Let's see:
$$\begin{align}\textrm{Vol} = \begin{vmatrix}a\_1 & b\_1 & c\_1 \\ a\_2 & b\_2 & c\_2 \\ a\_3 & b\_3 & c\_3\end{vmatrix} &= a\_1\begin{vmatrix} b\_2 & c\_2 \\ b\_3 & c\_3\end{vmatrix} - a\_2\begin{vmatrix} b\_1 & c\_1 \\ b\_3 & c\_3\end{vmatrix} + a\_3\begin{vmatrix} b\_1 & c\_1 \\ b\_2 & c\_2\end{vmatrix} \\ &= a\_1(b\_2c\_3-b\_3c\_2)+a\_2(b\_3c\_1-b\_1c\_3)+a\_3(b\_1c\_2-b\_2c\_1) \\ &= (a\_1, a\_2, a\_3)\cdot (b\_2c\_3-b\_3c\_2,b\_3c\_1-b\_1c\_3,b\_1c\_2-b\_2c\_1)\end{align}$$
So apparently the volume of a parallelopiped will always be the vector $a$ dotted with this interesting vector $(b\_2c\_3-b\_3c\_2,b\_3c\_1-b\_1c\_3,b\_1c\_2-b\_2c\_1)$. We call that vector the cross product and denote it $b\times c$.
---
From the above construction we can define the cross product in either of two equivalent ways:
**Implicit Definition**
Let $b,c\in \Bbb R^3$. Then define the vector $d = b\times c$ by $$a\cdot d = \det(a,b,c),\qquad \forall a\in\Bbb R^3$$
**Explicit Definition**
Let $b=(b\_1,b\_2,b\_3)$, $c=(c\_1,c\_2,c\_3)$. Then define the vector $b\times c$ by $$b\times c = (b\_2c\_3-b\_3c\_2,b\_3c\_1-b\_1c\_3,b\_1c\_2-b\_2c\_1)$$
---
Now you're probably wondering where that arbitrary right-handedness went. Surely it must be hidden in there somewhere. It is. It's in the ordered basis I'm implicitly using to give the coordinates of each of my vectors. If you choose a right-handed coordinate system, then you'll get a right-handed cross product. If you choose a left-handed coordinate system, then you'll get a *left*-handed cross product. So this definition essentially shifts the choice of chirality onto the basis for the space. This is actually rather pleasing (at least to me).
---
The other properties of the cross product are readily verified from this definition. For instance, try checking that $b\times c$ is orthogonal to both $b$ and $c$. If you know the properties of determinants it should be immediately clear. Another property of the cross product, $\|b\times c\| = \|b\|\|c\|\sin(\theta)$, is easily determined by the geometry of our construction. Draw a picture and see if you can verify this one. | There's a whole algebra ("Geometric Algebra", or Clifford algebra) behind the concept of multiplying vectors. Look there to find out where the handedness comes from, why $ \cos \theta $ for $a \cdot b$ but $\sin \theta$ for $a \times b$, and many other gems. [Here](http://faculty.luther.edu/~macdonal/GA&GC.pdf)'s a great reference.
Essentially, the cross product is a vector that describes a plane. A plane is described by two vectors (in any number of dimensions), but in $\mathbb{R}^3$ we have the handy situation that a plane can also be described by a vector. So, in 3-d only, vector $c = a \times b$ describes the plane described by $a$ and $b$. Since a plane has two sides, there's a two-fold arbitrariness ("orientation") that the choice of sign handles.
The $\sin$ and $\cos$ bit is slightly more complicated, but not much. Check out the reference. |
1,941,044 | >
> $\mathbf{a}\times \mathbf{b}$ follows the right hand rule? Why not left hand rule? Why is it $a b \sin (x)$ times the perpendicular vector? Why is $\sin (x)$ used with the vectors but $\cos(x)$ is a scalar product?
>
>
>
So why is cross product defined in the way that it is?
I am mainly interested in the right hand rule defintion too as it is out of reach? | 2016/09/25 | [
"https://math.stackexchange.com/questions/1941044",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/363952/"
]
| the Gibbs Vector Algebra Cross Product Right Hand Rule is a Convention
Any description of the (nominally) Euclidean 3 dimensional world we perceive runs into Chirality, the distinction between Right and Left handedness, the difference in a Mirror Reflection.
<https://en.wikipedia.org/wiki/Chirality>
A Mathematical System describing this world has to have a Convention for coordinate order, orientation.
Justifications for the Right Hand Rule for the Vector Cross Product are a consequence of the choice of Chirality in the the "Standard Basis" and are circular, not deep - you just have to choose.
In fact the other choice has been used:
<http://web.stanford.edu/class/me331b/documents/VectorBasisIndependent.pdf>
>
> The right-hand rule is a recently accepted universal convention, much like driving
> on the right-hand side of the road in North America. Until 1965, the Soviet Union used
> the left-hand rule, logically reasoning that the left-hand rule is more convenient because
> a right-handed person can simultaneously write while performing cross products.
>
>
> | As a complement to Bye\_World's illuminating answer, which defines $b \times\ c$ as the vector whose dot product with $a$ equals $\det(a, b, c)$, $\|b\|\|c\|\sin(\theta)$ is the surface of the parallelogram formed by vectors $b$ and $c$. If $a$ is a unit vector orthogonal to the $b$-and-$c$ plane, then $\det(a, b, c)$, which is the (signed) volume of the parallelepiped formed by the 3 vectors, equals the surface of the $b$-and-$c$ parallelogram. In this case, i.e.$\|a\|=1$ and angle from $a$ to $b$ (and to $c$) equal to positive $\pi/2$, one can picture $b \times c$ as $a$ times the surface of the parallelogram. |
2,198,408 | This question was on a test in my cryptography class a couple weeks ago and I haven't been able to figure out a good proof. A hint was given with the question: all natural numbers have unique prime factors.
Here's an example showing it's true for $P = 11$
$a = 1, b = 1, ab \equiv 1 \pmod P$
$a = 2, b = 6, ab \equiv 1 \pmod P$
$a = 3, b = 4, ab \equiv 1 \pmod P$
$a = 5, b = 9, ab \equiv 1 \pmod P$
$a = 7, b = 8, ab \equiv 1 \pmod P$
$a = 10, b = 10, ab \equiv 1 \pmod P$
the other values of a $(4, 6, 8, 9)$ appear as $b$ values, but it still works.
Some things I figured out that I'm not sure if they matter.
If $a = P-1$, then $b = P-1$. $( (P-1)(P-1) \equiv 1 \pmod p )$ | 2017/03/22 | [
"https://math.stackexchange.com/questions/2198408",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/428264/"
]
| Let $S = \{1,2, \dots, p-1\}$ Fix $a \in S$ and consider the function $m\_a: S -> S$ which sends $k \mapsto k\cdot a \pmod p$
We claim that $m\_a$ is injective. Note that if $m\_a(k\_1)=m\_a(k\_2)$ we have $a\cdot k\_1 \equiv a \cdot k\_2 \pmod p $ so $a \cdot (k\_1 - k\_2) \equiv 0 \pmod p$ This means that the product $a \cdot (k\_1 - k\_2)$ is divisible by $p$. As $p$ is prime, $a$ is coprime to $p$, so it must be the case that $k\_1 - k\_2$ is divible by $p$, As $|k\_1 - k\_2| < p$ and $p$ is prime, this can only be the case if $k\_1 - k\_2 = 0$, thus $k\_1 = k\_2$. Now finally as $m\_a$ is an injective function from a finite set to itself, it must be the case that $m\_a$ is surjective, which implies that there is some $b \in S$ such that $a\cdot b \equiv 1 \pmod p$
Note that this proof can be simplified and generalized if you know some basic notions from ring theory: it amounts to the fact that a finite integral domain is a field. | Lets see that, take $a$ in $S $ then as $p $ is prime $(a,p)=1$. Then there exists integers $r,s $ such that $ar+ps=1$ this implies $ps=1-ar $ then $p| 1-ar $ and this is the definition of $1 \equiv ar \pmod p $ and then the b you are looking for is the r we used. This shows such b exists and tells how can you find it. Hope it helps. |
2,198,408 | This question was on a test in my cryptography class a couple weeks ago and I haven't been able to figure out a good proof. A hint was given with the question: all natural numbers have unique prime factors.
Here's an example showing it's true for $P = 11$
$a = 1, b = 1, ab \equiv 1 \pmod P$
$a = 2, b = 6, ab \equiv 1 \pmod P$
$a = 3, b = 4, ab \equiv 1 \pmod P$
$a = 5, b = 9, ab \equiv 1 \pmod P$
$a = 7, b = 8, ab \equiv 1 \pmod P$
$a = 10, b = 10, ab \equiv 1 \pmod P$
the other values of a $(4, 6, 8, 9)$ appear as $b$ values, but it still works.
Some things I figured out that I'm not sure if they matter.
If $a = P-1$, then $b = P-1$. $( (P-1)(P-1) \equiv 1 \pmod p )$ | 2017/03/22 | [
"https://math.stackexchange.com/questions/2198408",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/428264/"
]
| It's easy to check that the values of $f(x)=ax$ are distinct for $x \in \{0,...,p-1\}$
So there is a unique $b$ with the property $f(b)=1$. | Lets see that, take $a$ in $S $ then as $p $ is prime $(a,p)=1$. Then there exists integers $r,s $ such that $ar+ps=1$ this implies $ps=1-ar $ then $p| 1-ar $ and this is the definition of $1 \equiv ar \pmod p $ and then the b you are looking for is the r we used. This shows such b exists and tells how can you find it. Hope it helps. |
37,623,430 | I managed to configure and schedule a Quartz job using JobStoreTX persistent store in Spring Boot ( version 4.2.5 ). Here is how I schedule the job.
First :
```
public class MyJob implements Job{
@Autowired
IService service;
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
service.doSomething();
}
}
```
`@Autowired` seems like it wont work in a Quartz job implementation because it wont be instantiated by Spring. Hence, im facing the famous JavaNullPointerException.
Second, in order to get hold of Spring-managed beans in a Quartz job, I used `org.springframework.scheduling.quartz.SchedulerFactoryBean` to manage the Quartz lifecycle :
```
public class MyJob implements Job{
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
try {
ApplicationContext applicationContext = (ApplicationContext) context.getScheduler().getContext().get("applicationContext");
IService service= applicationContext.getBean(IService.class);
service.getManualMaxConfig();
} catch (SchedulerException e) {
e.printStackTrace();
}
}
}
```
And then :
```
<bean id="scheduler"
class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="applicationContextSchedulerContextKey" value="applicationContext" />
</bean>
```
The sad news is that im also facing JavaNPE.
I also try these suggestions, in vain ..
[LINK](https://stackoverflow.com/questions/6990767/inject-bean-reference-into-a-quartz-job-in-spring)
Whats wrong with what im doing?
**Update 1 :**
Before trying to inject service, i tried to pass some Params as @ritesh.garg suggests.
```
public class MyJob implements Job{
private String someParam;
private int someParam2;
public void setSomeParam(String someParam) {
this.someParam = someParam;
}
public void setSomeParam2(int someParam2) {
this.someParam2 = someParam2;
}
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
System.out.println("My job is running with "+someParam+' '+someParam2);
}
}
```
And my jobBean.xml looks like :
```
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="scheduler"
class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="applicationContextSchedulerContextKey" value="applicationContext" />
</bean>
<bean id="myJob" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
<property name="jobClass" value="com.quartz.service.MyJob"/>
<property name="jobDataAsMap">
<map>
<entry key="someParam" value="some value"/>
<entry key="someParam2" value="1"/>
</map>
</property>
</bean>
</beans>
```
I dont know why, but the parameters arent passed and it prints :
`My job is running with null 0`
Ps : I imported the jobBean.xml into Application.java . So i dont know what am i missing ?
**Update 2 :** Here is my detailed code :
```
@Component
public class JobScheduler{
Timer timer = new Timer();
@PostConstruct
public void distributeAutomaticConf(){
try {
timer.schedule(new ServiceImpl(), 10000);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
```
Service Impl :
```
@Transactional
@Component
public class ServiceImpl extends TimerTask implements IService{
@Override
public void run() {
final SchedulerFactory factory = new StdSchedulerFactory();
Scheduler scheduler = null;
try {
scheduler = factory.getScheduler();
final JobDetailImpl jobDetail = new JobDetailImpl();
jobDetail.setName("My job executed only once.. ");
jobDetail.setJobClass(MyJob.class);
SimpleTrigger trigger = (SimpleTrigger) newTrigger()
.withIdentity("trigger_", "group_")
.build();
scheduler.start();
scheduler.scheduleJob(jobDetail, trigger);
System.in.read();
if (scheduler != null) {
scheduler.shutdown();
}
} catch (final SchedulerException e) {
e.printStackTrace();
} catch (final IOException e) {
e.printStackTrace();
}
}
}
```
MyJob :
```
public class MyJob extends QuartzJobBean{
@Autowired
IService service;
@Override
protected void executeInternal(JobExecutionContext arg0) throws JobExecutionException { SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
service.doSomething();
}
}
```
jobBean.xml :
```
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="scheduler"
class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="applicationContextSchedulerContextKey" value="applicationContext" />
</bean>
<bean id="myJob" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
<property name="jobClass" value="com.quartz.service.MyJob"/>
<property name="jobDataAsMap">
<map>
<entry key="someParam" value="some value"/>
<entry key="someParam2" value="1"/>
</map>
</property>
</bean>
</beans>
```
quartz.properties :
```
org.quartz.scheduler.instanceName = DefaultQuartzScheduler
org.quartz.scheduler.rmi.export = false
org.quartz.scheduler.rmi.proxy = false
org.quartz.scheduler.wrapJobExecutionInUserTransaction = false
org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount = 10
org.quartz.threadPool.threadPriority = 5
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread = true
org.quartz.jobStore.misfireThreshold = 60000
org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX
org.quartz.jobStore.driverDelegateClass=org.quartz.impl.jdbcjobstore.PostgreSQLDelegate
#org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate
org.quartz.jobStore.dataSource = myDS
org.quartz.jobStore.tablePrefix = QRTZ_
org.quartz.dataSource.myDS.driver = org.postgresql.Driver
org.quartz.dataSource.myDS.URL = jdbc:postgresql://localhost:5432/myDB
org.quartz.dataSource.myDS.user = admin
org.quartz.dataSource.myDS.password = admin
org.quartz.dataSource.myDS.maxConnections = 10
org.quartz.scheduler.skipUpdateCheck=true
```
console :
```
java.lang.NullPointerException: null
at com.quartz.service.MyJob.executeInternal(MyJob.java:27) ~[classes/:na]
at org.springframework.scheduling.quartz.QuartzJobBean.execute(QuartzJobBean.java:113) ~[spring-context-support-3.1.2.RELEASE.jar:3.1.2.RELEASE]
at org.quartz.core.JobRunShell.run(JobRunShell.java:202) ~[quartz-2.2.1.jar:na]
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:573) [quartz-2.2.1.jar:na]
2016-06-05 11:35:16.839 ERROR 25452 --- [eduler_Worker-1] org.quartz.core.ErrorLogger : Job (DEFAULT.My job executed only once.. threw an exception.
org.quartz.SchedulerException: Job threw an unhandled exception.
at org.quartz.core.JobRunShell.run(JobRunShell.java:213) ~[quartz-2.2.1.jar:na]
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:573) [quartz-2.2.1.jar:na]
Caused by: java.lang.NullPointerException: null
at com.quartz.service.MyJob.executeInternal(MyJob.java:27) ~[classes/:na]
at org.springframework.scheduling.quartz.QuartzJobBean.execute(QuartzJobBean.java:113) ~[spring-context-support-3.1.2.RELEASE.jar:3.1.2.RELEASE]
at org.quartz.core.JobRunShell.run(JobRunShell.java:202) ~[quartz-2.2.1.jar:na]
... 1 common frames omitted
``` | 2016/06/03 | [
"https://Stackoverflow.com/questions/37623430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5227664/"
]
| I have experienced the same problem in past. My understanding on this issue is that beans instantiated in spring context cannot be injected in quartz context simply by using `@Autowired` annotation.
I managed to solve it by using setter based dependency injection. But the same is mentioned in the "LINK" you have added in the original post.
Pasting the relevant information from the link:
**Update:** Replaced `implements Job` with `extends QuartzJobBean`
```
public class MyJob extends QuartzJobBean {
private String someParam;
private int someParam2;
public void setSomeParam(String someParam) {
this.someParam = someParam;
}
public void setSomeParam2(String someParam2) {
this.someParam2 = someParam2;
}
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
System.out.println("My job is running with "+someParam+' '+someParam2);
}
}
```
Here, someParam and someParam2 are being injected via setter dependency injection. Now the other part that makes this complete is to pass someParam and someParam2 in `jobDataAsMap`
```
<bean id="myJob" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
<property name="jobClass" value="com.my.MyJob"/>
<property name="jobDataAsMap">
<map>
<entry key="someParam" value="some value"/>
<entry key="someParam2" value="1"/>
</map>
</property>
</bean>
```
In your case, it would be a value-ref="IserviceBeanId", instead of 'value' in entry. I would be surprised as well as curious, if this did not/does not work for you. | We can use JobDataMap to pass the objects.
example: here restTemplate is Autowired.
```
JobDataMap newJobDataMap = new JobDataMap();
newJobDataMap.put("restTemplate", restTemplate);
JobDetail someJobDetail = JobBuilder
.newJob(QuartzJob.class)
.withIdentity(jobName, GROUP)
.usingJobData(newJobDataMap)
.build();
``` |
37,623,430 | I managed to configure and schedule a Quartz job using JobStoreTX persistent store in Spring Boot ( version 4.2.5 ). Here is how I schedule the job.
First :
```
public class MyJob implements Job{
@Autowired
IService service;
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
service.doSomething();
}
}
```
`@Autowired` seems like it wont work in a Quartz job implementation because it wont be instantiated by Spring. Hence, im facing the famous JavaNullPointerException.
Second, in order to get hold of Spring-managed beans in a Quartz job, I used `org.springframework.scheduling.quartz.SchedulerFactoryBean` to manage the Quartz lifecycle :
```
public class MyJob implements Job{
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
try {
ApplicationContext applicationContext = (ApplicationContext) context.getScheduler().getContext().get("applicationContext");
IService service= applicationContext.getBean(IService.class);
service.getManualMaxConfig();
} catch (SchedulerException e) {
e.printStackTrace();
}
}
}
```
And then :
```
<bean id="scheduler"
class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="applicationContextSchedulerContextKey" value="applicationContext" />
</bean>
```
The sad news is that im also facing JavaNPE.
I also try these suggestions, in vain ..
[LINK](https://stackoverflow.com/questions/6990767/inject-bean-reference-into-a-quartz-job-in-spring)
Whats wrong with what im doing?
**Update 1 :**
Before trying to inject service, i tried to pass some Params as @ritesh.garg suggests.
```
public class MyJob implements Job{
private String someParam;
private int someParam2;
public void setSomeParam(String someParam) {
this.someParam = someParam;
}
public void setSomeParam2(int someParam2) {
this.someParam2 = someParam2;
}
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
System.out.println("My job is running with "+someParam+' '+someParam2);
}
}
```
And my jobBean.xml looks like :
```
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="scheduler"
class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="applicationContextSchedulerContextKey" value="applicationContext" />
</bean>
<bean id="myJob" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
<property name="jobClass" value="com.quartz.service.MyJob"/>
<property name="jobDataAsMap">
<map>
<entry key="someParam" value="some value"/>
<entry key="someParam2" value="1"/>
</map>
</property>
</bean>
</beans>
```
I dont know why, but the parameters arent passed and it prints :
`My job is running with null 0`
Ps : I imported the jobBean.xml into Application.java . So i dont know what am i missing ?
**Update 2 :** Here is my detailed code :
```
@Component
public class JobScheduler{
Timer timer = new Timer();
@PostConstruct
public void distributeAutomaticConf(){
try {
timer.schedule(new ServiceImpl(), 10000);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
```
Service Impl :
```
@Transactional
@Component
public class ServiceImpl extends TimerTask implements IService{
@Override
public void run() {
final SchedulerFactory factory = new StdSchedulerFactory();
Scheduler scheduler = null;
try {
scheduler = factory.getScheduler();
final JobDetailImpl jobDetail = new JobDetailImpl();
jobDetail.setName("My job executed only once.. ");
jobDetail.setJobClass(MyJob.class);
SimpleTrigger trigger = (SimpleTrigger) newTrigger()
.withIdentity("trigger_", "group_")
.build();
scheduler.start();
scheduler.scheduleJob(jobDetail, trigger);
System.in.read();
if (scheduler != null) {
scheduler.shutdown();
}
} catch (final SchedulerException e) {
e.printStackTrace();
} catch (final IOException e) {
e.printStackTrace();
}
}
}
```
MyJob :
```
public class MyJob extends QuartzJobBean{
@Autowired
IService service;
@Override
protected void executeInternal(JobExecutionContext arg0) throws JobExecutionException { SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
service.doSomething();
}
}
```
jobBean.xml :
```
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="scheduler"
class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="applicationContextSchedulerContextKey" value="applicationContext" />
</bean>
<bean id="myJob" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
<property name="jobClass" value="com.quartz.service.MyJob"/>
<property name="jobDataAsMap">
<map>
<entry key="someParam" value="some value"/>
<entry key="someParam2" value="1"/>
</map>
</property>
</bean>
</beans>
```
quartz.properties :
```
org.quartz.scheduler.instanceName = DefaultQuartzScheduler
org.quartz.scheduler.rmi.export = false
org.quartz.scheduler.rmi.proxy = false
org.quartz.scheduler.wrapJobExecutionInUserTransaction = false
org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount = 10
org.quartz.threadPool.threadPriority = 5
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread = true
org.quartz.jobStore.misfireThreshold = 60000
org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX
org.quartz.jobStore.driverDelegateClass=org.quartz.impl.jdbcjobstore.PostgreSQLDelegate
#org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate
org.quartz.jobStore.dataSource = myDS
org.quartz.jobStore.tablePrefix = QRTZ_
org.quartz.dataSource.myDS.driver = org.postgresql.Driver
org.quartz.dataSource.myDS.URL = jdbc:postgresql://localhost:5432/myDB
org.quartz.dataSource.myDS.user = admin
org.quartz.dataSource.myDS.password = admin
org.quartz.dataSource.myDS.maxConnections = 10
org.quartz.scheduler.skipUpdateCheck=true
```
console :
```
java.lang.NullPointerException: null
at com.quartz.service.MyJob.executeInternal(MyJob.java:27) ~[classes/:na]
at org.springframework.scheduling.quartz.QuartzJobBean.execute(QuartzJobBean.java:113) ~[spring-context-support-3.1.2.RELEASE.jar:3.1.2.RELEASE]
at org.quartz.core.JobRunShell.run(JobRunShell.java:202) ~[quartz-2.2.1.jar:na]
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:573) [quartz-2.2.1.jar:na]
2016-06-05 11:35:16.839 ERROR 25452 --- [eduler_Worker-1] org.quartz.core.ErrorLogger : Job (DEFAULT.My job executed only once.. threw an exception.
org.quartz.SchedulerException: Job threw an unhandled exception.
at org.quartz.core.JobRunShell.run(JobRunShell.java:213) ~[quartz-2.2.1.jar:na]
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:573) [quartz-2.2.1.jar:na]
Caused by: java.lang.NullPointerException: null
at com.quartz.service.MyJob.executeInternal(MyJob.java:27) ~[classes/:na]
at org.springframework.scheduling.quartz.QuartzJobBean.execute(QuartzJobBean.java:113) ~[spring-context-support-3.1.2.RELEASE.jar:3.1.2.RELEASE]
at org.quartz.core.JobRunShell.run(JobRunShell.java:202) ~[quartz-2.2.1.jar:na]
... 1 common frames omitted
``` | 2016/06/03 | [
"https://Stackoverflow.com/questions/37623430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5227664/"
]
| I fix my problem implementing "InitializingBean" in my job;
```
public class MyJob extends QuartzJobBean implements InitializingBean {
private String someParam;
private int someParam2;
public void setSomeParam(String someParam) {
this.someParam = someParam;
}
public void setSomeParam2(String someParam2) {
this.someParam2 = someParam2;
}
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
System.out.println("My job is running with "+someParam+' '+someParam2);
}
@Override
public void afterPropertiesSet() throws Exception {
}
}
``` | We can use JobDataMap to pass the objects.
example: here restTemplate is Autowired.
```
JobDataMap newJobDataMap = new JobDataMap();
newJobDataMap.put("restTemplate", restTemplate);
JobDetail someJobDetail = JobBuilder
.newJob(QuartzJob.class)
.withIdentity(jobName, GROUP)
.usingJobData(newJobDataMap)
.build();
``` |
37,623,430 | I managed to configure and schedule a Quartz job using JobStoreTX persistent store in Spring Boot ( version 4.2.5 ). Here is how I schedule the job.
First :
```
public class MyJob implements Job{
@Autowired
IService service;
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
service.doSomething();
}
}
```
`@Autowired` seems like it wont work in a Quartz job implementation because it wont be instantiated by Spring. Hence, im facing the famous JavaNullPointerException.
Second, in order to get hold of Spring-managed beans in a Quartz job, I used `org.springframework.scheduling.quartz.SchedulerFactoryBean` to manage the Quartz lifecycle :
```
public class MyJob implements Job{
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
try {
ApplicationContext applicationContext = (ApplicationContext) context.getScheduler().getContext().get("applicationContext");
IService service= applicationContext.getBean(IService.class);
service.getManualMaxConfig();
} catch (SchedulerException e) {
e.printStackTrace();
}
}
}
```
And then :
```
<bean id="scheduler"
class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="applicationContextSchedulerContextKey" value="applicationContext" />
</bean>
```
The sad news is that im also facing JavaNPE.
I also try these suggestions, in vain ..
[LINK](https://stackoverflow.com/questions/6990767/inject-bean-reference-into-a-quartz-job-in-spring)
Whats wrong with what im doing?
**Update 1 :**
Before trying to inject service, i tried to pass some Params as @ritesh.garg suggests.
```
public class MyJob implements Job{
private String someParam;
private int someParam2;
public void setSomeParam(String someParam) {
this.someParam = someParam;
}
public void setSomeParam2(int someParam2) {
this.someParam2 = someParam2;
}
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
System.out.println("My job is running with "+someParam+' '+someParam2);
}
}
```
And my jobBean.xml looks like :
```
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="scheduler"
class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="applicationContextSchedulerContextKey" value="applicationContext" />
</bean>
<bean id="myJob" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
<property name="jobClass" value="com.quartz.service.MyJob"/>
<property name="jobDataAsMap">
<map>
<entry key="someParam" value="some value"/>
<entry key="someParam2" value="1"/>
</map>
</property>
</bean>
</beans>
```
I dont know why, but the parameters arent passed and it prints :
`My job is running with null 0`
Ps : I imported the jobBean.xml into Application.java . So i dont know what am i missing ?
**Update 2 :** Here is my detailed code :
```
@Component
public class JobScheduler{
Timer timer = new Timer();
@PostConstruct
public void distributeAutomaticConf(){
try {
timer.schedule(new ServiceImpl(), 10000);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
```
Service Impl :
```
@Transactional
@Component
public class ServiceImpl extends TimerTask implements IService{
@Override
public void run() {
final SchedulerFactory factory = new StdSchedulerFactory();
Scheduler scheduler = null;
try {
scheduler = factory.getScheduler();
final JobDetailImpl jobDetail = new JobDetailImpl();
jobDetail.setName("My job executed only once.. ");
jobDetail.setJobClass(MyJob.class);
SimpleTrigger trigger = (SimpleTrigger) newTrigger()
.withIdentity("trigger_", "group_")
.build();
scheduler.start();
scheduler.scheduleJob(jobDetail, trigger);
System.in.read();
if (scheduler != null) {
scheduler.shutdown();
}
} catch (final SchedulerException e) {
e.printStackTrace();
} catch (final IOException e) {
e.printStackTrace();
}
}
}
```
MyJob :
```
public class MyJob extends QuartzJobBean{
@Autowired
IService service;
@Override
protected void executeInternal(JobExecutionContext arg0) throws JobExecutionException { SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
service.doSomething();
}
}
```
jobBean.xml :
```
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="scheduler"
class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="applicationContextSchedulerContextKey" value="applicationContext" />
</bean>
<bean id="myJob" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
<property name="jobClass" value="com.quartz.service.MyJob"/>
<property name="jobDataAsMap">
<map>
<entry key="someParam" value="some value"/>
<entry key="someParam2" value="1"/>
</map>
</property>
</bean>
</beans>
```
quartz.properties :
```
org.quartz.scheduler.instanceName = DefaultQuartzScheduler
org.quartz.scheduler.rmi.export = false
org.quartz.scheduler.rmi.proxy = false
org.quartz.scheduler.wrapJobExecutionInUserTransaction = false
org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount = 10
org.quartz.threadPool.threadPriority = 5
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread = true
org.quartz.jobStore.misfireThreshold = 60000
org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX
org.quartz.jobStore.driverDelegateClass=org.quartz.impl.jdbcjobstore.PostgreSQLDelegate
#org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate
org.quartz.jobStore.dataSource = myDS
org.quartz.jobStore.tablePrefix = QRTZ_
org.quartz.dataSource.myDS.driver = org.postgresql.Driver
org.quartz.dataSource.myDS.URL = jdbc:postgresql://localhost:5432/myDB
org.quartz.dataSource.myDS.user = admin
org.quartz.dataSource.myDS.password = admin
org.quartz.dataSource.myDS.maxConnections = 10
org.quartz.scheduler.skipUpdateCheck=true
```
console :
```
java.lang.NullPointerException: null
at com.quartz.service.MyJob.executeInternal(MyJob.java:27) ~[classes/:na]
at org.springframework.scheduling.quartz.QuartzJobBean.execute(QuartzJobBean.java:113) ~[spring-context-support-3.1.2.RELEASE.jar:3.1.2.RELEASE]
at org.quartz.core.JobRunShell.run(JobRunShell.java:202) ~[quartz-2.2.1.jar:na]
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:573) [quartz-2.2.1.jar:na]
2016-06-05 11:35:16.839 ERROR 25452 --- [eduler_Worker-1] org.quartz.core.ErrorLogger : Job (DEFAULT.My job executed only once.. threw an exception.
org.quartz.SchedulerException: Job threw an unhandled exception.
at org.quartz.core.JobRunShell.run(JobRunShell.java:213) ~[quartz-2.2.1.jar:na]
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:573) [quartz-2.2.1.jar:na]
Caused by: java.lang.NullPointerException: null
at com.quartz.service.MyJob.executeInternal(MyJob.java:27) ~[classes/:na]
at org.springframework.scheduling.quartz.QuartzJobBean.execute(QuartzJobBean.java:113) ~[spring-context-support-3.1.2.RELEASE.jar:3.1.2.RELEASE]
at org.quartz.core.JobRunShell.run(JobRunShell.java:202) ~[quartz-2.2.1.jar:na]
... 1 common frames omitted
``` | 2016/06/03 | [
"https://Stackoverflow.com/questions/37623430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5227664/"
]
| The correct way from the most of the examples I've seen is to make your Job interface implementation a @Component
```
@Component
public class MyJob implements Job{
@Autowired IService service;
@Override
public void execute(JobExecutionContext context) throws JobExecutionException{
service.doSomething();
}
}
``` | We can use JobDataMap to pass the objects.
example: here restTemplate is Autowired.
```
JobDataMap newJobDataMap = new JobDataMap();
newJobDataMap.put("restTemplate", restTemplate);
JobDetail someJobDetail = JobBuilder
.newJob(QuartzJob.class)
.withIdentity(jobName, GROUP)
.usingJobData(newJobDataMap)
.build();
``` |
949,361 | I have a Cocoa app with an `NSTextView` control which holds its text in an `NSAttributedString` (actually I believe it's a `NSMutableAttributedString`). I can easily set and modify different text attributes (such as font, underline, etc.) on different character ranges inside that string.
However, I want to set a part of the text as **hidden** (similar to the effect of the CSS attribute `display: none`). When an external event occurs (say a button clicked), I want to unhide or hide that specific range of characters.
Is there anyway to do this with `NSAttributedString`? | 2009/06/04 | [
"https://Stackoverflow.com/questions/949361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/884/"
]
| The supported attributes for NSAttributedString are listed in AppKit's NSAttributedString.h header. There's no key like 'hidden' or 'visible'. The attributes (styles) are not derived from html and cannot express all css features.
Nevertheless, to hide a range of characters you can set the foreground color to transparent:
```
NSMutableAttributedString* myString;
[myString addAttribute:NSForegroundColorAttributeName
value:[NSColor clearColor]
range:NSMakeRange(0, 10)];
``` | As far as I know there are no invisible type attributes for NSAttributedString, however you could create a subclass of NSAttributedString (or the Mutable version, but that might not be necessary) that overrides the drawInRect: to avoid drawing the portion of the text that has your attribute.
But this could be a little messy. |
949,361 | I have a Cocoa app with an `NSTextView` control which holds its text in an `NSAttributedString` (actually I believe it's a `NSMutableAttributedString`). I can easily set and modify different text attributes (such as font, underline, etc.) on different character ranges inside that string.
However, I want to set a part of the text as **hidden** (similar to the effect of the CSS attribute `display: none`). When an external event occurs (say a button clicked), I want to unhide or hide that specific range of characters.
Is there anyway to do this with `NSAttributedString`? | 2009/06/04 | [
"https://Stackoverflow.com/questions/949361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/884/"
]
| Another possibility would be to use a custom attribute on the text you want to hide, and then write your own method in a category on `NSAttributedString` that creates a new attributed string that excludes the text marked as hidden.
```
- (NSAttributedString *)attributedStringWithoutHiddenText {
NSMutableAttributedString *result = [[[NSMutableString alloc] init] autorelease];
NSRange fullRange = NSMakeRange(0, [self length]);
NSRange range = NSZeroRange;
while (NSMaxRange(range) < [self length]) {
NSDictionary *attributes = [self attributesAtIndex:range.location longestEffectiveRange:&range inRange:fullRange];
if ([[attributes objectForKey:MyHiddenTextAttribute] boolValue])
continue;
NSAttributedString *substring = [[NSAttributedString alloc] initWithString:[[self string] substringWithRange:range] attributes:attributes];
[result appendAttributedString:substring];
[substring release];
}
return result;
}
```
Caveat: I totally just wrote this off the top of my head, and it's not guaranteed to compile, work, light your hard drive on fire, not kick your dog, etc.
This would generate a string that's appropriate for drawing, but you would still need the original string for accessing any of the hidden text. Depending on the size of your strings, this could be a big memory overhead. | As far as I know there are no invisible type attributes for NSAttributedString, however you could create a subclass of NSAttributedString (or the Mutable version, but that might not be necessary) that overrides the drawInRect: to avoid drawing the portion of the text that has your attribute.
But this could be a little messy. |
949,361 | I have a Cocoa app with an `NSTextView` control which holds its text in an `NSAttributedString` (actually I believe it's a `NSMutableAttributedString`). I can easily set and modify different text attributes (such as font, underline, etc.) on different character ranges inside that string.
However, I want to set a part of the text as **hidden** (similar to the effect of the CSS attribute `display: none`). When an external event occurs (say a button clicked), I want to unhide or hide that specific range of characters.
Is there anyway to do this with `NSAttributedString`? | 2009/06/04 | [
"https://Stackoverflow.com/questions/949361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/884/"
]
| A simple option is to set the font size of the hidden text to 0 | As far as I know there are no invisible type attributes for NSAttributedString, however you could create a subclass of NSAttributedString (or the Mutable version, but that might not be necessary) that overrides the drawInRect: to avoid drawing the portion of the text that has your attribute.
But this could be a little messy. |
949,361 | I have a Cocoa app with an `NSTextView` control which holds its text in an `NSAttributedString` (actually I believe it's a `NSMutableAttributedString`). I can easily set and modify different text attributes (such as font, underline, etc.) on different character ranges inside that string.
However, I want to set a part of the text as **hidden** (similar to the effect of the CSS attribute `display: none`). When an external event occurs (say a button clicked), I want to unhide or hide that specific range of characters.
Is there anyway to do this with `NSAttributedString`? | 2009/06/04 | [
"https://Stackoverflow.com/questions/949361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/884/"
]
| The supported attributes for NSAttributedString are listed in AppKit's NSAttributedString.h header. There's no key like 'hidden' or 'visible'. The attributes (styles) are not derived from html and cannot express all css features.
Nevertheless, to hide a range of characters you can set the foreground color to transparent:
```
NSMutableAttributedString* myString;
[myString addAttribute:NSForegroundColorAttributeName
value:[NSColor clearColor]
range:NSMakeRange(0, 10)];
``` | I realize this is a very old thread, but the other other option is to do custom glyph rendering. There was a session about advanced text handling techniques at WWDC 2010 that covered code folding. This uses a similar technique to what you'll need to do with this and that is to examine the text as its being lain out and render the null glyph for your hidden text rather than the actual string. The session is Session 114 - Advanced Cocoa Text Tips and Tricks from WWDC 2010 videos. If you're a Mac Developer Program member, you can download these through the developer portal. |
949,361 | I have a Cocoa app with an `NSTextView` control which holds its text in an `NSAttributedString` (actually I believe it's a `NSMutableAttributedString`). I can easily set and modify different text attributes (such as font, underline, etc.) on different character ranges inside that string.
However, I want to set a part of the text as **hidden** (similar to the effect of the CSS attribute `display: none`). When an external event occurs (say a button clicked), I want to unhide or hide that specific range of characters.
Is there anyway to do this with `NSAttributedString`? | 2009/06/04 | [
"https://Stackoverflow.com/questions/949361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/884/"
]
| Another possibility would be to use a custom attribute on the text you want to hide, and then write your own method in a category on `NSAttributedString` that creates a new attributed string that excludes the text marked as hidden.
```
- (NSAttributedString *)attributedStringWithoutHiddenText {
NSMutableAttributedString *result = [[[NSMutableString alloc] init] autorelease];
NSRange fullRange = NSMakeRange(0, [self length]);
NSRange range = NSZeroRange;
while (NSMaxRange(range) < [self length]) {
NSDictionary *attributes = [self attributesAtIndex:range.location longestEffectiveRange:&range inRange:fullRange];
if ([[attributes objectForKey:MyHiddenTextAttribute] boolValue])
continue;
NSAttributedString *substring = [[NSAttributedString alloc] initWithString:[[self string] substringWithRange:range] attributes:attributes];
[result appendAttributedString:substring];
[substring release];
}
return result;
}
```
Caveat: I totally just wrote this off the top of my head, and it's not guaranteed to compile, work, light your hard drive on fire, not kick your dog, etc.
This would generate a string that's appropriate for drawing, but you would still need the original string for accessing any of the hidden text. Depending on the size of your strings, this could be a big memory overhead. | I realize this is a very old thread, but the other other option is to do custom glyph rendering. There was a session about advanced text handling techniques at WWDC 2010 that covered code folding. This uses a similar technique to what you'll need to do with this and that is to examine the text as its being lain out and render the null glyph for your hidden text rather than the actual string. The session is Session 114 - Advanced Cocoa Text Tips and Tricks from WWDC 2010 videos. If you're a Mac Developer Program member, you can download these through the developer portal. |
949,361 | I have a Cocoa app with an `NSTextView` control which holds its text in an `NSAttributedString` (actually I believe it's a `NSMutableAttributedString`). I can easily set and modify different text attributes (such as font, underline, etc.) on different character ranges inside that string.
However, I want to set a part of the text as **hidden** (similar to the effect of the CSS attribute `display: none`). When an external event occurs (say a button clicked), I want to unhide or hide that specific range of characters.
Is there anyway to do this with `NSAttributedString`? | 2009/06/04 | [
"https://Stackoverflow.com/questions/949361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/884/"
]
| A simple option is to set the font size of the hidden text to 0 | I realize this is a very old thread, but the other other option is to do custom glyph rendering. There was a session about advanced text handling techniques at WWDC 2010 that covered code folding. This uses a similar technique to what you'll need to do with this and that is to examine the text as its being lain out and render the null glyph for your hidden text rather than the actual string. The session is Session 114 - Advanced Cocoa Text Tips and Tricks from WWDC 2010 videos. If you're a Mac Developer Program member, you can download these through the developer portal. |
7,109,180 | I have been using java mail to automate Gmail operations.
One of the operation is to delete mail and I use following for it -
```
message.setFlag(Flags.Flag.DELETED, true);
```
but doing so only pushes my mails to spam folder.
I am wondering if there is a straight way to delete mail permanently instead of deleting mail from "inbox" first and then searching mails in "spam " folder and deleting them. | 2011/08/18 | [
"https://Stackoverflow.com/questions/7109180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/270835/"
]
| According to <http://mail.google.com/support/bin/answer.py?answer=78755>:
>
> If you want to delete a message from all folders, move it to the [Gmail]/Trash folder.
>
>
> If you delete a message from [Gmail]/Spam or [Gmail]/Trash, it will be deleted permanently.
>
>
>
However, that page doesn't give any indication that your approach would move mail to the spam folder; and it implies that you *should* see a folder named `[Gmail]/Spam`; so maybe it doesn't apply to your situation, somehow? I think you'll just have to try its approach, and see whether it works for you! | You told that you are trying
```
message.setFlag(Flags.Flag.DELETED, true);
```
did you tried
`folder.close(true);`
this will expunge all messages with DELETED flags. |
7,109,180 | I have been using java mail to automate Gmail operations.
One of the operation is to delete mail and I use following for it -
```
message.setFlag(Flags.Flag.DELETED, true);
```
but doing so only pushes my mails to spam folder.
I am wondering if there is a straight way to delete mail permanently instead of deleting mail from "inbox" first and then searching mails in "spam " folder and deleting them. | 2011/08/18 | [
"https://Stackoverflow.com/questions/7109180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/270835/"
]
| According to <http://mail.google.com/support/bin/answer.py?answer=78755>:
>
> If you want to delete a message from all folders, move it to the [Gmail]/Trash folder.
>
>
> If you delete a message from [Gmail]/Spam or [Gmail]/Trash, it will be deleted permanently.
>
>
>
However, that page doesn't give any indication that your approach would move mail to the spam folder; and it implies that you *should* see a folder named `[Gmail]/Spam`; so maybe it doesn't apply to your situation, somehow? I think you'll just have to try its approach, and see whether it works for you! | Setting the flag to Flags.Flag.DELETED only marks the email as deleted.
You need to call
folder.expunge();
to actually expunge those emails marked as deleted. |
7,109,180 | I have been using java mail to automate Gmail operations.
One of the operation is to delete mail and I use following for it -
```
message.setFlag(Flags.Flag.DELETED, true);
```
but doing so only pushes my mails to spam folder.
I am wondering if there is a straight way to delete mail permanently instead of deleting mail from "inbox" first and then searching mails in "spam " folder and deleting them. | 2011/08/18 | [
"https://Stackoverflow.com/questions/7109180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/270835/"
]
| You told that you are trying
```
message.setFlag(Flags.Flag.DELETED, true);
```
did you tried
`folder.close(true);`
this will expunge all messages with DELETED flags. | Setting the flag to Flags.Flag.DELETED only marks the email as deleted.
You need to call
folder.expunge();
to actually expunge those emails marked as deleted. |
74,128,913 | ```
function isPrime(num) {
let result = true;
if (num < 2) {
result = false;
return result;
}
for (let i = 2; i < num; i++) {
if (num % i === 0) {
result = false;
break;
}
}
return result;
}
```
I am trying to find whether a given number is prime or not, why is my code not executing in a limited amount of time? | 2022/10/19 | [
"https://Stackoverflow.com/questions/74128913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12730690/"
]
| §6.7.6.3p5 "Function declarators (including prototypes) > Semantics":
>
> If, in the declaration "**T D1**", **D1** has the form
>
>
>
> >
> > **D** **(** *parameter-type-list* **)**
> >
> >
> >
>
>
> or
>
>
>
> >
> > **D** **(** *identifier-list*opt **)**
> >
> >
> >
>
>
> and the type specified for *ident* in the declaration "**T D**" is "*derived-declarator-type-list T*", then the type specified for *ident* is "*derived-declarator-type-list* function returning the unqualified version of *T*"
>
>
>
So the type of `foo` is the same as if it was declared `S foo(void)`.
See also §6.7.3p5 "Type qualifiers > Semantics":
>
> The properties associated with qualified types are meaningful only for expressions that are lvalues.
>
>
>
So even if the first quoted paragraph didn't change the type, the const-qualification of the non-lvalue expression `foo()` would not be meaningful | Undefined behavior?
>
> **6.7.3 Type qualifiers**
>
> ...
>
>
> 9 If the specification of an array type includes any type qualifiers, the element type is so qualified, not the array type. ***If the specification of a function type includes any type
> qualifiers, the behavior is undefined.***136)
>
Or am I massively missing the point? |
1,289,711 | Given $A\in M\_{n \times n}(\mathbb{F})$ and $p\_{A}(x)=\det(xI-A)$ why saying that $\det(AI-A)=0$ is not valid? | 2015/05/19 | [
"https://math.stackexchange.com/questions/1289711",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/222832/"
]
| It's not valid because in the expression $xI$, the hidden operation is scalar multiplication, i.e., multiplication of the identity matrix by the constant real value $x$. In the expression $AI$, the hidden operation is matrix multiply, which is in general different from scalar multiply.
There's a real subtlety here: the polynomial $p\_A(x)$ is, as defined by the equation, a polynomial function of a single real variable. The CH theorem says that if you, after having computed the coefficients of that polynomial, now plug in the matrix $A$ for the variable $x$, and treat powers of $x$ as matrix powers of $A$, you get the zero matrix. Doing that plugging=in=a=matrix=where=a=real=number=should=be is a very weird operation, and so the result is quite surprising. | It's not valid because Cayley Hamilton says that $p\_A(A)=0$ where 0 is the zero matrix, but in your argument you have a zero scalar. |
117,996 | There are many web application vulnerabilities out there, such as XSS, CSRF, and etc, and there are many resources which explain them very well. But I want to find about their history, for example, who was the first to discover them **[Surely, it wasn't a single person]**, and when they were first discovered **[Surely, they weren't discovered at the same time]**, and so on. | 2016/03/19 | [
"https://security.stackexchange.com/questions/117996",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/94890/"
]
| You can
* [search the CVE list](https://cve.mitre.org/cve/cve.html) for keywords or specific CVEs and
* [search the NVD of the NIST](https://web.nvd.nist.gov/view/vuln/search).
Those two links should be fine to answer questions you might have about individual vulnerabilities - not only constrained to web applications - although they do not usually disclose the actual person that found the vulnerability. | [CVE Details](http://www.cvedetails.com/) is a great site listing vulnerabilities narrowed down to manufacture, product and version.
In addition it also shows the published dates in any results, which is very useful. |
117,996 | There are many web application vulnerabilities out there, such as XSS, CSRF, and etc, and there are many resources which explain them very well. But I want to find about their history, for example, who was the first to discover them **[Surely, it wasn't a single person]**, and when they were first discovered **[Surely, they weren't discovered at the same time]**, and so on. | 2016/03/19 | [
"https://security.stackexchange.com/questions/117996",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/94890/"
]
| You can
* [search the CVE list](https://cve.mitre.org/cve/cve.html) for keywords or specific CVEs and
* [search the NVD of the NIST](https://web.nvd.nist.gov/view/vuln/search).
Those two links should be fine to answer questions you might have about individual vulnerabilities - not only constrained to web applications - although they do not usually disclose the actual person that found the vulnerability. | Wikipedia and Google would be my choice, as there isn't one authoritative website including the history of vulnerability types.
The usual places that list vulnerability types generally do not include a history section. For example, here is the [CWE on XSS](https://cwe.mitre.org/data/definitions/79.html), here is the [CAPEC on XSS](https://capec.mitre.org/data/definitions/63.html), and here is the [OWASP page on XSS](https://www.owasp.org/index.php/Cross-site_Scripting_%28XSS%29).
The CVE lists suggested by others list individual vulnerabilities (but not vulnerability classes). If you want to know who discovered specific vulnerabilities in specific applications they are a great place to look though.
Wikipedia on the other hand has a history or background section for most vulnerability types, eg on XSS:
>
> Microsoft security-engineers introduced the term "cross-site scripting" in January 2000.
>
> [...]
>
> XSS vulnerabilities have been reported and exploited since the 1990s.
>
>
>
Or on SQL Injection:
>
> The first public discussions of SQL injection started appearing around 1998.[3] For example, a 1998 article in Phrack Magazine.[4]
>
>
>
A google search for the history of CSRF would for example lead you to [this exchange](http://www.tux.org/~peterw/csrf.txt).
You would need to verify the claims yourself though. |
117,996 | There are many web application vulnerabilities out there, such as XSS, CSRF, and etc, and there are many resources which explain them very well. But I want to find about their history, for example, who was the first to discover them **[Surely, it wasn't a single person]**, and when they were first discovered **[Surely, they weren't discovered at the same time]**, and so on. | 2016/03/19 | [
"https://security.stackexchange.com/questions/117996",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/94890/"
]
| Wikipedia and Google would be my choice, as there isn't one authoritative website including the history of vulnerability types.
The usual places that list vulnerability types generally do not include a history section. For example, here is the [CWE on XSS](https://cwe.mitre.org/data/definitions/79.html), here is the [CAPEC on XSS](https://capec.mitre.org/data/definitions/63.html), and here is the [OWASP page on XSS](https://www.owasp.org/index.php/Cross-site_Scripting_%28XSS%29).
The CVE lists suggested by others list individual vulnerabilities (but not vulnerability classes). If you want to know who discovered specific vulnerabilities in specific applications they are a great place to look though.
Wikipedia on the other hand has a history or background section for most vulnerability types, eg on XSS:
>
> Microsoft security-engineers introduced the term "cross-site scripting" in January 2000.
>
> [...]
>
> XSS vulnerabilities have been reported and exploited since the 1990s.
>
>
>
Or on SQL Injection:
>
> The first public discussions of SQL injection started appearing around 1998.[3] For example, a 1998 article in Phrack Magazine.[4]
>
>
>
A google search for the history of CSRF would for example lead you to [this exchange](http://www.tux.org/~peterw/csrf.txt).
You would need to verify the claims yourself though. | [CVE Details](http://www.cvedetails.com/) is a great site listing vulnerabilities narrowed down to manufacture, product and version.
In addition it also shows the published dates in any results, which is very useful. |
1,742 | Is it possible to automatically "add" `\left` and `\right` commands in front of all brackets? The source code should be left intact, but LaTeX should interpret every pair of brackets as if they were preceded by such commands. This is because adding `\left` and `\right` commands is time consuming and makes source code longer and less readable. I considered defining new commands such as `\lb` and `\rb` for `\left(` and `\right)`, but it doesn't seem very elegant to me: what if I also want to add square brackets for example?
Any ideas? Thanks. | 2010/08/15 | [
"https://tex.stackexchange.com/questions/1742",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/808/"
]
| The `\DeclarePairedDelimiter` command from [mathtools](http://www.ctan.org/pkg/mathtools) is useful. For example defining an absolute value macro;
```
\DeclarePairedDelimiter\abs{\lvert}{\rvert}
```
gives also a starred version with `\left` and `\right`
```
\abs*{\frac{a}{b}}
```
and the unstarred version takes an optional argument that can be `\big`, `\Big`, etc
```
\abs[\Bigg]{\frac{a}{b}}
``` | To make auto-sized bracketing as painless and concise as possible, here's what I do:
```
\usepackage{mathtools}
\DeclarePairedDelimiter\autobracket{(}{)}
\newcommand{\br}[1]{\autobracket*{#1}}
```
Example:
```
$$\br{\frac{1}{2}} + \br{1} - \br{\frac{\int_0^{2\pi} f(x)}{\sqrt[2]{\frac{1}{2}}}}$$
```
[](https://i.stack.imgur.com/z7LEa.png) |
1,742 | Is it possible to automatically "add" `\left` and `\right` commands in front of all brackets? The source code should be left intact, but LaTeX should interpret every pair of brackets as if they were preceded by such commands. This is because adding `\left` and `\right` commands is time consuming and makes source code longer and less readable. I considered defining new commands such as `\lb` and `\rb` for `\left(` and `\right)`, but it doesn't seem very elegant to me: what if I also want to add square brackets for example?
Any ideas? Thanks. | 2010/08/15 | [
"https://tex.stackexchange.com/questions/1742",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/808/"
]
| Adding `\left` and `\right` to all delimiters is difficult and likely not to yield the desired result in many places.
The [`nath`](http://www.ctan.org/pkg/nath) package aims at making `\left` and `\right` obsolete. From the readme:
>
> delimiters adapt their size to the material enclosed, rendering `\left` and `\right` almost obsolete.
>
>
> | It seems to me that it's easy to do *exactly* what you say, but you might not really want that; see the caveat below.
```
\let\lparen=(\let\rparen=)
\catcode`(=\active\catcode`)=\active
\def({\left\lparen}\def){\right\rparen}
```
The catch: There are some obvious disadvantages to this, such as that parentheses now only work in math mode; any text-mode or un-stretchy parentheses have to be entered as `\lparen\rparen`. You may be willing to do this in your own code, but you'll have to be quite careful about any external packages you include. (If you were *really* dedicated, you could have something like a `\stretchparens` / `\plainparens` pair to turn this behaviour on and off.)
I wonder if those wiser than I could comment on subtler disadvantages? |
1,742 | Is it possible to automatically "add" `\left` and `\right` commands in front of all brackets? The source code should be left intact, but LaTeX should interpret every pair of brackets as if they were preceded by such commands. This is because adding `\left` and `\right` commands is time consuming and makes source code longer and less readable. I considered defining new commands such as `\lb` and `\rb` for `\left(` and `\right)`, but it doesn't seem very elegant to me: what if I also want to add square brackets for example?
Any ideas? Thanks. | 2010/08/15 | [
"https://tex.stackexchange.com/questions/1742",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/808/"
]
| To make auto-sized bracketing as painless and concise as possible, here's what I do:
```
\usepackage{mathtools}
\DeclarePairedDelimiter\autobracket{(}{)}
\newcommand{\br}[1]{\autobracket*{#1}}
```
Example:
```
$$\br{\frac{1}{2}} + \br{1} - \br{\frac{\int_0^{2\pi} f(x)}{\sqrt[2]{\frac{1}{2}}}}$$
```
[](https://i.stack.imgur.com/z7LEa.png) | I use the following newcommands:
```
\newcommand{\of}[1]{\left(#1\right)}
\newcommand{\off}[1]{\left[#1\right]}
\newcommand{\offf}[1]{\left\{#1\right\}}
```
Hence, in the text, `f\of{x}` will appear as `f(x)`, `M\ast\offf{g\off{x}+h\off{x}}` will appear as `M*{g[x]+h[x]}`, etc. with the `\left` and `\right` commands automatically built-in. |
1,742 | Is it possible to automatically "add" `\left` and `\right` commands in front of all brackets? The source code should be left intact, but LaTeX should interpret every pair of brackets as if they were preceded by such commands. This is because adding `\left` and `\right` commands is time consuming and makes source code longer and less readable. I considered defining new commands such as `\lb` and `\rb` for `\left(` and `\right)`, but it doesn't seem very elegant to me: what if I also want to add square brackets for example?
Any ideas? Thanks. | 2010/08/15 | [
"https://tex.stackexchange.com/questions/1742",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/808/"
]
| Adding `\left` and `\right` to all delimiters is difficult and likely not to yield the desired result in many places.
The [`nath`](http://www.ctan.org/pkg/nath) package aims at making `\left` and `\right` obsolete. From the readme:
>
> delimiters adapt their size to the material enclosed, rendering `\left` and `\right` almost obsolete.
>
>
> | I always use some commands. For example:
```
\newcommand{\angles}[1]{\left\lange #1 \right\rangle}% ⟨⟩
\newcommand{\braces}[1]{\left\lbrace #1 \right\rbrace}% {}
\newcommand{\bracks}[1]{\left\lbrack #1 \right\rbrack}% []
\newcommand{\pars}[1]{\left( #1 \right)}% ()
\newcommand{\ds}[1]{\displaystyle{#1}}%
\newcommand{\+}{^{\dagger}}%
\newcommand{\partiald}[3][]{{\partial^{#1}#2 \over \partial {#3}^{#1}}}%
```
It works like this:
* `\pars{\Huge A}`
* `\partiald[3]{y\pars{x,t}}{t}`
* `A\\+`
* etc.
You can leave them in a file (for example `myMacros.tex`) and use `\input` in the main document: `\input{pathToFile/myMacros.tex}`. |
1,742 | Is it possible to automatically "add" `\left` and `\right` commands in front of all brackets? The source code should be left intact, but LaTeX should interpret every pair of brackets as if they were preceded by such commands. This is because adding `\left` and `\right` commands is time consuming and makes source code longer and less readable. I considered defining new commands such as `\lb` and `\rb` for `\left(` and `\right)`, but it doesn't seem very elegant to me: what if I also want to add square brackets for example?
Any ideas? Thanks. | 2010/08/15 | [
"https://tex.stackexchange.com/questions/1742",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/808/"
]
| **Edit:** *I'm leaving this answer up for “academic purposes” but, consider [Lev Bishop's](https://tex.stackexchange.com/questions/1742/automatic-left-and-right-commands/1765#1765) answer for an easier solution than mine.*
---
Over the years I've evolved my own solution which I think turned out quite nice. It gives you a command which you can call like
```
\newdelimcommand{parens}{(}{)}
```
which in turn will define for you a `\parens` command which you can then use as `\parens{thing}` to produce something like `(thing)` where, moreover, the parenthesis automatically resize. In fact you can use the command in three different ways
```
\parens{thing} % automatic resize
\parens*{thing} % no resize
\parens[big]{thing} % use the specified size
```
For the latter option you can use `auto` (the default), `base` (no resize), or one of the sizes: `big`, `Big`, `bigg`, `Bigg`.
Furthermore, inside of `thing` you can use the commands `\ldelim`, `\rdelim`, and `\mdelim` to create even more delimiters with the appropriate size selected by the given options. This allows, for example, to use `\mdelim` to automagically resize a “middle” bar. (See example at the end of the code).
For this to work you have to drop the following code in a .sty file and include it in your main .tex file with `\usepackage`.
```
\RequirePackage{amsmath}
% delim sizing options
\let\delim@autol\left \let\delim@autor\right \let\delim@autom\middle
\let\delim@basel\relax \let\delim@baser\relax \let\delim@basem\relax
\let\delim@bigl\bigl \let\delim@bigr\bigr \let\delim@bigm\big
\let\delim@Bigl\Bigl \let\delim@Bigr\Bigr \let\delim@Bigm\Big
\let\delim@biggl\biggl \let\delim@biggr\biggr \let\delim@biggm\bigg
\let\delim@Biggl\Biggl \let\delim@Biggr\Biggr \let\delim@Biggm\Bigg
% default definitions
\newcommand\ldelim{\relax}
\newcommand\rdelim{\relax}
\newcommand\mdelim{\relax}
% the actual command
\newcommand\delim@command[4]{{% #1 size #2 ldelim #3 rdelim #4 content
\def\ldelim{\csname delim@#1l\endcsname}%
\def\rdelim{\csname delim@#1r\endcsname}%
\def\mdelim{\csname delim@#1m\endcsname}%
\ldelim#2#4\rdelim#3}}
% a factory to define new delimiter commands
\newcommand{\newdelimcommand}[3]{% #1 name #2 ldelim #3 rdelim
\expandafter\newcommand\csname delim@#1@st\endcsname[1]{% ##1 content
\delim@command{base}{#2}{#3}{##1}}%
\expandafter\newcommand\csname delim@#1@ns\endcsname[2][auto]{%
% ##1 size ##2 content
\delim@command{##1}{#2}{#3}{##2}}%
\expandafter\DeclareRobustCommand\csname#1\endcsname{%
\@ifstar{\csname delim@#1@st\endcsname}{\csname delim@#1@ns\endcsname}%
}%
}
% syntactically named delimiters
\newdelimcommand{braces}{\lbrace}{\rbrace}
\newdelimcommand{angles}{\langle}{\rangle}
\newdelimcommand{verts}{\lvert}{\rvert}
\newdelimcommand{Verts}{\lVert}{\rVert}
\newdelimcommand{brackets}{[}{]}
% semantically named delimiters
\newcommand{\set}{\braces}
\newcommand{\abs}{\verts}
\newcommand{\size}{\verts}
\newcommand{\norm}{\Verts}
\newcommand{\tuple}{\angles}
% Automagic `such that' for set comprehension. Inside an automagic
% delimiter command, the vertical bar will resize appropriately
% Example:
% \set{ x \in W \st x > 0 }
\newcommand{\st}{\;\mdelim\vert\;}
```
I've been thinking to eventually release this (and other bits of code) as a proper style file. But for the time being here it is for you to copy&paste. :) | I always use some commands. For example:
```
\newcommand{\angles}[1]{\left\lange #1 \right\rangle}% ⟨⟩
\newcommand{\braces}[1]{\left\lbrace #1 \right\rbrace}% {}
\newcommand{\bracks}[1]{\left\lbrack #1 \right\rbrack}% []
\newcommand{\pars}[1]{\left( #1 \right)}% ()
\newcommand{\ds}[1]{\displaystyle{#1}}%
\newcommand{\+}{^{\dagger}}%
\newcommand{\partiald}[3][]{{\partial^{#1}#2 \over \partial {#3}^{#1}}}%
```
It works like this:
* `\pars{\Huge A}`
* `\partiald[3]{y\pars{x,t}}{t}`
* `A\\+`
* etc.
You can leave them in a file (for example `myMacros.tex`) and use `\input` in the main document: `\input{pathToFile/myMacros.tex}`. |
1,742 | Is it possible to automatically "add" `\left` and `\right` commands in front of all brackets? The source code should be left intact, but LaTeX should interpret every pair of brackets as if they were preceded by such commands. This is because adding `\left` and `\right` commands is time consuming and makes source code longer and less readable. I considered defining new commands such as `\lb` and `\rb` for `\left(` and `\right)`, but it doesn't seem very elegant to me: what if I also want to add square brackets for example?
Any ideas? Thanks. | 2010/08/15 | [
"https://tex.stackexchange.com/questions/1742",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/808/"
]
| Adding `\left` and `\right` to all delimiters is difficult and likely not to yield the desired result in many places.
The [`nath`](http://www.ctan.org/pkg/nath) package aims at making `\left` and `\right` obsolete. From the readme:
>
> delimiters adapt their size to the material enclosed, rendering `\left` and `\right` almost obsolete.
>
>
> | I use the following newcommands:
```
\newcommand{\of}[1]{\left(#1\right)}
\newcommand{\off}[1]{\left[#1\right]}
\newcommand{\offf}[1]{\left\{#1\right\}}
```
Hence, in the text, `f\of{x}` will appear as `f(x)`, `M\ast\offf{g\off{x}+h\off{x}}` will appear as `M*{g[x]+h[x]}`, etc. with the `\left` and `\right` commands automatically built-in. |
1,742 | Is it possible to automatically "add" `\left` and `\right` commands in front of all brackets? The source code should be left intact, but LaTeX should interpret every pair of brackets as if they were preceded by such commands. This is because adding `\left` and `\right` commands is time consuming and makes source code longer and less readable. I considered defining new commands such as `\lb` and `\rb` for `\left(` and `\right)`, but it doesn't seem very elegant to me: what if I also want to add square brackets for example?
Any ideas? Thanks. | 2010/08/15 | [
"https://tex.stackexchange.com/questions/1742",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/808/"
]
| To make auto-sized bracketing as painless and concise as possible, here's what I do:
```
\usepackage{mathtools}
\DeclarePairedDelimiter\autobracket{(}{)}
\newcommand{\br}[1]{\autobracket*{#1}}
```
Example:
```
$$\br{\frac{1}{2}} + \br{1} - \br{\frac{\int_0^{2\pi} f(x)}{\sqrt[2]{\frac{1}{2}}}}$$
```
[](https://i.stack.imgur.com/z7LEa.png) | I always use some commands. For example:
```
\newcommand{\angles}[1]{\left\lange #1 \right\rangle}% ⟨⟩
\newcommand{\braces}[1]{\left\lbrace #1 \right\rbrace}% {}
\newcommand{\bracks}[1]{\left\lbrack #1 \right\rbrack}% []
\newcommand{\pars}[1]{\left( #1 \right)}% ()
\newcommand{\ds}[1]{\displaystyle{#1}}%
\newcommand{\+}{^{\dagger}}%
\newcommand{\partiald}[3][]{{\partial^{#1}#2 \over \partial {#3}^{#1}}}%
```
It works like this:
* `\pars{\Huge A}`
* `\partiald[3]{y\pars{x,t}}{t}`
* `A\\+`
* etc.
You can leave them in a file (for example `myMacros.tex`) and use `\input` in the main document: `\input{pathToFile/myMacros.tex}`. |
1,742 | Is it possible to automatically "add" `\left` and `\right` commands in front of all brackets? The source code should be left intact, but LaTeX should interpret every pair of brackets as if they were preceded by such commands. This is because adding `\left` and `\right` commands is time consuming and makes source code longer and less readable. I considered defining new commands such as `\lb` and `\rb` for `\left(` and `\right)`, but it doesn't seem very elegant to me: what if I also want to add square brackets for example?
Any ideas? Thanks. | 2010/08/15 | [
"https://tex.stackexchange.com/questions/1742",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/808/"
]
| The `\DeclarePairedDelimiter` command from [mathtools](http://www.ctan.org/pkg/mathtools) is useful. For example defining an absolute value macro;
```
\DeclarePairedDelimiter\abs{\lvert}{\rvert}
```
gives also a starred version with `\left` and `\right`
```
\abs*{\frac{a}{b}}
```
and the unstarred version takes an optional argument that can be `\big`, `\Big`, etc
```
\abs[\Bigg]{\frac{a}{b}}
``` | I use the following newcommands:
```
\newcommand{\of}[1]{\left(#1\right)}
\newcommand{\off}[1]{\left[#1\right]}
\newcommand{\offf}[1]{\left\{#1\right\}}
```
Hence, in the text, `f\of{x}` will appear as `f(x)`, `M\ast\offf{g\off{x}+h\off{x}}` will appear as `M*{g[x]+h[x]}`, etc. with the `\left` and `\right` commands automatically built-in. |
1,742 | Is it possible to automatically "add" `\left` and `\right` commands in front of all brackets? The source code should be left intact, but LaTeX should interpret every pair of brackets as if they were preceded by such commands. This is because adding `\left` and `\right` commands is time consuming and makes source code longer and less readable. I considered defining new commands such as `\lb` and `\rb` for `\left(` and `\right)`, but it doesn't seem very elegant to me: what if I also want to add square brackets for example?
Any ideas? Thanks. | 2010/08/15 | [
"https://tex.stackexchange.com/questions/1742",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/808/"
]
| I use the following newcommands:
```
\newcommand{\of}[1]{\left(#1\right)}
\newcommand{\off}[1]{\left[#1\right]}
\newcommand{\offf}[1]{\left\{#1\right\}}
```
Hence, in the text, `f\of{x}` will appear as `f(x)`, `M\ast\offf{g\off{x}+h\off{x}}` will appear as `M*{g[x]+h[x]}`, etc. with the `\left` and `\right` commands automatically built-in. | Why has no one metioned `\qty`?
It comes in physics package
```tex
\documentclass{minimal}
\usepackage{amsmath}
\usepackage{physics}
\begin{document}
\begin{align*}
\qty{curly braces}\\
\qty(parenthesis)\\
\qty|Vertical bars|
\end{align*}
\end{document}
``` |
1,742 | Is it possible to automatically "add" `\left` and `\right` commands in front of all brackets? The source code should be left intact, but LaTeX should interpret every pair of brackets as if they were preceded by such commands. This is because adding `\left` and `\right` commands is time consuming and makes source code longer and less readable. I considered defining new commands such as `\lb` and `\rb` for `\left(` and `\right)`, but it doesn't seem very elegant to me: what if I also want to add square brackets for example?
Any ideas? Thanks. | 2010/08/15 | [
"https://tex.stackexchange.com/questions/1742",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/808/"
]
| I use the following newcommands:
```
\newcommand{\of}[1]{\left(#1\right)}
\newcommand{\off}[1]{\left[#1\right]}
\newcommand{\offf}[1]{\left\{#1\right\}}
```
Hence, in the text, `f\of{x}` will appear as `f(x)`, `M\ast\offf{g\off{x}+h\off{x}}` will appear as `M*{g[x]+h[x]}`, etc. with the `\left` and `\right` commands automatically built-in. | There is another possibility to do it, if the automatic size should be the default ([as here](https://tex.stackexchange.com/questions/23178/swap-definition-of-starred-and-non-starred-command)) and explicit sizes should be easier to remember (numbers 0 till 4 instead of exotic names)
```
\documentclass{article}
\usepackage{amsmath}
% Enable the new LaTeX 3 commands.
\usepackage{xparse}
% Provide the \alias command substituting the \let command by working with optional arguments.
\usepackage{letltxmacro}
\LetLtxMacro{\alias}{\LetLtxMacro}
% Define a clear and useful programming interface. You should define \new, \renew and \provide similarly and use the correct one below.
\alias{\declare}{\DeclareDocumentCommand}
% Fix the spacing around \left and \right: https://tex.stackexchange.com/questions/2607/spacing-around-left-and-right
\alias{\leftOld}{\left}
\alias{\rightOld}{\right}
\declare{\left}{}{\mathopen{}\mathclose\bgroup\leftOld}
\declare{\right}{}{\aftergroup\egroup\rightOld}
% Usage: \newdelimited{functionName}{left delimiter}{right delimiter}
% Example: \newdelimited{parens}{(}{)}
%
% Usage of inner command: \functionName[explicit size]{delimited content}
% An auto sized delimiter is used, if no explicit size is given. Explicit sizes range from 0 (small) to 4 (huge)
% Examples: \parens{x}, \parens{\frac{x}{y}}, \parens[3]{x}, \parens[0]{\frac{x}{y}}
%
\declare{\newdelimited}{mmm}{%
\declare{#1}{om}{%
\IfNoValueTF{##1}{%
\left#2 ##2 \right#3%
}{%
% Use the amsmath delimiter sizes to have proper scaling all the time.
\ifcase##1\relax%
#2 ##2 #3%
\or \bigl#2 ##2 \bigr#3%
\or \Bigl#2 ##2 \Bigr#3%
\or \biggl#2 ##2 \biggr#3%
\or \Biggl#2 ##2 \Biggr#3%
\else \PackageError{newdelimited}{Only optional values 0, 1, 2, 3 and 4 are supported.}%
\fi%
}%
}%
}
\begin{document}
\newdelimited{\parens}{(}{)}
$\parens{x}, \parens{\frac{M}{W}}, \parens[3]{x}, \parens[0]{\frac{M}{W}}$
\end{document}
```
The result looks like this:
 |
17,152,489 | I'm using a self tracking entity model. `ProductInstallation` is a DTO which contains all the details about the product installation for a company.
The `UserRoles` entity holds the relationship in-between the Product-System Role-UserID.
As an example:
>
> Product: Inventory
>
>
> System Role : PurchasingUser
>
>
> User ID : hasithaH <- (Suppose me)
>
>
>
using the below LINQ query, I can get the distinct UserIDs.
```
string[] userIDs = productInstallation.UserRoles
.Select(u=>u.UserID).Distinct().ToArray();
```
now I need to get all the User Profiles for the UserIDs I queried in above steps.
```
productInstallation.SystemUsers = context.SystemUsers.Select(u=> u.UserID ..???
```
In SQL point of view, this is the query I want:
```
Select * from SystemUsers where UserID in ('UserA','UserB','UserC')
```
How should I write a LINQ query to get this done? | 2013/06/17 | [
"https://Stackoverflow.com/questions/17152489",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2494075/"
]
| You write it as follows:
```
var result = context.SystemUsers.Where(su =>
productInstallation.UserRoles.Any(ur => su.UserID == ur.UserId));
```
Or if both sources are not `IQuerable` from the same db:
```
string[] userIDs = productInstallation.UserRoles
.Select(u=>u.UserID).Distinct().ToArray();
var result = context.SystemUsers.Where(su =>
userIDs.Contains(su.UserID));
``` | You can try this:
```
productInstallation.SystemUsers =
context.SystemUsers.FindAll(u=> userIDs.Contains(u.UserID))
``` |
17,152,489 | I'm using a self tracking entity model. `ProductInstallation` is a DTO which contains all the details about the product installation for a company.
The `UserRoles` entity holds the relationship in-between the Product-System Role-UserID.
As an example:
>
> Product: Inventory
>
>
> System Role : PurchasingUser
>
>
> User ID : hasithaH <- (Suppose me)
>
>
>
using the below LINQ query, I can get the distinct UserIDs.
```
string[] userIDs = productInstallation.UserRoles
.Select(u=>u.UserID).Distinct().ToArray();
```
now I need to get all the User Profiles for the UserIDs I queried in above steps.
```
productInstallation.SystemUsers = context.SystemUsers.Select(u=> u.UserID ..???
```
In SQL point of view, this is the query I want:
```
Select * from SystemUsers where UserID in ('UserA','UserB','UserC')
```
How should I write a LINQ query to get this done? | 2013/06/17 | [
"https://Stackoverflow.com/questions/17152489",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2494075/"
]
| You write it as follows:
```
var result = context.SystemUsers.Where(su =>
productInstallation.UserRoles.Any(ur => su.UserID == ur.UserId));
```
Or if both sources are not `IQuerable` from the same db:
```
string[] userIDs = productInstallation.UserRoles
.Select(u=>u.UserID).Distinct().ToArray();
var result = context.SystemUsers.Where(su =>
userIDs.Contains(su.UserID));
``` | What you really want to do here is join the two tables. Using a Join you can do this in one query rather than executing two separate queries:
```
var systemUsers = from userRole in UserRoles
join systemUser in SystemUsers
on userRole.UserID equals systemUser.UserID
select systemUser;
``` |
70,670,161 | I'm working to create a graph using HTML/JS/Python/Flask and the labels for this line graph should come from a list in Python and then I would use it on a Javascript.
So far I have not been able to successfully iterate over that list in Javascript, I'm getting 4 times the same string on my HTML.
I'm using a code similar to this one:
start.py
```
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/', methods = ['GET','POST'])
def home():
data = ['ABC','DEF','GHI','JKL']
return render_template('index.html', data = data, len = len(data))
if __name__ == '__main__':
app.run(debug=True)
```
index.html
```
<body>
<p id='test'></p>
<script>
let text = '';
for (i=0; i<'{{len}}'; i++){
text += '{{data | tojson}}[i]' + '<br>'
}
console.log(text)
document.getElementById('test').innerHTML = text;
</script>
</body>
```
I'm getting this as an output:
```
['ABC','DEF','GHI','JKL'][i]
['ABC','DEF','GHI','JKL'][i]
['ABC','DEF','GHI','JKL'][i]
['ABC','DEF','GHI','JKL'][i]
```
And I'm looking to get this instead:
```
ABC
DEF
GHI
JKL
```
The data sent to the Javascript is sent as text and not as a list, if I change this:
```
text += '{{data | tojson}}[i]' + '<br>'
```
To this:
```
text += '{{data | tojson}}'[i] + '<br>'
```
The output becomes:
```
[
"
A
B
```
And the console output is:
```
[<br>"<br>A<br>B<br>
```
Do anybody know how to handle this properly so I get the correct results? | 2022/01/11 | [
"https://Stackoverflow.com/questions/70670161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12959019/"
]
| As you might have noticed, I'm a complete beginner when it comes to Javascript, doing some research, I found out I can slice and split in Javascript as well. So I solved my issue by using those two methods.
Giving more detail about what I did, {{data}} is passed over to Javascript as a single string, as '['ABC','DEF','GHI','JKL']', and if you read this string as a console output it shows:
```
['ABC', 'DEF', 'GHI', 'JKL']
```
To solve this I first sliced the string with:
```
flask_data = '{{data}}';
temp_array = flask_data.slice(6,-6);
```
So I get this as a result:
```
ABC', 'DEF', 'GHI', 'JKL
```
Then I split the string using the following substring: '', '', as follows:
```
array = temp_array.split('', '');
```
And as a result I got the array I needed:
```
['ABC','DEF','GHI','JKL']
``` | Try this in HTML
```html
<body>
<p id='test'></p>
<script>
let text = '';
for (i=0; i<'{{len}}'; i++){
text += '{{data[i]}}' + '<br>'
}
console.log(text)
document.getElementById('test').innerHTML = text;
</script>
</body>
```
or you can also pass a string instead of an array.
```py
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/', methods = ['GET','POST'])
def home():
data = ['ABC','DEF','GHI','JKL']
return render_template('index.html', data = "\n".join(data), len = len(data))
if __name__ == '__main__':
app.run(debug=True)
```
and then in HTML you can just print this joined string
```
<body>
<p id='test'></p>
<script>
document.getElementById('test').innerHTML = {{data}};
</script>
</body>
``` |
27,019,783 | well, i'm new in this and i dont know how i can make this program works, i need Write a program that calculates and returns the sum of the components of a vector squared
and i got this error:
```
import java.util.*;
public class cuadrado
{
public static void main(String[] args)
{
Scanner teclado= new Scanner (System.in);
int n=0,i=0,y=0;
System.out.println("ingrese el valor de el vector");
n=teclado.nextInt();
int[ ]suma=new int[n];
for(i=0;i<suma.lenght;i=i+1);
{
System.out.println("ingrese el valor de un numero");
suma[i]=teclado.nextInt();
y+=suma[i];
System.out.println(""+y);
}
}
}
```
cannot find symbol in the line 16 | 2014/11/19 | [
"https://Stackoverflow.com/questions/27019783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| It's fairly simple to do this with XML::Twig (and I am happy I got the "delete the current element during parsing" to work a while back):
```
#!/usr/bin/perl
use strict;
use warnings;
use XML::Twig;
my $delt= 'delt.xml';
XML::Twig->new( twig_handlers => { delt => \&delt },
pretty_print => 'indented',
)
->parsefile( $delt);
exit;
sub delt
{ my( $t, $delt)= @_;
my $delt_file= sprintf( 'delt_%s.xml', $delt->id);
# the only tricky part: remove previous doc if needed
if( my $prev_doc= $delt->parent( 'doc')->prev_sibling( 'doc'))
{ $prev_doc->delete; }
$t->print_to_file( $delt_file);
$delt->delete;
}
``` | The reason you're having difficult is because what you're doing is extracting a subset from an XML doc, but then trying to also include some of the stuff from the 'parent'.
Pulling your 'delts' out would be fairly straightforward
I would be wanting to use `XML::Twig` with this - this is a perfect place to use a twig handler.
I'd be thinking *something* along the lines of (and apologies, this doesn't quite work yet).
```
use strict;
use warnings;
use XML::Twig;
sub process_delt {
my ( $twig, $delt ) = @_;
my $delt_id = $delt->att('id');
print "\nID:\n$delt_id\n";
my $filename = "$delt_id.xml";
$delt->set_pretty_print('indented');
$delt->print;
print "\n--------\n";
}
my $twig = XML::Twig->new(
twig_handlers => { delt => \&process_delt },
);
local $/;
$twig->parse(<DATA>);
__DATA__
<xml>
<service>
<title>split xml</title>
<main>
<doc id="001">
<title>doc1</title>
<delt id="0001">
<title>delt1</title>
<text>num1</text>``
<text>num1</text>
</delt>
<delt id="0002-A">
<title>delt1</title>
<text>num1</text>
<text>num1</text>
</delt>
</doc>
<doc id="002">
<title>doc2</title>
<delt id="0003">
<title>delt1</title>
<text>num1</text>
<text>num1</text>
</delt>
<delt id="0004">
<title>delt1</title>
<text>num1</text>
<text>num1</text>
</delt>
</doc>
</main>
</service>
</xml>
```
Edit: Take a look at @mirod's answer, because it's fully working. This one will just extract each 'delt' and then you'd probably have to mess around with figuring out parent stuff. |
71,769,925 | I have a dataframe like the below and want to remove trailing zeros in pairs of 2.
```
col1
99990000
11100000
22220000
```
```
data = {'col1': ['99990000', '11100000', '22220000']}
df = pd.DataFrame(data=data)
```
desired result
```
col1
9999
1110
2222
```
The below removes all trailing zeros not and not keeping 1110?
```
df['col1'].str.replace('00+$','')
df['col1'].str.rstrip('00')
``` | 2022/04/06 | [
"https://Stackoverflow.com/questions/71769925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6402231/"
]
| Your `00+` applies the repeater `+` only to the last `0`, you need to use a group:
```
df['col1'].str.replace('(00)+$','')
```
Output:
```
0 9999
1 1110
2 2222
Name: col1, dtype: object
``` | Try this, it should work
```
df['col1'].str[:4]
``` |
71,769,925 | I have a dataframe like the below and want to remove trailing zeros in pairs of 2.
```
col1
99990000
11100000
22220000
```
```
data = {'col1': ['99990000', '11100000', '22220000']}
df = pd.DataFrame(data=data)
```
desired result
```
col1
9999
1110
2222
```
The below removes all trailing zeros not and not keeping 1110?
```
df['col1'].str.replace('00+$','')
df['col1'].str.rstrip('00')
``` | 2022/04/06 | [
"https://Stackoverflow.com/questions/71769925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6402231/"
]
| Just to conceptualize the regex, here is an example. The solution from @mozway is much better but this focuses on the substitution only, ignoring pandas:
```
import re
col1 = [re.sub(r'(00)+$', '', num) for num in
['99990000', '11100000', '22220000']]
# ['9999', '1110', '2222']
```
* [`(00)+$`](https://regex101.com/r/1IVn5T/2)
[](https://i.stack.imgur.com/Yaf9r.png) | Try this, it should work
```
df['col1'].str[:4]
``` |
71,769,925 | I have a dataframe like the below and want to remove trailing zeros in pairs of 2.
```
col1
99990000
11100000
22220000
```
```
data = {'col1': ['99990000', '11100000', '22220000']}
df = pd.DataFrame(data=data)
```
desired result
```
col1
9999
1110
2222
```
The below removes all trailing zeros not and not keeping 1110?
```
df['col1'].str.replace('00+$','')
df['col1'].str.rstrip('00')
``` | 2022/04/06 | [
"https://Stackoverflow.com/questions/71769925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6402231/"
]
| Your `00+` applies the repeater `+` only to the last `0`, you need to use a group:
```
df['col1'].str.replace('(00)+$','')
```
Output:
```
0 9999
1 1110
2 2222
Name: col1, dtype: object
``` | Just to conceptualize the regex, here is an example. The solution from @mozway is much better but this focuses on the substitution only, ignoring pandas:
```
import re
col1 = [re.sub(r'(00)+$', '', num) for num in
['99990000', '11100000', '22220000']]
# ['9999', '1110', '2222']
```
* [`(00)+$`](https://regex101.com/r/1IVn5T/2)
[](https://i.stack.imgur.com/Yaf9r.png) |
29,711,573 | I don't understand this behavior of dart2js code.
I have this only in async function and only after compiling to JS.
```
e.keyCode is equal 13
KeyCode.ENTER is equal 13
```
but
```
(e.keyCode == KeyCode.ENTER) is false
```
This is simple code to debugging my issue.
Whats going on?
```
import 'dart:html';
main() async
{
await for(KeyboardEvent e in window.onKeyDown)
{
print('e.keyCode : ${e.keyCode}');
print('e.keyCode.hashCode : ${e.keyCode.hashCode}');
print('KeyCode.ENTER : ${KeyCode.ENTER}');
print('KeyCode.ENTER.hashCode : ${KeyCode.ENTER.hashCode}');
print('e.keyCode.runtimeType : ${e.keyCode.runtimeType}');
print('KeyCode.ENTER.runtimeType : ${KeyCode.ENTER.runtimeType}');
print('e.keyCode == KeyCode.ENTER ${e.keyCode == KeyCode.ENTER}');
print('e.keyCode != KeyCode.ENTER ${e.keyCode != KeyCode.ENTER}');
int a = e.keyCode;
int b = KeyCode.ENTER;
print('a = $a');
print('b = $b');
print('a.hashCode = ${a.hashCode}');
print('b.hashCode = ${b.hashCode}');
print('a == b ${(a == b).toString()}');
print('a == 13 ${(a == 13).toString()}');
print('b == 13 ${(b == 13).toString()}');
if(a == b)
print('DART: a == b');
else
print('DART: a != b');
}
}
```
Output on Chrome after pressing Enter (dart2js - minified):
>
> e.keyCode : 13
>
> e.keyCode.hashCode : 13
>
> KeyCode.ENTER : 13
>
> KeyCode.ENTER.hashCode : 13
>
> e.keyCode.runtimeType : int
>
> KeyCode.ENTER.runtimeType : int
>
> e.keyCode == KeyCode.ENTER false
>
> e.keyCode != KeyCode.ENTER true
>
> a = 13
>
> b = 13
>
> a.hashCode = 13
>
> b.hashCode = 13
>
> a == b true
>
> a == 13 true
>
> b == 13 true
>
> DART: a != b
>
>
>
>
On DartVM (Dartium) everything is correct:
>
> e.keyCode : 13
>
> e.keyCode.hashCode : 13
>
> KeyCode.ENTER : 13
>
> KeyCode.ENTER.hashCode : 13
>
> e.keyCode.runtimeType : int
>
> KeyCode.ENTER.runtimeType : int
>
> e.keyCode == KeyCode.ENTER true
>
> e.keyCode != KeyCode.ENTER false
>
> a = 13
>
> b = 13
>
> a.hashCode = 13
>
> b.hashCode = 13
>
> a == b true
>
> a == 13 true
>
> b == 13 true
>
> DART: a == b
>
>
>
>
**// EDIT**
I noticed that it does not matter that I'm using keyCode.
This is async issue.
Code below returns 'OK' on Dartium and 'NOPE' on Chrome after compiling to JS.
```
import 'dart:async';
main() async
{
var ctrl = new StreamController();
ctrl.add(true);
await for(var e in ctrl.stream)
{
if(e == e)
print('OK');
else
print('NOPE');
}
}
``` | 2015/04/18 | [
"https://Stackoverflow.com/questions/29711573",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3489593/"
]
| This is indeed the same as [this bug](http://dartbug.com/23119).
The wrong type was inferred for the iteration variable of async for loops.
It is fixed in 1.10. | This must be 1.9.3 dart2js bug.
I use now Dart SDK version 1.10.0-dev.1.5 and everything works fine. This is only solution what I found, if I want use 'await for'. |
1,557,019 | I have a clumsy way to get the max length of a column in the database, but it's so bad that it seems wrong:
```
var length = new DataNS.WidgetTable(provider).description.MaxLength
```
Do I really have to instantiate some object and go digging through it? I even have to pass a provider to it explicitly.
If this really is the right way to do it, what's the best to get the current provider to pass to it? If it's not, what is the best way? | 2009/10/12 | [
"https://Stackoverflow.com/questions/1557019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15915/"
]
| Yes this does seem a bit clumsy but I can't see any less clumsy way of getting the MaxLength values. To get the current provider you can just use the GetProvider method of theSubSonic.DataProviders.ProviderFactory class. So your example would look something like:
```
var length = new DataNS.WidgetTable(ProviderFactory.GetProvider()).description.MaxLength;
``` | In subsonic 2.2 I do the following. Does this not work in 3?
```
var length = Template.Schema.GetColumn("Name").MaxLength;
``` |
1,557,019 | I have a clumsy way to get the max length of a column in the database, but it's so bad that it seems wrong:
```
var length = new DataNS.WidgetTable(provider).description.MaxLength
```
Do I really have to instantiate some object and go digging through it? I even have to pass a provider to it explicitly.
If this really is the right way to do it, what's the best to get the current provider to pass to it? If it's not, what is the best way? | 2009/10/12 | [
"https://Stackoverflow.com/questions/1557019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15915/"
]
| Yes this does seem a bit clumsy but I can't see any less clumsy way of getting the MaxLength values. To get the current provider you can just use the GetProvider method of theSubSonic.DataProviders.ProviderFactory class. So your example would look something like:
```
var length = new DataNS.WidgetTable(ProviderFactory.GetProvider()).description.MaxLength;
``` | If you use ActiveRecord then your object has a [COLUMN\_NAME]Column property which has all of this information. So if you have a Post object instantiated (like "post") you could use post.TitleColumn.MaxLength.
If you're using SubSonic 3 you can head in to Structs.tt and spin up whatever you need as well. |
1,557,019 | I have a clumsy way to get the max length of a column in the database, but it's so bad that it seems wrong:
```
var length = new DataNS.WidgetTable(provider).description.MaxLength
```
Do I really have to instantiate some object and go digging through it? I even have to pass a provider to it explicitly.
If this really is the right way to do it, what's the best to get the current provider to pass to it? If it's not, what is the best way? | 2009/10/12 | [
"https://Stackoverflow.com/questions/1557019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15915/"
]
| Yes this does seem a bit clumsy but I can't see any less clumsy way of getting the MaxLength values. To get the current provider you can just use the GetProvider method of theSubSonic.DataProviders.ProviderFactory class. So your example would look something like:
```
var length = new DataNS.WidgetTable(ProviderFactory.GetProvider()).description.MaxLength;
``` | I got something like this to work in SubSonic 3 using ActiveRecord, it works:
```
new AccountsTable(null).ContactEmail.MaxLength
```
I'm using it in an ASP.NET MVC view:
```
<%= Html.TextBoxFor(model => model.ContactEmail,
new { maxlength = new AccountsTable(null).ContactEmail.MaxLength })%>
```
But not sure if passing null in the AccountsTable constructor is going to trip things up at some point -- does anyone know if this is NOT advisable? I tried to find another way, as concise as possible, but this is where I ended up. |
1,557,019 | I have a clumsy way to get the max length of a column in the database, but it's so bad that it seems wrong:
```
var length = new DataNS.WidgetTable(provider).description.MaxLength
```
Do I really have to instantiate some object and go digging through it? I even have to pass a provider to it explicitly.
If this really is the right way to do it, what's the best to get the current provider to pass to it? If it's not, what is the best way? | 2009/10/12 | [
"https://Stackoverflow.com/questions/1557019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15915/"
]
| If you use ActiveRecord then your object has a [COLUMN\_NAME]Column property which has all of this information. So if you have a Post object instantiated (like "post") you could use post.TitleColumn.MaxLength.
If you're using SubSonic 3 you can head in to Structs.tt and spin up whatever you need as well. | In subsonic 2.2 I do the following. Does this not work in 3?
```
var length = Template.Schema.GetColumn("Name").MaxLength;
``` |
1,557,019 | I have a clumsy way to get the max length of a column in the database, but it's so bad that it seems wrong:
```
var length = new DataNS.WidgetTable(provider).description.MaxLength
```
Do I really have to instantiate some object and go digging through it? I even have to pass a provider to it explicitly.
If this really is the right way to do it, what's the best to get the current provider to pass to it? If it's not, what is the best way? | 2009/10/12 | [
"https://Stackoverflow.com/questions/1557019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15915/"
]
| If you use ActiveRecord then your object has a [COLUMN\_NAME]Column property which has all of this information. So if you have a Post object instantiated (like "post") you could use post.TitleColumn.MaxLength.
If you're using SubSonic 3 you can head in to Structs.tt and spin up whatever you need as well. | I got something like this to work in SubSonic 3 using ActiveRecord, it works:
```
new AccountsTable(null).ContactEmail.MaxLength
```
I'm using it in an ASP.NET MVC view:
```
<%= Html.TextBoxFor(model => model.ContactEmail,
new { maxlength = new AccountsTable(null).ContactEmail.MaxLength })%>
```
But not sure if passing null in the AccountsTable constructor is going to trip things up at some point -- does anyone know if this is NOT advisable? I tried to find another way, as concise as possible, but this is where I ended up. |
30,916,718 | I have problem with my Dynamic Web Application. I just started learning JavaEE 6 and now I stack on JPA. I configured my app, added libraries but I still get this annoying info: No Persistence provider for EntityManager named X. I try to get answer in Internet, but nothing help me.
This is my persistance.xml file:
```
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="PierwszaAplikacja" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>devcastzone.javaee.Uzytkownik</class>
<properties>
<property name="hibernate.connection.username" value="root"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost/szkolenie_javaee?characterEncoding=utf8"/>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
</properties>
</persistence-unit>
```
This is my class Uzytkownik.java:
```
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="uzytkownik")
public class Uzytkownik implements Serializable {
private static final long serialVersionUID = -3299291830280417103L;
@Id
private int id;
private String imie;
private String nazwisko;
//getters and setters
}
```
And my EntityManagerFactory creator in servlet:
```
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException
{
res.setContentType("text/plain;charset=utf-8");
res.getWriter().println("Cos tam cos tam");
EntityManagerFactory emf = Persistence.createEntityManagerFactory("PierwszaAplikacja");
EntityManager em = emf.createEntityManager();
Uzytkownik u = em.find(Uzytkownik.class, 1);
res.getWriter().println(u.getImie() + " " + u.getNazwisko() + "\n");
em.close();
emf.close();
}
```
Of course I have my persistence.xml in root in META-INF. Maybe anyone can help me with that issue? | 2015/06/18 | [
"https://Stackoverflow.com/questions/30916718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5024224/"
]
| You're gonna need to extend the `HtmlHelper` class with the following:
```
public static MvcHtmlString HelpTextFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expr)
{
var memberExpr = expr.Body as MemberExpression;
if (memberExpr != null)
{
var helpAttr = memberExpr.Member.GetCustomAttributes(false).OfType<HelpTextAttribute>().SingleOrDefault();
if (helpAttr != null)
return new MvcHtmlString(@"<span class=""help"">" + helpAttr.Text + "</span>");
}
return MvcHtmlString.Empty;
}
```
Then use it as requested:
```
@Html.HelpTextFor(m => m.MemberNo)
```
Also, be sure to mark your `HelpTextAttribute` with the `public` modifier. | Maybe you are doing things wrong because i think that `DataAnnotations` and `MVC Helpers` are different things.
i would do something like this:
a helper view on my `App_Code` with the code:
```
@helper HelpTextFor(string text) {
<span>@text</span>
}
```
and then use it as you wrote. |
30,916,718 | I have problem with my Dynamic Web Application. I just started learning JavaEE 6 and now I stack on JPA. I configured my app, added libraries but I still get this annoying info: No Persistence provider for EntityManager named X. I try to get answer in Internet, but nothing help me.
This is my persistance.xml file:
```
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="PierwszaAplikacja" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>devcastzone.javaee.Uzytkownik</class>
<properties>
<property name="hibernate.connection.username" value="root"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost/szkolenie_javaee?characterEncoding=utf8"/>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
</properties>
</persistence-unit>
```
This is my class Uzytkownik.java:
```
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="uzytkownik")
public class Uzytkownik implements Serializable {
private static final long serialVersionUID = -3299291830280417103L;
@Id
private int id;
private String imie;
private String nazwisko;
//getters and setters
}
```
And my EntityManagerFactory creator in servlet:
```
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException
{
res.setContentType("text/plain;charset=utf-8");
res.getWriter().println("Cos tam cos tam");
EntityManagerFactory emf = Persistence.createEntityManagerFactory("PierwszaAplikacja");
EntityManager em = emf.createEntityManager();
Uzytkownik u = em.find(Uzytkownik.class, 1);
res.getWriter().println(u.getImie() + " " + u.getNazwisko() + "\n");
em.close();
emf.close();
}
```
Of course I have my persistence.xml in root in META-INF. Maybe anyone can help me with that issue? | 2015/06/18 | [
"https://Stackoverflow.com/questions/30916718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5024224/"
]
| You're gonna need to extend the `HtmlHelper` class with the following:
```
public static MvcHtmlString HelpTextFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expr)
{
var memberExpr = expr.Body as MemberExpression;
if (memberExpr != null)
{
var helpAttr = memberExpr.Member.GetCustomAttributes(false).OfType<HelpTextAttribute>().SingleOrDefault();
if (helpAttr != null)
return new MvcHtmlString(@"<span class=""help"">" + helpAttr.Text + "</span>");
}
return MvcHtmlString.Empty;
}
```
Then use it as requested:
```
@Html.HelpTextFor(m => m.MemberNo)
```
Also, be sure to mark your `HelpTextAttribute` with the `public` modifier. | About localizing the string (I cannot comment because I do not have enough points yet)
Add the following attributes to your HelpTextAttribute
```
public string ResourceName { get; set; }
public Type ResourceType { get; set; }
```
and then adjust the HelpTextFor as follows:
```
var helpAttr = memberExpr.Member.GetCustomAttributes(false).OfType<HelpTextAttribute>().SingleOrDefault();
Assembly resourceAssembly = helpAttr.ResourceType.Assembly;
string[] manifests = resourceAssembly.GetManifestResourceNames();
// remove .resources
for (int i = 0; i < manifests.Length; i++)
{
manifests[i] = manifests[i].Replace(".resources", string.Empty);
}
string manifest = manifests.Where(m => m.EndsWith(helpAttr.ResourceType.FullName)).First();
ResourceManager manager = new ResourceManager(manifest, resourceAssembly);
if (helpAttr != null)
return new MvcHtmlString(@"<span class=""help"">" + manager.GetString(helpAttr.ResourceName) + "</span>");
```
Please see the following link on why to remove .resources
[C# - Cannot getting a string from ResourceManager (from satellite assembly)](https://stackoverflow.com/questions/5246584/c-sharp-cannot-getting-a-string-from-resourcemanager-from-satellite-assembly)
Best regards
Dominic Rooijackers
.NET software developer |
39,469,608 | How to run controller from the sub folder in codeigniter.
I have tried but i get the following error bellow.
[](https://i.stack.imgur.com/wruhe.png) | 2016/09/13 | [
"https://Stackoverflow.com/questions/39469608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6661902/"
]
| You can do this by following below steps:
Stpep 1) create sub-folder `"superadmin"` in controllers folder like below:
```
controllers/superadmin
```
Stpep 2) create controller `controllers/superadmin/loginvalueget.php` in sub-folder `"superadmin"` like below:
```
<?php
class Loginvalueget extends CI_Controller {
function index()
{
die('hello world');
}
}
?>
```
Step 3) change default controller route in `application/config/routes.php` like below:
```
$route['default_controller'] = 'superadmin/loginvalueget';
```
Step 4) replace \_set\_default\_controller() with below method in `system/core/Router.php`:
```
protected function _set_default_controller()
{
if (empty($this->default_controller))
{
show_error('Unable to determine what should be displayed. A default route has not been specified in the routing file.');
}
// Is the method being specified?
$x = explode('/', $this->default_controller);
$dir = APPPATH.'controllers';
$dir_arr = array();
foreach($x as $key => $val){
if(!is_dir($dir.'/'.$val)){
if(file_exists($dir.'/'.ucfirst($val).'.php')){
$class = $val;
if(array_key_exists(($key+1), $x)){
$method = $x[$key+1];
}else{
$method = 'index';
}
}else{
show_error('Not found specified default controller : '. $this->default_controller);
}
break;
}
$dir_arr[] = $val;
$dir = $dir.'/'.$val;
}
//set directory
$this->set_directory(implode('/', $dir_arr));
$this->set_class($class);
$this->set_method($method);
// Assign routed segments, index starting from 1
$this->uri->rsegments = array(
1 => $class,
2 => $method
);
log_message('debug', 'No URI present. Default controller set.');
}
``` | As you can see yourself in the attachment, you haven't set the route. You can do this by setting route path in "application>config>routes.php". |
10,560,622 | I have searched many articles but I could not find one appropriate. I am trying to take input form user a multiple line text and show them as it is. I am using textarea tag, but the page is not working the input values are showed in one line even it I press enter an start a new line.
Please help me fixing this. | 2012/05/12 | [
"https://Stackoverflow.com/questions/10560622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1403801/"
]
| Use [`nl2br()`](http://us3.php.net/manual/en/function.nl2br.php) when echoing the output. | Already mentioned `nl2br()` is one way;
another way is to echo the output within `<pre> .. </pre>` HTML tags. |
63,217,004 | I am trying to plot the S-shape cumulative distribution function (cdf) curve of a normal distribution. However, I ended up with a uniform distribution. What am I doing wrong?
**Test Script**
```
import numpy as np
from numpy.random import default_rng
from scipy.stats import norm
import matplotlib.pyplot as plt
siz = 1000
rg = default_rng( 12345 )
a = rg.random(size=siz)
rg = default_rng( 12345 )
b = norm.rvs(size=siz, random_state=rg)
c = norm.cdf(b)
print( 'a = ', a)
print( 'b = ', b)
print( 'c = ', c)
fig, ax = plt.subplots(3, 1)
acount, abins, aignored = ax[0].hist( a, bins=20, histtype='bar', label='a', color='C0' )
bcount, bbins, bignored = ax[1].hist( b, bins=20, histtype='bar', label='b', color='C1' )
ccount, cbins, cignored = ax[2].hist( c, bins=20, histtype='bar', label='c', color='C2' )
print( 'acount, abins, aignored = ', acount, abins, aignored)
print( 'bcount, bbins, bignored = ', bcount, bbins, bignored)
print( 'ccount, cbins, cignored = ', ccount, cbins, cignored)
ax[0].legend()
ax[1].legend()
ax[2].legend()
plt.show()
```
[](https://i.stack.imgur.com/TShKL.png) | 2020/08/02 | [
"https://Stackoverflow.com/questions/63217004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5722359/"
]
| Now I don't know your particular application. But I think the problem lies in that you are creating the values of the cdf for a number of normally distributed random numbers.
Below you can see a code example which plots the CDF of a standard normal from -3 to +3
```
import numpy as np
from scipy.stats import norm
import matplotlib.pyplot as plt
x = np.arange(-3, 3, 0.1)
c = norm.cdf(x)
plt.plot(x, c)
plt.show()
```
CDF of standard normal
 | You are plotting the wrong values.
when you do `b = norm.rvs(size=siz, random_state=rg)`, what you get is a 10 independently drawn random samples from standard normal distribution, i.e., `z` values
hence their histogram is what you see as bell shaped curve.
`norm.cdf` returns the `cfd` value at a given z value. If you want cdf's S curve, you can draw uniformly from -3 to 3 z values and get their cdf values at all points . then you plot the output probability values.
EDIT: The other answer gives code for this approach so I won't bother adding again. |
63,217,004 | I am trying to plot the S-shape cumulative distribution function (cdf) curve of a normal distribution. However, I ended up with a uniform distribution. What am I doing wrong?
**Test Script**
```
import numpy as np
from numpy.random import default_rng
from scipy.stats import norm
import matplotlib.pyplot as plt
siz = 1000
rg = default_rng( 12345 )
a = rg.random(size=siz)
rg = default_rng( 12345 )
b = norm.rvs(size=siz, random_state=rg)
c = norm.cdf(b)
print( 'a = ', a)
print( 'b = ', b)
print( 'c = ', c)
fig, ax = plt.subplots(3, 1)
acount, abins, aignored = ax[0].hist( a, bins=20, histtype='bar', label='a', color='C0' )
bcount, bbins, bignored = ax[1].hist( b, bins=20, histtype='bar', label='b', color='C1' )
ccount, cbins, cignored = ax[2].hist( c, bins=20, histtype='bar', label='c', color='C2' )
print( 'acount, abins, aignored = ', acount, abins, aignored)
print( 'bcount, bbins, bignored = ', bcount, bbins, bignored)
print( 'ccount, cbins, cignored = ', ccount, cbins, cignored)
ax[0].legend()
ax[1].legend()
ax[2].legend()
plt.show()
```
[](https://i.stack.imgur.com/TShKL.png) | 2020/08/02 | [
"https://Stackoverflow.com/questions/63217004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5722359/"
]
| To plot the sigmoidal result of the CDF of the normally distributed random variates, I should not have used matplotlib's `hist()` function. Rather, I could have used the `bar()` function to plot my results.
[@Laaggan](https://stackoverflow.com/a/63217196/5722359) and [@dumbPy](https://stackoverflow.com/a/63217209/5722359) answer stated that using regularised and ordered x value is the way to derive the sigmoidal cdf curve. Though commonly done, it isn't applicable when random variates are used. I have compared the solutions of the approach that they had mentioned with what I have done to show that both approaches give the same result. However, my results (see below figure) do show that the usual approach of getting the cdf values goes yield more occurrences of the extreme values of a normal distribution than by using random variates. Excluding the two extremes, occurrences appear uniformly distributed.
I have revised my script and provided comments to demonstrate how I compared the two approaches. I hope my answer can benefit others who are learning to use the `rvs()`, `pdf()`, and `cdf()` functions of the `scipy.stats.norm` class.
```
import numpy as np
from numpy.random import default_rng
from scipy.stats import norm
import matplotlib.pyplot as plt
mu = 0
sigma = 1
samples = 1000
rg = default_rng( 12345 )
a = rg.random(size=samples) #Get a uniform distribution of numbers in the range of 0 to 1.
print( 'a = ', a)
# Get pdf and cdf values using normal random variates.
rg = default_rng( 12345 ) #Recreate Bit Generator to ensure a same starting point
b_pdf = norm.rvs( loc=mu, scale=sigma, size=samples, random_state=rg ) #Get pdf of normal distribution(mu=0, sigma=1 gives -3.26 to +3.26).
b_cdf = norm.cdf( b_pdf, loc=mu, scale=sigma ) #get cdf of normal distribution using pdf values (always gives between 0 to 1).
print( 'b_pdf = ', b_pdf)
print( 'b_cdf = ', b_cdf)
#To check b is normally distributed. Using the ordered x (commonly practiced):
c_x = np.linspace( mu - 3.26*sigma, mu + 3.26*sigma, samples )
c_pdf = norm.pdf( c_x, loc=mu, scale=sigma )
c_cdf = norm.cdf( c_x, loc=mu, scale=sigma )
print( 'c_x = ', c_x )
print( 'c_pdf = ', c_pdf )
print( 'c_cdf = ', c_cdf )
fig, ax = plt.subplots(3, 1)
bins=np.linspace( 0, 1, num=10 )
acount, abins, aignored = ax[0].hist( a, bins=50, histtype='bar', label='a', color='C0', alpha=0.2, density=True )
bcount, bbins, bignored = ax[0].hist( b_cdf, bins=50, histtype='bar', label='b_cdf', color='C1', alpha=0.2, density=True )
ccount, cbins, cignored = ax[0].hist( c_cdf, bins=50, histtype='bar', label='c_cdf', color='C2', alpha=0.2, density=True )
bcount, bbins, bignored = ax[1].hist( b_pdf, bins=20, histtype='bar', label='b_pdf', color='C1', alpha=0.4, density=True )
cpdf_line = ax[1].plot(c_x, c_pdf, label='c_pdf', color='C2')
bpdf_bar = ax[2].bar( b_pdf, b_cdf, label='b_cdf', color='C1', alpha=0.4, width=0.01)
ccdf_line = ax[2].plot(c_x, c_cdf, label='c_cdf', color='C2')
print( 'acount, abins, aignored = ', acount, abins, aignored)
print( 'bcount, bbins, bignored = ', bcount, bbins, bignored)
print( 'ccount, cbins, cignored = ', ccount, cbins, cignored)
ax[0].legend(loc='upper left')
ax[1].legend(loc='upper left')
ax[2].legend(loc='upper left')
plt.show()
```
[](https://i.stack.imgur.com/zQzmm.png) | Now I don't know your particular application. But I think the problem lies in that you are creating the values of the cdf for a number of normally distributed random numbers.
Below you can see a code example which plots the CDF of a standard normal from -3 to +3
```
import numpy as np
from scipy.stats import norm
import matplotlib.pyplot as plt
x = np.arange(-3, 3, 0.1)
c = norm.cdf(x)
plt.plot(x, c)
plt.show()
```
CDF of standard normal
 |
63,217,004 | I am trying to plot the S-shape cumulative distribution function (cdf) curve of a normal distribution. However, I ended up with a uniform distribution. What am I doing wrong?
**Test Script**
```
import numpy as np
from numpy.random import default_rng
from scipy.stats import norm
import matplotlib.pyplot as plt
siz = 1000
rg = default_rng( 12345 )
a = rg.random(size=siz)
rg = default_rng( 12345 )
b = norm.rvs(size=siz, random_state=rg)
c = norm.cdf(b)
print( 'a = ', a)
print( 'b = ', b)
print( 'c = ', c)
fig, ax = plt.subplots(3, 1)
acount, abins, aignored = ax[0].hist( a, bins=20, histtype='bar', label='a', color='C0' )
bcount, bbins, bignored = ax[1].hist( b, bins=20, histtype='bar', label='b', color='C1' )
ccount, cbins, cignored = ax[2].hist( c, bins=20, histtype='bar', label='c', color='C2' )
print( 'acount, abins, aignored = ', acount, abins, aignored)
print( 'bcount, bbins, bignored = ', bcount, bbins, bignored)
print( 'ccount, cbins, cignored = ', ccount, cbins, cignored)
ax[0].legend()
ax[1].legend()
ax[2].legend()
plt.show()
```
[](https://i.stack.imgur.com/TShKL.png) | 2020/08/02 | [
"https://Stackoverflow.com/questions/63217004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5722359/"
]
| To plot the sigmoidal result of the CDF of the normally distributed random variates, I should not have used matplotlib's `hist()` function. Rather, I could have used the `bar()` function to plot my results.
[@Laaggan](https://stackoverflow.com/a/63217196/5722359) and [@dumbPy](https://stackoverflow.com/a/63217209/5722359) answer stated that using regularised and ordered x value is the way to derive the sigmoidal cdf curve. Though commonly done, it isn't applicable when random variates are used. I have compared the solutions of the approach that they had mentioned with what I have done to show that both approaches give the same result. However, my results (see below figure) do show that the usual approach of getting the cdf values goes yield more occurrences of the extreme values of a normal distribution than by using random variates. Excluding the two extremes, occurrences appear uniformly distributed.
I have revised my script and provided comments to demonstrate how I compared the two approaches. I hope my answer can benefit others who are learning to use the `rvs()`, `pdf()`, and `cdf()` functions of the `scipy.stats.norm` class.
```
import numpy as np
from numpy.random import default_rng
from scipy.stats import norm
import matplotlib.pyplot as plt
mu = 0
sigma = 1
samples = 1000
rg = default_rng( 12345 )
a = rg.random(size=samples) #Get a uniform distribution of numbers in the range of 0 to 1.
print( 'a = ', a)
# Get pdf and cdf values using normal random variates.
rg = default_rng( 12345 ) #Recreate Bit Generator to ensure a same starting point
b_pdf = norm.rvs( loc=mu, scale=sigma, size=samples, random_state=rg ) #Get pdf of normal distribution(mu=0, sigma=1 gives -3.26 to +3.26).
b_cdf = norm.cdf( b_pdf, loc=mu, scale=sigma ) #get cdf of normal distribution using pdf values (always gives between 0 to 1).
print( 'b_pdf = ', b_pdf)
print( 'b_cdf = ', b_cdf)
#To check b is normally distributed. Using the ordered x (commonly practiced):
c_x = np.linspace( mu - 3.26*sigma, mu + 3.26*sigma, samples )
c_pdf = norm.pdf( c_x, loc=mu, scale=sigma )
c_cdf = norm.cdf( c_x, loc=mu, scale=sigma )
print( 'c_x = ', c_x )
print( 'c_pdf = ', c_pdf )
print( 'c_cdf = ', c_cdf )
fig, ax = plt.subplots(3, 1)
bins=np.linspace( 0, 1, num=10 )
acount, abins, aignored = ax[0].hist( a, bins=50, histtype='bar', label='a', color='C0', alpha=0.2, density=True )
bcount, bbins, bignored = ax[0].hist( b_cdf, bins=50, histtype='bar', label='b_cdf', color='C1', alpha=0.2, density=True )
ccount, cbins, cignored = ax[0].hist( c_cdf, bins=50, histtype='bar', label='c_cdf', color='C2', alpha=0.2, density=True )
bcount, bbins, bignored = ax[1].hist( b_pdf, bins=20, histtype='bar', label='b_pdf', color='C1', alpha=0.4, density=True )
cpdf_line = ax[1].plot(c_x, c_pdf, label='c_pdf', color='C2')
bpdf_bar = ax[2].bar( b_pdf, b_cdf, label='b_cdf', color='C1', alpha=0.4, width=0.01)
ccdf_line = ax[2].plot(c_x, c_cdf, label='c_cdf', color='C2')
print( 'acount, abins, aignored = ', acount, abins, aignored)
print( 'bcount, bbins, bignored = ', bcount, bbins, bignored)
print( 'ccount, cbins, cignored = ', ccount, cbins, cignored)
ax[0].legend(loc='upper left')
ax[1].legend(loc='upper left')
ax[2].legend(loc='upper left')
plt.show()
```
[](https://i.stack.imgur.com/zQzmm.png) | You are plotting the wrong values.
when you do `b = norm.rvs(size=siz, random_state=rg)`, what you get is a 10 independently drawn random samples from standard normal distribution, i.e., `z` values
hence their histogram is what you see as bell shaped curve.
`norm.cdf` returns the `cfd` value at a given z value. If you want cdf's S curve, you can draw uniformly from -3 to 3 z values and get their cdf values at all points . then you plot the output probability values.
EDIT: The other answer gives code for this approach so I won't bother adding again. |
51,014,512 | What way is more convenient to set image from my app assets in my app Image View? I have two ways: the first one is function UIImage(named: String) or UIImage and both is working for me, but I want to know which one is the best ,so I can use one in the future
here is two examples
```
// first
let myImages1 = ["dice1", "dice2", "dice3", "dice4", "dice5", "dice6"]
@IBOutlet weak var diceImageView1: UIImageView!
diceImageView1.image = UIImage(named: myImages1[index1])
// second
let myImages2 = [ image1, image2, image3, image4, image5, image6 ]
@IBOutlet weak var diceImageView2: UIImageView!
diceImageView2.image = myImages2[index2]
``` | 2018/06/24 | [
"https://Stackoverflow.com/questions/51014512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7374351/"
]
| We're using Images from assets catalog instead String names. It's the better way to set UIImage. But from swift 4.2 we can't use asset names anymore.
We should use image literal.
Here's the example:
```
let logoImageView: UIImageView = {
let iv = UIImageView()
// Set image with image literal
iv.image = #imageLiteral(resourceName: "feedback")
return iv
}()
```
Look at the screenshot below.
[](https://i.stack.imgur.com/zg0rq.png)
After you've typed `Image Literal` you can double click on that and choose your image from assets catalog. Here is the screenshot.
[](https://i.stack.imgur.com/E34hI.png)
But last time I use this lib R.swift. Get strong typed, autocompleted resources like images, fonts and segues in Swift projects.
How it looks in code:
[](https://i.stack.imgur.com/Rd8rJ.png) | You can create an extension for UIImage and have static variables holding your images.
```
extension UIImage {
static var dice1: UIImage? {
return UIImage(named: "dice1")
}
}
let imageView = UIImageView()
imageView.image = UIImage.dice1
```
Or you can use image literals in Xcode which are nice because you can see the actual image[](https://i.stack.imgur.com/I7JHn.png) |
48,285,834 | In oracle DB I have a table say T which has columns id, att1, att2, att3. Now i also have a CSV file which has lots of id's in it along with one additional parameter.How to insert att2 corresponding to each id in the DB.
initially, csv is like
```
id, random
id, random
.
.
```
i.e after running the PL/SQL script csv file will look like:
```
id, random, att2
id, random, att2
.
.
.
``` | 2018/01/16 | [
"https://Stackoverflow.com/questions/48285834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3767047/"
]
| I think the concept that you like to use are `interceptors`.
In `vue-resource` you can define them for `request` and `response`.
An example for a interceptor:
```
Vue.http.interceptors.push(function(request, next) {
// modify request ...
// stop and return response
next(request.respondWith(body, {
status: 404,
statusText: 'Not found'
}));
});
``` | Thanks to [C Sharper](https://stackoverflow.com/users/1487681/c-sharper) for the very good start point.
I've wrote here my final solution for posterity.
I've checked the `response` status in the interceptor and if it isn't `ok`, it will show a message to end-user, using the `$alert()` function.
Here the code:
```
Vue.http.interceptors.push(function(request, next) {
next((response) => {
if (!response.ok) {
let message = "<summary>Unexpected error</summary><details>Error: " + response.status + " " + response.url + "</details>";
this.$alert(message, 'Error', {
"type" : "error",
"dangerouslyUseHTMLString" : "true"
});
}
return response;
});
}
``` |
8,436,515 | I have a DataTable that contains 4 rows. I want to compare a value in one column in row 1 with the value in row 2. Something similar to this:
```
For Each row As DataRow in drRows
If row("column") <> row("column") 'I want the second row("column") to be the next row.
'do something else
End If
Next
``` | 2011/12/08 | [
"https://Stackoverflow.com/questions/8436515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33690/"
]
| You can always access a `DataRow` with its index ([`DataRowCollection.Item`](http://msdn.microsoft.com/en-us/library/system.data.datarowcollection.item.aspx)):
```
For i As Integer = 0 To tbl.Rows.Count - 1
Dim row As DataRow = tbl.Rows(i)
If i <> tbl.Rows.Count - 1 Then
Dim nextRow As DataRow = tbl(i + 1)
If row("column").Equals(nextRow("column")) Then
'do something"
End If
End If
Next
``` | Say you have the following table:
```none
A B C D
1 2 3 4
5 6 7 8
9 10 11 12
12 12 13 14
```
```
For i As Integer = 0 To dt.Rows.Count - 2
If dt.Rows(i)("ColName") <> dt.Rows(i + 1)("ColName") Then
'Do something
End If
Next
``` |
8,436,515 | I have a DataTable that contains 4 rows. I want to compare a value in one column in row 1 with the value in row 2. Something similar to this:
```
For Each row As DataRow in drRows
If row("column") <> row("column") 'I want the second row("column") to be the next row.
'do something else
End If
Next
``` | 2011/12/08 | [
"https://Stackoverflow.com/questions/8436515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33690/"
]
| You can always access a `DataRow` with its index ([`DataRowCollection.Item`](http://msdn.microsoft.com/en-us/library/system.data.datarowcollection.item.aspx)):
```
For i As Integer = 0 To tbl.Rows.Count - 1
Dim row As DataRow = tbl.Rows(i)
If i <> tbl.Rows.Count - 1 Then
Dim nextRow As DataRow = tbl(i + 1)
If row("column").Equals(nextRow("column")) Then
'do something"
End If
End If
Next
``` | You keep track of the last item:
```
Dim last As DataRow = Nothing
For Each row As DataRow In drRows
If last IsNot Nothing Then
' Compare last with row
End If
last = row
Next
``` |
8,436,515 | I have a DataTable that contains 4 rows. I want to compare a value in one column in row 1 with the value in row 2. Something similar to this:
```
For Each row As DataRow in drRows
If row("column") <> row("column") 'I want the second row("column") to be the next row.
'do something else
End If
Next
``` | 2011/12/08 | [
"https://Stackoverflow.com/questions/8436515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33690/"
]
| You keep track of the last item:
```
Dim last As DataRow = Nothing
For Each row As DataRow In drRows
If last IsNot Nothing Then
' Compare last with row
End If
last = row
Next
``` | Say you have the following table:
```none
A B C D
1 2 3 4
5 6 7 8
9 10 11 12
12 12 13 14
```
```
For i As Integer = 0 To dt.Rows.Count - 2
If dt.Rows(i)("ColName") <> dt.Rows(i + 1)("ColName") Then
'Do something
End If
Next
``` |
10,333,503 | So I started using Git together with [this workflow](http://nvie.com/posts/a-successful-git-branching-model/) to make a personal website (mostly for testing and to learn Git) and I am developing it locally on my laptop using Xampp.
But now I would like to make this website public and upload it to my webserver. Problem is, I use a shared hosting plan which means I only have FTP access to my website directory. Can't use SSH or install Git or anything..
I would like to deploy the website and any updates to that webserver, but I was wondering if that was possible with Git with only FTP access? And if not, what would be an advisable way to update my website? Manually drag an dropping files through Filezilla can get a bit tedious. | 2012/04/26 | [
"https://Stackoverflow.com/questions/10333503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1356391/"
]
| If you have no SSH access to the remote server and the hosting provider doesn't offer a git deploy feature, you won't be able to deploy directly using git.
However, it's always a good idea to track your source code regardless the remote options.
In your case, a good alternative to automate the release process would be to create a simple deploy script in your favorite programming language (Ruby, Python, Bash...) that loads the list of changed files from your git repository and performs an upload via FTP of these files.
A simple search for [git-ftp](https://www.google.com/search?sugexp=chrome,mod=0&ix=nh&sourceid=chrome&ie=UTF-8&q=git-ftp) reveals that there are already two projects that seems to do what I suggested:
* [ezyang/git-ftp](https://github.com/ezyang/git-ftp)
* [git-ftp/git-ftp](https://github.com/git-ftp/git-ftp) | If you are in a shared hosting plan, its not a good idea to host your own git server as you'll have both space and bandwidth limitations. You can look out for other options such as [github](http://github.com) or if you want to have a private hosting, there is [bitbucket](http://bitbucket.org) |
10,333,503 | So I started using Git together with [this workflow](http://nvie.com/posts/a-successful-git-branching-model/) to make a personal website (mostly for testing and to learn Git) and I am developing it locally on my laptop using Xampp.
But now I would like to make this website public and upload it to my webserver. Problem is, I use a shared hosting plan which means I only have FTP access to my website directory. Can't use SSH or install Git or anything..
I would like to deploy the website and any updates to that webserver, but I was wondering if that was possible with Git with only FTP access? And if not, what would be an advisable way to update my website? Manually drag an dropping files through Filezilla can get a bit tedious. | 2012/04/26 | [
"https://Stackoverflow.com/questions/10333503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1356391/"
]
| If you have no SSH access to the remote server and the hosting provider doesn't offer a git deploy feature, you won't be able to deploy directly using git.
However, it's always a good idea to track your source code regardless the remote options.
In your case, a good alternative to automate the release process would be to create a simple deploy script in your favorite programming language (Ruby, Python, Bash...) that loads the list of changed files from your git repository and performs an upload via FTP of these files.
A simple search for [git-ftp](https://www.google.com/search?sugexp=chrome,mod=0&ix=nh&sourceid=chrome&ie=UTF-8&q=git-ftp) reveals that there are already two projects that seems to do what I suggested:
* [ezyang/git-ftp](https://github.com/ezyang/git-ftp)
* [git-ftp/git-ftp](https://github.com/git-ftp/git-ftp) | Maybe think about a different hosting set up?
1. On a VPS you have more freedom but you need to set up everything yourself.
2. On a cloud PaaS you will get great technology but pay a little more.
3. As mentioned above: A private repo hoster with ftp deployment option might also work.
For me, best productivity is most important. Compare costs of web hosting with costs for web development. |
10,333,503 | So I started using Git together with [this workflow](http://nvie.com/posts/a-successful-git-branching-model/) to make a personal website (mostly for testing and to learn Git) and I am developing it locally on my laptop using Xampp.
But now I would like to make this website public and upload it to my webserver. Problem is, I use a shared hosting plan which means I only have FTP access to my website directory. Can't use SSH or install Git or anything..
I would like to deploy the website and any updates to that webserver, but I was wondering if that was possible with Git with only FTP access? And if not, what would be an advisable way to update my website? Manually drag an dropping files through Filezilla can get a bit tedious. | 2012/04/26 | [
"https://Stackoverflow.com/questions/10333503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1356391/"
]
| If you have no SSH access to the remote server and the hosting provider doesn't offer a git deploy feature, you won't be able to deploy directly using git.
However, it's always a good idea to track your source code regardless the remote options.
In your case, a good alternative to automate the release process would be to create a simple deploy script in your favorite programming language (Ruby, Python, Bash...) that loads the list of changed files from your git repository and performs an upload via FTP of these files.
A simple search for [git-ftp](https://www.google.com/search?sugexp=chrome,mod=0&ix=nh&sourceid=chrome&ie=UTF-8&q=git-ftp) reveals that there are already two projects that seems to do what I suggested:
* [ezyang/git-ftp](https://github.com/ezyang/git-ftp)
* [git-ftp/git-ftp](https://github.com/git-ftp/git-ftp) | If git is installed on the server (e.g `<?php $last_line = system('git --version', $retval); ?>`), but you don't have SSH access, perhaps try [php-git-bundle](https://bitbucket.org/jwerner/php-git-bundle). |
10,333,503 | So I started using Git together with [this workflow](http://nvie.com/posts/a-successful-git-branching-model/) to make a personal website (mostly for testing and to learn Git) and I am developing it locally on my laptop using Xampp.
But now I would like to make this website public and upload it to my webserver. Problem is, I use a shared hosting plan which means I only have FTP access to my website directory. Can't use SSH or install Git or anything..
I would like to deploy the website and any updates to that webserver, but I was wondering if that was possible with Git with only FTP access? And if not, what would be an advisable way to update my website? Manually drag an dropping files through Filezilla can get a bit tedious. | 2012/04/26 | [
"https://Stackoverflow.com/questions/10333503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1356391/"
]
| If you have no SSH access to the remote server and the hosting provider doesn't offer a git deploy feature, you won't be able to deploy directly using git.
However, it's always a good idea to track your source code regardless the remote options.
In your case, a good alternative to automate the release process would be to create a simple deploy script in your favorite programming language (Ruby, Python, Bash...) that loads the list of changed files from your git repository and performs an upload via FTP of these files.
A simple search for [git-ftp](https://www.google.com/search?sugexp=chrome,mod=0&ix=nh&sourceid=chrome&ie=UTF-8&q=git-ftp) reveals that there are already two projects that seems to do what I suggested:
* [ezyang/git-ftp](https://github.com/ezyang/git-ftp)
* [git-ftp/git-ftp](https://github.com/git-ftp/git-ftp) | This question may be old but there is a shared web hosting which offers git deployment option and SSH access to git pull/push etc: [githoster.com](http://githoster.com)
Or there are some scripts you can search in google which will link your github account to your host with git hooks. |
10,333,503 | So I started using Git together with [this workflow](http://nvie.com/posts/a-successful-git-branching-model/) to make a personal website (mostly for testing and to learn Git) and I am developing it locally on my laptop using Xampp.
But now I would like to make this website public and upload it to my webserver. Problem is, I use a shared hosting plan which means I only have FTP access to my website directory. Can't use SSH or install Git or anything..
I would like to deploy the website and any updates to that webserver, but I was wondering if that was possible with Git with only FTP access? And if not, what would be an advisable way to update my website? Manually drag an dropping files through Filezilla can get a bit tedious. | 2012/04/26 | [
"https://Stackoverflow.com/questions/10333503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1356391/"
]
| If you are in a shared hosting plan, its not a good idea to host your own git server as you'll have both space and bandwidth limitations. You can look out for other options such as [github](http://github.com) or if you want to have a private hosting, there is [bitbucket](http://bitbucket.org) | If git is installed on the server (e.g `<?php $last_line = system('git --version', $retval); ?>`), but you don't have SSH access, perhaps try [php-git-bundle](https://bitbucket.org/jwerner/php-git-bundle). |
10,333,503 | So I started using Git together with [this workflow](http://nvie.com/posts/a-successful-git-branching-model/) to make a personal website (mostly for testing and to learn Git) and I am developing it locally on my laptop using Xampp.
But now I would like to make this website public and upload it to my webserver. Problem is, I use a shared hosting plan which means I only have FTP access to my website directory. Can't use SSH or install Git or anything..
I would like to deploy the website and any updates to that webserver, but I was wondering if that was possible with Git with only FTP access? And if not, what would be an advisable way to update my website? Manually drag an dropping files through Filezilla can get a bit tedious. | 2012/04/26 | [
"https://Stackoverflow.com/questions/10333503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1356391/"
]
| If you are in a shared hosting plan, its not a good idea to host your own git server as you'll have both space and bandwidth limitations. You can look out for other options such as [github](http://github.com) or if you want to have a private hosting, there is [bitbucket](http://bitbucket.org) | This question may be old but there is a shared web hosting which offers git deployment option and SSH access to git pull/push etc: [githoster.com](http://githoster.com)
Or there are some scripts you can search in google which will link your github account to your host with git hooks. |
10,333,503 | So I started using Git together with [this workflow](http://nvie.com/posts/a-successful-git-branching-model/) to make a personal website (mostly for testing and to learn Git) and I am developing it locally on my laptop using Xampp.
But now I would like to make this website public and upload it to my webserver. Problem is, I use a shared hosting plan which means I only have FTP access to my website directory. Can't use SSH or install Git or anything..
I would like to deploy the website and any updates to that webserver, but I was wondering if that was possible with Git with only FTP access? And if not, what would be an advisable way to update my website? Manually drag an dropping files through Filezilla can get a bit tedious. | 2012/04/26 | [
"https://Stackoverflow.com/questions/10333503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1356391/"
]
| Maybe think about a different hosting set up?
1. On a VPS you have more freedom but you need to set up everything yourself.
2. On a cloud PaaS you will get great technology but pay a little more.
3. As mentioned above: A private repo hoster with ftp deployment option might also work.
For me, best productivity is most important. Compare costs of web hosting with costs for web development. | If git is installed on the server (e.g `<?php $last_line = system('git --version', $retval); ?>`), but you don't have SSH access, perhaps try [php-git-bundle](https://bitbucket.org/jwerner/php-git-bundle). |
10,333,503 | So I started using Git together with [this workflow](http://nvie.com/posts/a-successful-git-branching-model/) to make a personal website (mostly for testing and to learn Git) and I am developing it locally on my laptop using Xampp.
But now I would like to make this website public and upload it to my webserver. Problem is, I use a shared hosting plan which means I only have FTP access to my website directory. Can't use SSH or install Git or anything..
I would like to deploy the website and any updates to that webserver, but I was wondering if that was possible with Git with only FTP access? And if not, what would be an advisable way to update my website? Manually drag an dropping files through Filezilla can get a bit tedious. | 2012/04/26 | [
"https://Stackoverflow.com/questions/10333503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1356391/"
]
| Maybe think about a different hosting set up?
1. On a VPS you have more freedom but you need to set up everything yourself.
2. On a cloud PaaS you will get great technology but pay a little more.
3. As mentioned above: A private repo hoster with ftp deployment option might also work.
For me, best productivity is most important. Compare costs of web hosting with costs for web development. | This question may be old but there is a shared web hosting which offers git deployment option and SSH access to git pull/push etc: [githoster.com](http://githoster.com)
Or there are some scripts you can search in google which will link your github account to your host with git hooks. |
71,199,771 | ```
// program to count down numbers to 1
function countDown(number) {
// display the number
console.log(number);
// decrease the number value
const newNumber = number - 1;
// base case
if (newNumber > 0) {
countDown(newNumber);
}
console.log(newNumber);
}
countDown(4);
// output => 4 3 2 1 0 1 2 3
```
I can't visualize what happens after the if condition. I mean I understand that there is "loop" with countDown(newNumber). But I don't understand why there is the output 0 1 2 3. I know I can put an else keyword, but I'd like to understand why JS engine after finishing the recursion it prints four times console.log(newNumber). | 2022/02/20 | [
"https://Stackoverflow.com/questions/71199771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11586735/"
]
| Your recursive call does not end the execution of the function.
So what happens is that if you call `newNumber(2)` it executes the first console.log, logging 2. Then it assigns `newNumber` to 1. Then your recursion happens, printing 1. Inside the recursive call newNumber becomes 0, so no more recursion. Instead, the second print inside the recursion prints 0.
Now your recursion returns, and the second print outside of your recursion prints the current value of `newNumber` in the non recursive call. And that is 1.
So you get 2 (outside recursion) 1 (inside) 0 (inside) 1 (outside) | You can simplify your function.
```js
function countDown(number) {
if (number > 0) {
console.log(number);
countDown(--number);
}
}
countDown(4);
``` |
71,199,771 | ```
// program to count down numbers to 1
function countDown(number) {
// display the number
console.log(number);
// decrease the number value
const newNumber = number - 1;
// base case
if (newNumber > 0) {
countDown(newNumber);
}
console.log(newNumber);
}
countDown(4);
// output => 4 3 2 1 0 1 2 3
```
I can't visualize what happens after the if condition. I mean I understand that there is "loop" with countDown(newNumber). But I don't understand why there is the output 0 1 2 3. I know I can put an else keyword, but I'd like to understand why JS engine after finishing the recursion it prints four times console.log(newNumber). | 2022/02/20 | [
"https://Stackoverflow.com/questions/71199771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11586735/"
]
| You can simplify your function.
```js
function countDown(number) {
if (number > 0) {
console.log(number);
countDown(--number);
}
}
countDown(4);
``` | this way ?
```js
countDown( 4 )
// program to count down numbers to 1
function countDown(num)
{
if (num<1) return
console.log(num)
countDown(--num)
}
``` |
71,199,771 | ```
// program to count down numbers to 1
function countDown(number) {
// display the number
console.log(number);
// decrease the number value
const newNumber = number - 1;
// base case
if (newNumber > 0) {
countDown(newNumber);
}
console.log(newNumber);
}
countDown(4);
// output => 4 3 2 1 0 1 2 3
```
I can't visualize what happens after the if condition. I mean I understand that there is "loop" with countDown(newNumber). But I don't understand why there is the output 0 1 2 3. I know I can put an else keyword, but I'd like to understand why JS engine after finishing the recursion it prints four times console.log(newNumber). | 2022/02/20 | [
"https://Stackoverflow.com/questions/71199771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11586735/"
]
| Your recursive call does not end the execution of the function.
So what happens is that if you call `newNumber(2)` it executes the first console.log, logging 2. Then it assigns `newNumber` to 1. Then your recursion happens, printing 1. Inside the recursive call newNumber becomes 0, so no more recursion. Instead, the second print inside the recursion prints 0.
Now your recursion returns, and the second print outside of your recursion prints the current value of `newNumber` in the non recursive call. And that is 1.
So you get 2 (outside recursion) 1 (inside) 0 (inside) 1 (outside) | this way ?
```js
countDown( 4 )
// program to count down numbers to 1
function countDown(num)
{
if (num<1) return
console.log(num)
countDown(--num)
}
``` |
9,704,329 | I have tested loads of HTML5 MP3 players with Flash fallback in the past month, and none seem to work on Blackberry phones (i.e. below OS 7.0, because OS 7 already has some HTML5 support). Do you know of any?
The closest I have gotten so far is for it to play but then the flash never responds when you try to pause or stop it.
P.S. I have trawled S/O posts and tried various suggestions, to no avail on BLACKBERRY phone webpages. I *dislike* duplicates as much as the next guy. | 2012/03/14 | [
"https://Stackoverflow.com/questions/9704329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572561/"
]
| Does it *have* to have a **FLASH** fallback? Because [jPlayer](http://www.jplayer.org/) seems to have good java intentions, while running in HTML5. It's open source, too, so I suppose it could have a forked flash version? (just a question, *who uses blackberry anymore anyway?*)
Best of regards,
JXP | Try the [Yahoo! WebPlayer](http://webplayer.yahoo.com/). I haven't tried it on blackberry but I've had good luck with it on every other device I've tested. I believe it used html5 if it can and has a flash fallback if it can't use html5. Hopefully it works for you. If not, sorry and good luck! |
8,347,990 | So if I have a select list of lets say dates that looks like
```
<option value="624e70cb-2796-4029-bd09-2642abaa54b4">1989</option>
<option value="ff591d9a-e8a4-4280-829b-9307b7b41912">1988</option>
<option value="f2e9e756-7c59-4883-89b5-9c8cccf85ad6">1987</option>
<option value="c65d6a65-441f-4cb5-9e6d-d9de58efb060">1986</option>
<option value="27aa2cd0-f77a-48c0-83f3-5348d5a7239f">1985</option>
<option value="50e375c0-a1fa-405e-8ec9-a3f220041a39">1984</option>
```
if I have a string that holds the value 86 is there a good way to select:
```
<option value="c65d6a65-441f-4cb5-9e6d-d9de58efb060">1986</option>
```
with jquery? | 2011/12/01 | [
"https://Stackoverflow.com/questions/8347990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/517721/"
]
| You can use google chrome. Open console by pressing F12 or inspect any element, in right-bottom corner click on gear icon, then go to "overrides" where you can enable "Emulate touch events". Your mouse clicks will be like touches.
Notice: unbind/remove any pc's click events like onclick,onmousedown,.click and .ect because in this mode will works both of touch and click events.
 | One possible way is to [install the Android SDK](http://developer.android.com/sdk/installing.html) and use the browser in the emulator. I'd advise an Android 2.x image as emulation is a bit slow, especially the 3.x and 4.0 images. |
8,347,990 | So if I have a select list of lets say dates that looks like
```
<option value="624e70cb-2796-4029-bd09-2642abaa54b4">1989</option>
<option value="ff591d9a-e8a4-4280-829b-9307b7b41912">1988</option>
<option value="f2e9e756-7c59-4883-89b5-9c8cccf85ad6">1987</option>
<option value="c65d6a65-441f-4cb5-9e6d-d9de58efb060">1986</option>
<option value="27aa2cd0-f77a-48c0-83f3-5348d5a7239f">1985</option>
<option value="50e375c0-a1fa-405e-8ec9-a3f220041a39">1984</option>
```
if I have a string that holds the value 86 is there a good way to select:
```
<option value="c65d6a65-441f-4cb5-9e6d-d9de58efb060">1986</option>
```
with jquery? | 2011/12/01 | [
"https://Stackoverflow.com/questions/8347990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/517721/"
]
| If it's still actual, you can use [this](https://github.com/jtangelder/faketouches.js) library to test touch events. It's used to test touch for Hammer. | One possible way is to [install the Android SDK](http://developer.android.com/sdk/installing.html) and use the browser in the emulator. I'd advise an Android 2.x image as emulation is a bit slow, especially the 3.x and 4.0 images. |
8,347,990 | So if I have a select list of lets say dates that looks like
```
<option value="624e70cb-2796-4029-bd09-2642abaa54b4">1989</option>
<option value="ff591d9a-e8a4-4280-829b-9307b7b41912">1988</option>
<option value="f2e9e756-7c59-4883-89b5-9c8cccf85ad6">1987</option>
<option value="c65d6a65-441f-4cb5-9e6d-d9de58efb060">1986</option>
<option value="27aa2cd0-f77a-48c0-83f3-5348d5a7239f">1985</option>
<option value="50e375c0-a1fa-405e-8ec9-a3f220041a39">1984</option>
```
if I have a string that holds the value 86 is there a good way to select:
```
<option value="c65d6a65-441f-4cb5-9e6d-d9de58efb060">1986</option>
```
with jquery? | 2011/12/01 | [
"https://Stackoverflow.com/questions/8347990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/517721/"
]
| You can use google chrome. Open console by pressing F12 or inspect any element, in right-bottom corner click on gear icon, then go to "overrides" where you can enable "Emulate touch events". Your mouse clicks will be like touches.
Notice: unbind/remove any pc's click events like onclick,onmousedown,.click and .ect because in this mode will works both of touch and click events.
 | `Hammer.js` library can simulate touch events on desktop devices.
<http://eightmedia.github.com/hammer.js/> |
8,347,990 | So if I have a select list of lets say dates that looks like
```
<option value="624e70cb-2796-4029-bd09-2642abaa54b4">1989</option>
<option value="ff591d9a-e8a4-4280-829b-9307b7b41912">1988</option>
<option value="f2e9e756-7c59-4883-89b5-9c8cccf85ad6">1987</option>
<option value="c65d6a65-441f-4cb5-9e6d-d9de58efb060">1986</option>
<option value="27aa2cd0-f77a-48c0-83f3-5348d5a7239f">1985</option>
<option value="50e375c0-a1fa-405e-8ec9-a3f220041a39">1984</option>
```
if I have a string that holds the value 86 is there a good way to select:
```
<option value="c65d6a65-441f-4cb5-9e6d-d9de58efb060">1986</option>
```
with jquery? | 2011/12/01 | [
"https://Stackoverflow.com/questions/8347990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/517721/"
]
| If it's still actual, you can use [this](https://github.com/jtangelder/faketouches.js) library to test touch events. It's used to test touch for Hammer. | `Hammer.js` library can simulate touch events on desktop devices.
<http://eightmedia.github.com/hammer.js/> |
17,568,348 | I am using SuiteScript to fetch Subsidiary information. Using nlapiLookupField method I am able to see the basic fields. But I want some information on Subsidiary-Preferences tab.
It seems nlapiLookupField cannot access fields on a subtab (Preferences). | 2013/07/10 | [
"https://Stackoverflow.com/questions/17568348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/665836/"
]
| These fields are not even listed in [SuiteScript Records Browser](https://system.netsuite.com/help/helpcenter/en_US/RecordsBrowser/2013_1/index.html).
One way to read them is by loading the record eg:
```
var rec = nlapiLoadRecord('subsidiary', 11);
rec.getFieldValue('CHECKTYPE');
``` | Open the record inside the NetSuite UI. Append '&xml=T' to the end of the url for the record.
Take a look at the underlying XML data - that should be everything you see in the UI, and you will see the field names, sublists, etc. |
3,767,128 | In my page, I'm using a javascript function
```
<script>
function redirect(){
window.location="hurray.php";
}
</script>
```
Calling the function from the line below.
```
<input id="search_box" name="textbox" type="text" size="50" maxlength="100" onkeypress="redirect()" />
```
Now I want to make it sure that the page 'hurray.php' is visited only from this action. If I typed the direct URL to 'hurray' page, I should not be able to visit this page, rather redirect it to this previous page. | 2010/09/22 | [
"https://Stackoverflow.com/questions/3767128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383393/"
]
| Make an AJAX call to a PHP function that will set a variable in the session. When the AJAX call returns response redirect the user to this page and check for the session variable. You can delete it if you do not want the user to be able to visit it again for this session. | You cannot do this using javascript alone, I don't think.
You need to intercept this on the server and handle it accordingly.
Your probably going to need a token to be sent along with the redirect, you can then validate this token server side and allow the redirect to complete or do some other action if the user has been sent there in error or by typing in the URL directly.
Why are you wanting to do this in the example you give? Surely this would lead the user away from the search form and to another page? |
3,767,128 | In my page, I'm using a javascript function
```
<script>
function redirect(){
window.location="hurray.php";
}
</script>
```
Calling the function from the line below.
```
<input id="search_box" name="textbox" type="text" size="50" maxlength="100" onkeypress="redirect()" />
```
Now I want to make it sure that the page 'hurray.php' is visited only from this action. If I typed the direct URL to 'hurray' page, I should not be able to visit this page, rather redirect it to this previous page. | 2010/09/22 | [
"https://Stackoverflow.com/questions/3767128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383393/"
]
| You cannot do this using javascript alone, I don't think.
You need to intercept this on the server and handle it accordingly.
Your probably going to need a token to be sent along with the redirect, you can then validate this token server side and allow the redirect to complete or do some other action if the user has been sent there in error or by typing in the URL directly.
Why are you wanting to do this in the example you give? Surely this would lead the user away from the search form and to another page? | Does your example contain real code, or have you just included someething that's made up to make the question simpler to ask?
It seems a strange thing to do - providing the user with a search box and then, as soon as they start typing, redirect them to another page.
If you are doing a search, and you only want the earch page to be triggered from a form, rather than by the user typing in the URL, then consider setting the form method to 'POST' and checking for this on the search page. If the method is 'GET', then the URL was typed manually, and you can redirect back to the original page.
Admittedly, this technically violates the recommendations for the use of 'POST', which should only be for operations that change information, rather than 'GET' which should be used when asking for information. However, this is one occasion where this might be excusable.
Another approach that you could use is to generate a unique key of some kind, and store this in a hidden field of the form, the check for this before deciding whether to redirect to the original page. This would require some kind of reliable key generation scheme, making it slightly trickier, but not impossible. |
3,767,128 | In my page, I'm using a javascript function
```
<script>
function redirect(){
window.location="hurray.php";
}
</script>
```
Calling the function from the line below.
```
<input id="search_box" name="textbox" type="text" size="50" maxlength="100" onkeypress="redirect()" />
```
Now I want to make it sure that the page 'hurray.php' is visited only from this action. If I typed the direct URL to 'hurray' page, I should not be able to visit this page, rather redirect it to this previous page. | 2010/09/22 | [
"https://Stackoverflow.com/questions/3767128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383393/"
]
| Make an AJAX call to a PHP function that will set a variable in the session. When the AJAX call returns response redirect the user to this page and check for the session variable. You can delete it if you do not want the user to be able to visit it again for this session. | Does your example contain real code, or have you just included someething that's made up to make the question simpler to ask?
It seems a strange thing to do - providing the user with a search box and then, as soon as they start typing, redirect them to another page.
If you are doing a search, and you only want the earch page to be triggered from a form, rather than by the user typing in the URL, then consider setting the form method to 'POST' and checking for this on the search page. If the method is 'GET', then the URL was typed manually, and you can redirect back to the original page.
Admittedly, this technically violates the recommendations for the use of 'POST', which should only be for operations that change information, rather than 'GET' which should be used when asking for information. However, this is one occasion where this might be excusable.
Another approach that you could use is to generate a unique key of some kind, and store this in a hidden field of the form, the check for this before deciding whether to redirect to the original page. This would require some kind of reliable key generation scheme, making it slightly trickier, but not impossible. |
3,767,128 | In my page, I'm using a javascript function
```
<script>
function redirect(){
window.location="hurray.php";
}
</script>
```
Calling the function from the line below.
```
<input id="search_box" name="textbox" type="text" size="50" maxlength="100" onkeypress="redirect()" />
```
Now I want to make it sure that the page 'hurray.php' is visited only from this action. If I typed the direct URL to 'hurray' page, I should not be able to visit this page, rather redirect it to this previous page. | 2010/09/22 | [
"https://Stackoverflow.com/questions/3767128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383393/"
]
| Make an AJAX call to a PHP function that will set a variable in the session. When the AJAX call returns response redirect the user to this page and check for the session variable. You can delete it if you do not want the user to be able to visit it again for this session. | Extend your function so it sets a cookie via "document.cookie", then check via JS ,PHP or whatever on the target page if the cookie is set and redirect somewhere else if not, quite simple. **Of Course thats not really secure!** |
3,767,128 | In my page, I'm using a javascript function
```
<script>
function redirect(){
window.location="hurray.php";
}
</script>
```
Calling the function from the line below.
```
<input id="search_box" name="textbox" type="text" size="50" maxlength="100" onkeypress="redirect()" />
```
Now I want to make it sure that the page 'hurray.php' is visited only from this action. If I typed the direct URL to 'hurray' page, I should not be able to visit this page, rather redirect it to this previous page. | 2010/09/22 | [
"https://Stackoverflow.com/questions/3767128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383393/"
]
| Extend your function so it sets a cookie via "document.cookie", then check via JS ,PHP or whatever on the target page if the cookie is set and redirect somewhere else if not, quite simple. **Of Course thats not really secure!** | Does your example contain real code, or have you just included someething that's made up to make the question simpler to ask?
It seems a strange thing to do - providing the user with a search box and then, as soon as they start typing, redirect them to another page.
If you are doing a search, and you only want the earch page to be triggered from a form, rather than by the user typing in the URL, then consider setting the form method to 'POST' and checking for this on the search page. If the method is 'GET', then the URL was typed manually, and you can redirect back to the original page.
Admittedly, this technically violates the recommendations for the use of 'POST', which should only be for operations that change information, rather than 'GET' which should be used when asking for information. However, this is one occasion where this might be excusable.
Another approach that you could use is to generate a unique key of some kind, and store this in a hidden field of the form, the check for this before deciding whether to redirect to the original page. This would require some kind of reliable key generation scheme, making it slightly trickier, but not impossible. |
45,725 | I read the instructions as stating that you can place an action and/ or a money and/ or a property. But others say you can do any combination of the three in any of the three piles. | 2019/04/01 | [
"https://boardgames.stackexchange.com/questions/45725",
"https://boardgames.stackexchange.com",
"https://boardgames.stackexchange.com/users/27005/"
]
| The three cards can be any combination of properties, actions, and/or money. From the rules (abbreviated for clarity):
>
> PLAY UP TO 3 CARDS from your hand, onto the table in front of you. You don't have to play any cards if you don't want to. Play your 3 cards in any combination of the following: A, B, and/or C.
>
>
> A: Put Money/Bank cards into your own Bank
>
>
> B: Put down Properties into your own collection
>
>
> C: Play Action cards into the center
>
>
> | You can play any three cards from your hand during your turn. These three cards are not otherwise restricted in type; you can for example,
* Play three *Deal Breaker* cards and potentially win the game
* Play three *Pass Go* cards to draw a total of six new cards
* Lay down three properties to either form a set (and possibly win the game immediately) or to complete existing partial sets
* Play three *Rent* cards, either using different properties/sets or the same property/set as the base
* Lay down three *Money* cards in your bank
You can also choose to end your turn before playing any cards at all, let alone all three cards allowed. |
32,305,717 | **How can I read OST file (outlook 2010/2013) from another computer in network using C#**
I can read but only from local system/server. I want to read it from other computer/server in network.I have credentials of other system/server. I couldn't find any article on google | 2015/08/31 | [
"https://Stackoverflow.com/questions/32305717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1055502/"
]
| Your update query seems to have problem. Check shop` rate. Change it
```
UPDATE `table_name` SET `shop rate` = '545454' WHERE i_id = '190';
``` | ```
UPDATE table_name SET `shop rate` = '545454' WHERE i_id = '190';
```
will work
EDIT: also, sorry for not noticing earlier:
$posted[`shop rate`]
should be $posted['shop rate']
EDIT2: part of answer was wrong, omitted that |
62,257,565 | I have tried this alert but not getting result what exactly I want
Suppose my URL = <http://expense.test/admin/manageExpense.php>
I want alert (<http://expense.test/admin/>)
```
var base_url = window.location.origin + '/' + window.location.pathname.split ('/') [1] + '/';
```
Above query getting exact result which i want but when i alert below URL it's not exactly which i want.
Suppose my url is
<http://expense.test/admin/admin/admin/index.php>
when i alert with above query it's getting me same alert (<http://expense.test/admin/>) but I want alert (<http://expense.test/admin/admin/admin/>) , How can i achieve this. Any Help will be appreciated
Main focus how many folders with url but i want to exclude last filename from URL | 2020/06/08 | [
"https://Stackoverflow.com/questions/62257565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10903445/"
]
| I have taken a look at your stackblitz and I have modified it and made it working. You don't need to bind the formControlName with your products because you are not setting them from the frontend UI rather you are just selecting them. I have added a field named `added` in the class `ProductModel` and then I have just implemented the `change` event for the checkboxes to mark it true or false.
Also you can see how I am setting the value for the product. When you hit the `Load Products` button you are adding empty `FormGroup` but you should also set the `product` control inside it with product data. You can see that in the code how i am doing it inside the LoadProducts method
After that you can see in the loop for the products how i am getting the product field. The loop is actually giving us FormGroup we have to get product field value from it
Here is the stackblitz that is doing the job.
<https://stackblitz.com/edit/angular-ivy-ohwv1v>
Particular you can note this part
```
if (this.productsByCategory) {
this.productsByCategory.forEach(
(product) => {
const productForm: FormGroup = this.initProduct();
productForm.controls.product.setValue(product);
control.push(productForm);
});
}
```
After creating the productFormGroup you should also set the product in it. like `productForm.controls.product.setValue(product);`
And then in the frontend you can see
```
<div *ngFor="let p of getProducts(course); let j = index" [formGroupName]="j">
<input type="checkbox" id="product{{i}}-{{j}}" [value]="p.value.product.added" (change)="p.value.product.added = !p.value.product.added"/>
<label for="product{{i}}-{{j}}">{{p.value.product.name}}</label>
</div>
```
you should have the value bind to the added attribute of the product and the name should be shown inside label from the product object too.
Hopefully this will help you proceed further.
>
> And the second problem is that the labels of my checkboxes are not independent. If i add a new 'course' and that i select some products, the labels of all checkboxes in other courses are changed too.
>
>
>
The above issue is resolved
>
> I don't know how to be able to retrieve something like:
>
>
>
Rather than `productName: true/false` you have whole product object available and the `added` field will mark whether its `checked/unchecked` | courses is array of formGroup and inside that formGroup products is another formArray so you have to pass single course formGroup to getProducts method.
**component.html**
```
<div class="row" formArrayName="courses">
<div *ngFor="let course of getCourses(menuForm); let i = index" [formGroupName]="i">
<div class="...">
<select class="form-control" formControlName="courseName">
[value]="course"
<option *ngFor="let course of courses">{{ course.name }}</option>
</select>
<button type="button" class="mt-2 btn btn-outline-dark" (click)="onLoadProducts(i)">
Load Products
</button>
<div class="row" formArrayName="products">
<div class="col-md-12" *ngFor="let product of getProducts(course); let j = index" [formGroupName]="j">
<input class="form-check-input" type="checkbox" id="product{{ i }}-{{ j }}" formControlName="product" />
<label class="form-check-label" for="product{{ i }}-{{ j }}">product</label>
</div>
</div>
</div>
</div>
</div>
```
Then use get method in FormGroup to get a child control.
**component.ts**
```
getCourses(form) {
return form.get('courses').controls;
}
getProducts(form) {
return form.get('products').controls;
}
```
[Example](https://stackblitz.com/edit/angular-ivy-e6h1fj) |
20,628,812 | Good day, I found this priority queue implementation and I am trying to get a min version of it (instead of max). I have no idea where to start. I tried mixing the signs of the functions (naive attempt) but it didn't get me far. Any help of how to implement it and a few words explaining it are very wellcome. The source is below:
Note I have left it's comments
```
#include <iostream>
#include <vector>
#include <assert.h>
using namespace std;
class PriorityQueue
{
vector<int> pq_keys;
void shiftRight(int low, int high);
void shiftLeft(int low, int high);
void buildHeap();
public:
PriorityQueue(){}
PriorityQueue(vector<int>& items)
{
pq_keys = items;
buildHeap();
}
/*Insert a new item into the priority queue*/
void enqueue(int item);
/*Get the maximum element from the priority queue*/
int dequeue();
/*Just for testing*/
void print();
};
void PriorityQueue::enqueue(int item)
{
pq_keys.push_back(item);
shiftLeft(0, pq_keys.size() - 1);
return;
}
int PriorityQueue::dequeue()
{
assert(pq_keys.size() != 0);
int last = pq_keys.size() - 1;
int tmp = pq_keys[0];
pq_keys[0] = pq_keys[last];
pq_keys[last] = tmp;
pq_keys.pop_back();
shiftRight(0, last-1);
return tmp;
}
void PriorityQueue::print()
{
int size = pq_keys.size();
for (int i = 0; i < size; ++i)
cout << pq_keys[i] << " ";
cout << endl;
}
void PriorityQueue::shiftLeft(int low, int high)
{
int childIdx = high;
while (childIdx > low)
{
int parentIdx = (childIdx-1)/2;
/*if child is bigger than parent we need to swap*/
if (pq_keys[childIdx] > pq_keys[parentIdx])
{
int tmp = pq_keys[childIdx];
pq_keys[childIdx] = pq_keys[parentIdx];
pq_keys[parentIdx] = tmp;
/*Make parent index the child and shift towards left*/
childIdx = parentIdx;
}
else
{
break;
}
}
return;
}
void PriorityQueue::shiftRight(int low, int high)
{
int root = low;
while ((root*2)+1 <= high)
{
int leftChild = (root * 2) + 1;
int rightChild = leftChild + 1;
int swapIdx = root;
/*Check if root is less than left child*/
if (pq_keys[swapIdx] < pq_keys[leftChild])
{
swapIdx = leftChild;
}
/*If right child exists check if it is less than current root*/
if ((rightChild <= high) && (pq_keys[swapIdx] < pq_keys[rightChild]))
{
swapIdx = rightChild;
}
/*Make the biggest element of root, left and right child the root*/
if (swapIdx != root)
{
int tmp = pq_keys[root];
pq_keys[root] = pq_keys[swapIdx];
pq_keys[swapIdx] = tmp;
/*Keep shifting right and ensure that swapIdx satisfies
heap property aka left and right child of it is smaller than
itself*/
root = swapIdx;
}
else
{
break;
}
}
return;
}
void PriorityQueue::buildHeap()
{
/*Start with middle element. Middle element is chosen in
such a way that the last element of array is either its
left child or right child*/
int size = pq_keys.size();
int midIdx = (size -2)/2;
while (midIdx >= 0)
{
shiftRight(midIdx, size-1);
--midIdx;
}
return;
}
int main()
{
//example usage
PriorityQueue asd;
asd.enqueue(2);
asd.enqueue(3);
asd.enqueue(4);
asd.enqueue(7);
asd.enqueue(5);
asd.print();
cout<< asd.dequeue() << endl;
asd.print();
return 0;
}
``` | 2013/12/17 | [
"https://Stackoverflow.com/questions/20628812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1846979/"
]
| You *can* do this with `setattr`, but **I don't recommend it**:
```
for i in range(1,5):
setattr(self, 'folderheader%s' % i, QtGui.QLabel(self.folders))
```
Instead, might I suggest a `list`?
```
self.folderheaders = [QtGui.Qlabel(self.folders) for _ in range(1, 5)]
```
Now instead of `self.folderheaders1` you have `self.folderheaders[0]` which isn't really that different... | You can use a `dict` like this
```
self.foldersdict = {}
for i in range(100):
self.foldersdict[i] = QtGui.QLabel(self.folders)
```
You can later access them like this,
```
self.foldersdict[1]
``` |
19,443,247 | I want to save value TRUE if checkbox checked, and FALSE if it is unchecked in an array, how can I do that. I have implemented checkbox in tableview. Code is,
```
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
BOOL checked = [[checkedArr objectAtIndex:indexPath.row] boolValue];
[checkedArr removeObjectAtIndex:indexPath.row];
[cheval insertObject:(checked) ? @"FALSE":@"TRUE" atIndex:indexPath.row];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
UIButton *button = (UIButton *)cell.accessoryView;
UIImage *newImage = (checked) ? [UIImage imageNamed:@"tick.png"] : [UIImage imageNamed:@"white_bg.png"];
[button setBackgroundImage:newImage forState:UIControlStateNormal];
cell.accessoryView=button;
}
``` | 2013/10/18 | [
"https://Stackoverflow.com/questions/19443247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2772174/"
]
| You don't need to bind `click` event handler to *every* button in the column. Every binding take memory and other resources of web browser. The most events bubbling to from inner to outer DOM element (see [here](http://en.wikipedia.org/wiki/DOM_events#Event_flow)), Mouse click, Keyboard keydown, Touch touchstart and other events on the button inside of grid will be bubble to the grid's `<table>` element. jqGrid register by default `click` event handler on the grid. It calls `beforeSelectRow` and `onCellSelect` callbacks and trigger `jqGridBeforeSelectRow` and `jqGridCellSelect` events from the event handler. So instead of binding your own `click` event handlers on every button it's enough to use one from listed above callbacks or events. `beforeSelectRow` (or `jqGridBeforeSelectRow`) will be used first. The callback is practical if you what that click on the button don't select the corresponding row. [The answer](https://stackoverflow.com/a/16241558/315935) for example shows how to verify whether the column which you needs are called. [Another answer](https://stackoverflow.com/a/14537512/315935) provides an example which will be very close to what you need. [One more answer](https://stackoverflow.com/a/13765086/315935) gives you another code fragment. To see more my old answers about the subject you can use [the following query](https://stackoverflow.com/search?q=user:315935%20%5Bjqgrid%5D%20%2bonCellSelect%20%2bbeforeSelectRow%20).
**UPDATED**: the demo <http://jsfiddle.net/ShKDX/82/> is modification of the demo posted by Manuel van Rijn. It demonstrates what I mean. | Here's an simple example how you could add buttons dynamically to a jqgrid
<http://jsfiddle.net/ShKDX/1/>
Not sure if you first row is the id as specified in the fiddle, but you can modify it to use the correct data from the `afterInsertRow` function
```
var data = [
{id: 1, text: 'row1'},
{id: 2, text: 'row2'},
{id: 3, text: 'row3'},
{id: 4, text: 'row4'},
{id: 5, text: 'row5'},
];
$("#grid").jqGrid({
datatype: "local",
height: 250,
colNames: ['Id', 'Text', 'edit'],
colModel: [
{ name: 'id', index: 'id', sorttype: "int" },
{ name: 'text', index: 'text' },
{ name: 'edit', index: 'edit', align: 'center', sortable: false, width: '40px' }
],
caption: "Custom buttons",
data: data,
afterInsertRow: function(id, currentData, jsondata) {
var button = "<a class='gridbutton' data-id='"+id+"' href='#'>edit</a>";
$(this).setCell(id, "edit", button);
},
loadComplete: function(data) {
$(".gridbutton").on('click', function(e) {
e.preventDefault();
alert('Edit id: ' + $(this).data("id"));
});
}
});
``` |
16,802,360 | I have an observable array of observables - each observable has been extended for require however when i save the form with cleared fields it does not collect error or have any errors to show -
```
ko.validation.configure({
grouping: {
deep: true,
observable: true
}
});
var viewModel = function () {
var self = this;
var data = {
"deadzone": "0.2",
"sloperange": "2",
"stepsize": "0.8",
"setpoint": "0.75",
"pressure": "1"
};
self.defaultCalculations = ko.observableArray([]);
self.defaultCalculationProperties = function (defaults) {
var self = this;
var properties = defaults;
self.deadzone = ko.observable(properties.deadzone || '').extend({
required: {
message: '*required'
}
});
self.sloperange = ko.observable(properties.sloperange || '').extend({
required: {
message: '*required'
}
});
self.stepsize = ko.observable(properties.stepsize || '').extend({
required: {
message: '*required'
}
});
self.setpoint = ko.observable(properties.setpoint || '').extend({
required: {
message: '*required'
}
});
self.pressure = ko.observable(properties.pressure || '').extend({
required: {
message: '*required'
}
});
};
//populate calculation values
self.populateCalculationDefaults = function (data) {
//pushing data to an array and mapping each item
var temp = [];
temp[0] = data;
var mappedTasks = _.map(temp, function (item) {
return new self.defaultCalculationProperties(item);
});
self.defaultCalculations(mappedTasks);
};
self.save = function (model) {
//console.log(model);
console.log(self.errors().length, self.errors.showAllMessages());
if (self.errors().length != 0) {
self.errors.showAllMessages();
}
};
self.errors = ko.validation.group(self.defaultCalculations());
self.populateCalculationDefaults(data);
};
ko.applyBindings(new viewModel());
```
Not sure what the problem is and have scoured over stackflow - any suggestions?
<http://jsfiddle.net/kmcadams/W2SZb/> | 2013/05/28 | [
"https://Stackoverflow.com/questions/16802360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1034670/"
]
| Easiest thing to do is call ko.validation.group again inside the populate function. Another option, which i prefer, is to subscribe to defaultcalculations and run the group call in there.
```
self.defaultCalculations.subscribe(function () {
self.errors = ko.validation.group(self.defaultCalculations);
});
```
this will manually subscribe the function to be run anytime defaultCalculations has an item added/removed. | You can also add notify always when extending observable.
```
this.validationModel = ko.validatedObservable({
Num: ko.observable(this.Num).extend({ number: true, notify: 'always' }),
});
```
It worked for me. Before, when this.Num wasn't modified, it wasn't validated. |
6,561,477 | I have someone who wants me to make a website for them but wants to know how much i will charge. I severely undervalue the worth of what i can do as i enjoy it and find it easy. So what would be a fair price for a website consisting of 5 basic html pages and 45+ catalog pages (images, descriptions and item code)? These will be written in HTML and CSS
Thanks | 2011/07/03 | [
"https://Stackoverflow.com/questions/6561477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/635129/"
]
| You're not missing anything and this isn't a particularly important issue. You have a few options:
```
NSLog(@"%d", sender.tag);
```
Sometimes that will produce warnings when compiling, depending on the type of the method parameter.
```
NSLog(@"%d", ((UIButton *)sender).tag);
```
Or finally:
```
UIButton *button = (UIButton *)sender;
NSLog(@"%d", button.tag);
```
(These all basically do the same thing, so it's mostly a matter of preference.) | When you say `UIButton* myButton = (UIButton*) sender;`, you are not making a new object. You are simply making a new handle (pointer) to the `sender` object, and explicitly telling the compiler that it is a `UIButton`.
This means that you can call `UIButton` methods on it without having the compiler complain that they might not exist.
From a memory point of view, you should assume it makes no difference at all. The compiler is probably smart enough to not make you a new pointer anyway, and even if it did, it's going to be 4 bytes or so, which is not worth worrying about. |
6,561,477 | I have someone who wants me to make a website for them but wants to know how much i will charge. I severely undervalue the worth of what i can do as i enjoy it and find it easy. So what would be a fair price for a website consisting of 5 basic html pages and 45+ catalog pages (images, descriptions and item code)? These will be written in HTML and CSS
Thanks | 2011/07/03 | [
"https://Stackoverflow.com/questions/6561477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/635129/"
]
| You're not missing anything and this isn't a particularly important issue. You have a few options:
```
NSLog(@"%d", sender.tag);
```
Sometimes that will produce warnings when compiling, depending on the type of the method parameter.
```
NSLog(@"%d", ((UIButton *)sender).tag);
```
Or finally:
```
UIButton *button = (UIButton *)sender;
NSLog(@"%d", button.tag);
```
(These all basically do the same thing, so it's mostly a matter of preference.) | If the sender is always UIButton, I would declare method as
```
- (void) myMethod: (UIButton*) sender
```
because it practically yield the same effect to pointer type casting. It also saves you one line of code. |
6,561,477 | I have someone who wants me to make a website for them but wants to know how much i will charge. I severely undervalue the worth of what i can do as i enjoy it and find it easy. So what would be a fair price for a website consisting of 5 basic html pages and 45+ catalog pages (images, descriptions and item code)? These will be written in HTML and CSS
Thanks | 2011/07/03 | [
"https://Stackoverflow.com/questions/6561477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/635129/"
]
| When you say `UIButton* myButton = (UIButton*) sender;`, you are not making a new object. You are simply making a new handle (pointer) to the `sender` object, and explicitly telling the compiler that it is a `UIButton`.
This means that you can call `UIButton` methods on it without having the compiler complain that they might not exist.
From a memory point of view, you should assume it makes no difference at all. The compiler is probably smart enough to not make you a new pointer anyway, and even if it did, it's going to be 4 bytes or so, which is not worth worrying about. | If the sender is always UIButton, I would declare method as
```
- (void) myMethod: (UIButton*) sender
```
because it practically yield the same effect to pointer type casting. It also saves you one line of code. |
39,971,726 | For example, my string is: `DELIMxxxyyyzzzaaabbbcc,DELIMaaabbcccxxxyyyzzz,DELIMzzzyyyxxxaaabbbccc,DELIMyyyaaabbb,`
You can see this data is organised in delimited groups. I want to extract the second group (for example) where I'm given the position (in this case 24) and the next delimiter which I know to be "DELIM".
What combination of `substr` and `strpos` or others would I use to get this? | 2016/10/11 | [
"https://Stackoverflow.com/questions/39971726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2066625/"
]
| Use `strpos` to select the start and end position of your delimited group. Then you can use `substr` to get the delimeted group by selecting the string between those two positions.
```
$offset = 4;
$start = strpos($mystring, 'DELIM', $offset); //select start point
$end = strpos($mystring, 'DELIM', $start+5); //select end point by selecting next delimiter
$substr = substr($mystring, $start, $end-$start);
``` | You can use strpos with offset
```
$mystring = 'DELIMxxxyyyzzzaaabbbcc,DELIMaaabbcccxxxyyyzzz,DELIMzzzyyyxxxaaabbbccc,DELIMyyyaaabbb,'
$pos = strpos($mystring, 'DELIM', 24+1 + strlen('DELIM'));
$myPart = substr($mystring, 24, $pos);
``` |
22,363,701 | I'm looking for an OS X editor (preferably a dedicated Forth editor, but I doubt it exists) that has/can be customized to change the font color of Forth variables, programs, etc. If not, is there any sort of workaround? | 2014/03/12 | [
"https://Stackoverflow.com/questions/22363701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3412631/"
]
| I know it's an old question, but: atom with the forth-language package. See <http://atom.io/>
Longer answer:
I have tried both emacs and atom on Mac OS X and both are more than adequate for editing Forth. Atom is lighter and easier to learn while maintaining many emacs-ish capabilities (cmd-shift-p in place of meta-x).
I don't have automatic indenting working in atom yet, the syntax package I found needs a little work, but this hasn't been a real problem as yet.
atom also plays well with git.
I'm using the following packages: emacs-plus, language-forth, clipboard-plus, disable-arrow-keys. The key and clipboard are for a more emacs like experience. There are more themes and color schemes than I need available, I'm using the 4-color-dark and minimal-syntax themes. | I would suggest Gedit and if you change the forth.lang in the app you can change the syntax highlighting |
22,363,701 | I'm looking for an OS X editor (preferably a dedicated Forth editor, but I doubt it exists) that has/can be customized to change the font color of Forth variables, programs, etc. If not, is there any sort of workaround? | 2014/03/12 | [
"https://Stackoverflow.com/questions/22363701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3412631/"
]
| [UltraEdit](http://www.ultraedit.com/products/uex.html) has a Forth syntax highlight mode. MicroProcessor Engineering have an up to date copy in there [downloads](http://www.mpeforth.com/arena.htm) page. | I would suggest Gedit and if you change the forth.lang in the app you can change the syntax highlighting |
22,363,701 | I'm looking for an OS X editor (preferably a dedicated Forth editor, but I doubt it exists) that has/can be customized to change the font color of Forth variables, programs, etc. If not, is there any sort of workaround? | 2014/03/12 | [
"https://Stackoverflow.com/questions/22363701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3412631/"
]
| Look no further !!
I'm currently programming in FORTH using the 'Visual Studio Code; editor.
Has (installable) syntax-highlighting for many languages, including FORTH.
Have a try:
<https://code.visualstudio.com/download>
It has even automatic indenting, AND code folding!!
...and let me know if you like it like I do.
Robbert / PA3BKL | I would suggest Gedit and if you change the forth.lang in the app you can change the syntax highlighting |
13,953,102 | I'm trying to get [poshrunner.exe] to be able to run a script in a PowerShell version 2.0 environment on a machine where PowerShell version 3.0 is installed. PowerShell.exe supports this, [although it seems that distinct support for PowerShell 1.0 is dubious](https://stackoverflow.com/questions/5415259/why-is-powershell-2-0-installed-in-the-same-location-as-powershell-1-0).
I'm running Windows 8. I have two versions of System.Management.Automation.dll in my GAC:
* System.Management.Automation, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 (loaded by `powershell.exe -version 3.0`)
* System.Management.Automation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 (loaded by `powershell.exe -version 1.0` and `powershell.exe -version 2.0`)
As far as I can tell I have no [publisher policy assembly](http://support.microsoft.com/kb/891030) for System.Management.Automation.dll
```
C:\Windows\assembly\GAC_MSIL>dir C:\Windows\assembly\GAC_MSIL\policy*
Volume in drive C has no label.
Volume Serial Number is 0207-A8AA
Directory of C:\Windows\assembly\GAC_MSIL
11/16/2012 11:49 PM <DIR> Policy.12.0.Microsoft.Office.Interop.Access.Dao
12/13/2012 11:49 PM <DIR> policy.2.1.Microsoft.Web.PlatformInstaller
12/13/2012 11:49 PM <DIR> policy.3.0.Microsoft.Web.PlatformInstaller
10/29/2012 03:33 PM <DIR> policy.3.5.System.Data.SqlServerCe
10/29/2012 03:33 PM <DIR> policy.3.5.System.Data.SqlServerCe.Entity
0 File(s) 0 bytes
5 Dir(s) 51,204,710,400 bytes free
C:\Windows\assembly\GAC_MSIL>
```
However, doing an [`AppDomain.CurrentDomain.Load("System.Management.Automation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");`](http://msdn.microsoft.com/en-us/library/36az8x58.aspx) is loading version 3 of the assembly. [Assembly.Load()](http://msdn.microsoft.com/en-us/library/system.reflection.assembly.load.aspx) has the same results.
Before calling assembly:
[]
After Calling Assembly:
[]
That code happens to be running in a secondary app domain, so I'm willing and able to much about with AppDomain settings. How do I force System.Management.Automation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 to laod conditionally at runtime. | 2012/12/19 | [
"https://Stackoverflow.com/questions/13953102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/95195/"
]
| I have had all sorts of issues with System.Management.Automation over time. I recently hit it again and decided to find an alternative way to run PowerShell from .NET using a batch file. See this blog post for code samples:
<http://www.nootn.com.au/2013/01/run-powershell-from-net-program-without.html>
This also mentions how to force it to run a particular version of PowerShell, so if this solution works for you, it may be the answer to your question (assuming you are happy to try and avoid System.Management.Automation).
I hope this helps solve your issue or work around it! | If you go to the references in your project, find the reference and tell it to copy to local that should help too. |
60,683,954 | I'm developing an app in two different languages (fa/en) using [Angular Internationalization (i18n)](https://angular.io/guide/i18n).
* The target is to deploy the two different builds into sub-folders on the server (example.com/en/...)
* These builds are different not only in translation but also styles and layout directions are different.
I can serve any of the localization (languages) like this
```
"architect": {
"build": {
...
,
"configurations": {
...
},
"fa": {
"localize": ["fa"],
"baseHref": "/fa/"
},
"en": {
"localize": ["en"],
"baseHref": "/en/"
}
}
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "app:build"
},
"configurations": {
"production": {
"browserTarget": "app:build:production"
},
"en": {
"browserTarget": "app:build:en"
},
"fa": {
"browserTarget": "app:build:fa"
}
}
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "app:build"
}
},
...
}
```
And then `ng serve --configuration=en` works and I have it on `http://localhost:4200/en/...` But **I need to serve both languages simultaneously** during development to work on the styles and the correct layout and check the translations. If I try to do this in the build configuration `"localize": ["fa","en"]` I get the following error.
`An unhandled exception occurred: The development server only supports localizing a single locale per build`
The best I got so far is to run `ng serve ..` multiple times on different ports to have two instances of the development server in different locales but that is kinda ugly. I am hoping for a better solution. | 2020/03/14 | [
"https://Stackoverflow.com/questions/60683954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3160597/"
]
| In Angular 9 the development server (ng serve) can only be used with a single locale.
However, you can still serve each locale on different ports by running two separate commands:
`ng serve --configuration=fa --port 4200`
`ng serve --configuration=en --port 4201`
Hopefully, they will introduce multiple locale options for development builds in Angular 10 | If you just want to quickly validate the localization for a specific language, like me, just add `"localize": ["<YOUR-LOCALE>"]` to the `angular.json` in `"projects" > "<YOUR PROJECT NAME>" > "architect" > "build" > "configurations" > "development"`. After that, the normal `ng serve` command uses the specified localization. Once you're done, don't forget to remove it again ;)
And yes, I'm aware that this doesn't address the question, but this thread shows up at the very top in google. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.