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
|
---|---|---|---|---|---|
186,308 |
In a world similar set in renaissance times, there are natural occurring stones with the ability to produce flames. The more precious the stone, the higher and stronger quality of the flame/fire. Each stone, whether it's low quality or not, can be chiseled by skilled craftsmen to produce more efficient fires. These fire stones can also be re-charged in special fire pits till they disintegrate from over use. These stones are mined and excavated for in remote mountains.
Practical use of these stones: If you're in the arctic and need to start a fire, all you need is a few stones and you'll have a blazing fire that lasts longer than firewood. If the stones are of low quality, they can burn for 2-3 hours. If they are superior, they can burn for 2-3 days if left unmolested.
The trouble I'm having is **how does one activate such a power**? If it's through spoken word (like a spell), what's stopping someone from lighting a wayfarer's stones on fire with the slip of a word? Would it make sense to inscribe runes into the stone that special individuals can activate? What's a more practical way of summoning and putting out the flames? I'm aiming at having these stones being an every-day-use household item used for cooking, warming hearths, etc. — so the simpler the solution, the better.
|
2020/09/27
|
[
"https://worldbuilding.stackexchange.com/questions/186308",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/55047/"
] |
If you don't need them to burn more than once between recharging, you could have the energy stored in some kind of phase change. Heating the stones in a special oven causes them to store the energy. Once they are at room temperature, they need some kind of catalyst to start releasing the energy again - which is as simple as touching them with an already "burnt" stone. Stones of different sizes will "burn" for different times, and flatter stones will burn hotter than round stones. Charged vs. burnt states could even be different colors, based on the phase change.
A parallel to this in our world are handwarmers based on sodium acetate, or "rechargeable" hand warmers.
|
[Sodium acetate](https://en.wikipedia.org/wiki/Sodium_acetate#Heating_pad) used in heating packs is a good example of trigger-based chimical exothermic reaction.
With a simple "physical" spark (through a little piece of metal), you will trigger the reaction. So you don't need any complicated way to trigger it (unless you want it fancy or really cool).
About your stones, whether they are harvested, mined or built, the reaction should not be triggered easilly, but should instead be "foundable" by human way (by serendipity, basic observation, active research). If collected, the trigger could be very simple but should not be found in the vicinity of the harvesting site.
So I think they are a few questions that should be answered before you can focus on a acceptable and plausible trigger :
* Are they harvested / mined / built / ....?
* If not built, where do you collect them (environnment, temperature, etc.)
* Who do build / collect them?
For example:
* If the stones are found underwater, or collected in the void of space: you could basically used "open
air" as the trigger. Then the stones would be stored in a jar, until
you empty it and trigger the reaction.
* If found in a azot-free environnment (totally fanciful, but it's for
the exemple) : a sufficient amount of azot in its immediate vicinity
would be the spark.
* If built, it could be basically any kind of trigger that would not
reproduce outdoors (a rare radiation, an specific radio frequency, a
microwave, etc.)
Etc.
|
186,308 |
In a world similar set in renaissance times, there are natural occurring stones with the ability to produce flames. The more precious the stone, the higher and stronger quality of the flame/fire. Each stone, whether it's low quality or not, can be chiseled by skilled craftsmen to produce more efficient fires. These fire stones can also be re-charged in special fire pits till they disintegrate from over use. These stones are mined and excavated for in remote mountains.
Practical use of these stones: If you're in the arctic and need to start a fire, all you need is a few stones and you'll have a blazing fire that lasts longer than firewood. If the stones are of low quality, they can burn for 2-3 hours. If they are superior, they can burn for 2-3 days if left unmolested.
The trouble I'm having is **how does one activate such a power**? If it's through spoken word (like a spell), what's stopping someone from lighting a wayfarer's stones on fire with the slip of a word? Would it make sense to inscribe runes into the stone that special individuals can activate? What's a more practical way of summoning and putting out the flames? I'm aiming at having these stones being an every-day-use household item used for cooking, warming hearths, etc. — so the simpler the solution, the better.
|
2020/09/27
|
[
"https://worldbuilding.stackexchange.com/questions/186308",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/55047/"
] |
You are basically describing magic coal. It is magic because it can maybe burn longer and stronger, but mostly because it is rechargeable. Other than that it is just coal.
You light it up just as non-magical coal, by applying a lot of heat on a small point. You can spin a stick on top of it, or rub two sticks together, or you can bang small rocks to make sparks. On a pinch, you can also use magic to summon fire. The problem with fireballs is that without any fuel their flames run out quickly, but the magic coal solves that problem for the fellow pyro looking for a lasting fix.
You can then deactivate it by throwing water, ice, sand, a cloth or someone else on top of it, in order to deprive the flames from oxygen. I don't see why you would want to do that, though.
|
If you don't need them to burn more than once between recharging, you could have the energy stored in some kind of phase change. Heating the stones in a special oven causes them to store the energy. Once they are at room temperature, they need some kind of catalyst to start releasing the energy again - which is as simple as touching them with an already "burnt" stone. Stones of different sizes will "burn" for different times, and flatter stones will burn hotter than round stones. Charged vs. burnt states could even be different colors, based on the phase change.
A parallel to this in our world are handwarmers based on sodium acetate, or "rechargeable" hand warmers.
|
186,308 |
In a world similar set in renaissance times, there are natural occurring stones with the ability to produce flames. The more precious the stone, the higher and stronger quality of the flame/fire. Each stone, whether it's low quality or not, can be chiseled by skilled craftsmen to produce more efficient fires. These fire stones can also be re-charged in special fire pits till they disintegrate from over use. These stones are mined and excavated for in remote mountains.
Practical use of these stones: If you're in the arctic and need to start a fire, all you need is a few stones and you'll have a blazing fire that lasts longer than firewood. If the stones are of low quality, they can burn for 2-3 hours. If they are superior, they can burn for 2-3 days if left unmolested.
The trouble I'm having is **how does one activate such a power**? If it's through spoken word (like a spell), what's stopping someone from lighting a wayfarer's stones on fire with the slip of a word? Would it make sense to inscribe runes into the stone that special individuals can activate? What's a more practical way of summoning and putting out the flames? I'm aiming at having these stones being an every-day-use household item used for cooking, warming hearths, etc. — so the simpler the solution, the better.
|
2020/09/27
|
[
"https://worldbuilding.stackexchange.com/questions/186308",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/55047/"
] |
You are basically describing magic coal. It is magic because it can maybe burn longer and stronger, but mostly because it is rechargeable. Other than that it is just coal.
You light it up just as non-magical coal, by applying a lot of heat on a small point. You can spin a stick on top of it, or rub two sticks together, or you can bang small rocks to make sparks. On a pinch, you can also use magic to summon fire. The problem with fireballs is that without any fuel their flames run out quickly, but the magic coal solves that problem for the fellow pyro looking for a lasting fix.
You can then deactivate it by throwing water, ice, sand, a cloth or someone else on top of it, in order to deprive the flames from oxygen. I don't see why you would want to do that, though.
|
**Just like a nuclear reactor works (with a bigger safety margin).**
Put a lot of them together and they start to make heat. Put them apart and they fade and stop.
You may as well handwave two supplemental materials - a reflector (one may put fewer stones inside a reflecting container and they will ignite) and a poison (as in neutron poison - separate them with the poison material and they don't work even when piled together, you have to remove the poison to make them work again).
|
373,511 |
Let $X$ be a connected CW-complex with $\pi\_k(X)$ trivial for $k >2$. Is it known under which circumstances $X$ is an $H$-group?
I have been able only to deduce the necessary condition that $\pi\_1(X)$ has to be abelian and act trivially on $\pi\_2(X)$. Furthermore, if the necessary condition holds, vanishing of the Postnikov invariant $\beta \in H^3( \pi\_1(X), \pi\_2(X))$ is a sufficient condition. Thus the interesting case is that of $\beta$ nonzero.
|
2020/10/07
|
[
"https://mathoverflow.net/questions/373511",
"https://mathoverflow.net",
"https://mathoverflow.net/users/94647/"
] |
The necessary condition is a "additivity"-type condition on the $k$-invariant.
Suppose $\pi\_1 X = G$ and $\pi\_2 X = A$. As you correctly point out, $G$ must be abelian and act trivially on $A$. Under these circumstances, the $k$-invariant is expressible as a natural map of pointed spaces
$$
\beta: K(G,1) \to K(A,3).
$$
(Normally $\beta$ can only be constructed as a map $K(G,1) \to K(A\_G, 3)$ in terms of the coinvariants.) The space $X$ is the homotopy fiber of $\beta$, and the $k$-invariant of $X \times X$ is $\beta \times \beta$.
This means that, in order to get an $H$-space, it is necessary and sufficient to get a homotopy commutative diagram of pointed spaces:
$\require{AMScd}$
$$
\begin{CD}
K(G,1) \times K(G,1) @>m>> K(G,1)\\
@V \beta \times \beta V V @VV \beta V\\
K(A,3) \times K(A,3) @>>m> K(A,3)
\end{CD}
$$
Here $m$ is the $H$-space multiplication on Eilenberg--Mac Lane spaces for abelian groups, which induces addition on cohomology. In terms of the projection maps $p\_i: K(G,1) \times K(G,1) \to K(G,1)$, homotopy commutativity of this diagram says that
$$
m^\*(\beta) = p\_1^\*(\beta) + p\_2^\*(\beta).
$$
If there is a sufficiently good Kunneth formula (e.g. if $A$ is a ring and $H\_\*(K(G,1);A)$ are finitely generated projective) then $m^\*$ is a "coproduct"
$$
m^\*: H^\*(K(G,1); A) \to H^\*(K(G,1); A) \otimes\_A H^\*(K(G,1); A)
$$
and under this identification we are asking that $\beta$ is primitive: $m^\*(\beta) = \beta \otimes 1 + 1 \otimes \beta$.
If we think of $\beta$ as representing a cohomology operation $H^1(-;G) \to H^3(-;A)$, this condition equivalently asks that $\beta$ is additive: $\beta(x + y) = \beta(x) + \beta(y)$.
|
I just wanted to add to Tyler Lawson's answer that all the maps $\beta\colon K(G,1)\rightarrow K(A,3)$ ($G$ and $A$ abelian and no action of $G$ on $A$) satisfying his additivity condition are loop maps by Stasheff's Homotopy Associativity of $H$-Spaces II (Theorem 5.3). Hence for 2-types being an $H$-space is the same as being a loop space. See also Qiaochu Yuan's comment.
In terms of $k$-invariants, the condition is that the $k$-invariant of the 2-type is in the image of the so-called cohomology 'suspension' morphism
$$H^4(K(G,2),A)\longrightarrow H^3(K(G,1),A),$$
which is induced by taking loops on the corresponding sets of homotopy classes of maps between Eilenberg-MacLane spaces.
The source is very well understood, it coincides with
$$\hom(\Gamma(G),A).$$
Here $\Gamma(G)$ is the target of the universal quadratic map $G\rightarrow\Gamma(G)$. Recall that a map $\gamma\colon G\to B$ between abelian groups is *quadratic* if $G\times G\to B\colon (x,y)\mapsto\gamma(x+y)-\gamma(x)-\gamma(y)$ is bilinear.
An example with non-trivial $k$-invariant can be constructed as follows. It suffices to show that
$$H^4(K(\mathbb{Z}/2,2),\mathbb{Z}/4)\longrightarrow H^3(K(\mathbb{Z}/2,1),\mathbb{Z}/4)$$
coincides with
$$\mathbb{Z}/4\twoheadrightarrow \mathbb{Z}/2.$$
Indeed, $H^3(K(\mathbb{Z}/2,1),\mathbb{Z}/4)$ is well-known to be the elements annihilated by $2$ in $\mathbb{Z}/4$, which identifies with $\mathbb{Z}/2$. A normalised $3$-cocycle representing the generator is
$$f\colon \mathbb{Z}/2\times \mathbb{Z}/2\times \mathbb{Z}/2\longrightarrow \mathbb{Z}/4,\qquad f(1,1,1)=2.$$
(I will omit notations for classes in quotients of $\mathbb{Z}$ since the meaning in each case will be clear from the context.)
The universal quadratic map for $\mathbb{Z}/2$ is $\gamma\colon \mathbb{Z}/2\rightarrow \mathbb{Z}/4$, $\gamma(0)=0$, $\gamma(1)=1$. Hence $\Gamma(\mathbb{Z}/2)=\mathbb{Z}/4$ and
$$\hom(\Gamma(\mathbb{Z}/2),\mathbb{Z}/4)=\hom(\mathbb{Z}/4,\mathbb{Z}/4)=\mathbb{Z}/4.$$
In order to compute the suspension morphisms I'm going to use crossed modules and their semi-stable version called reduced quadratic modules by Baues (see his book on 4-dimensional complexes). It is well known that 3-dimensional group cohomology classifies crossed modules (Eilenberg-MacLane or one of them alone, I don't currently remember). Similarly $\hom(\Gamma(\mathbb{Z}/2),\mathbb{Z}/4)$ classifies reduced quadratic modules. The generator is represented by the reduced quadratic module
$$\mathbb{Z}\otimes \mathbb{Z} \stackrel{\langle-,-\rangle}\longrightarrow \mathbb{Z}\oplus \mathbb{Z}/4\stackrel{\partial}\longrightarrow \mathbb{Z}$$
where $\partial(a,b)=2a$ and $\langle x,y\rangle =(0,{xy}).$ This is because $\ker \partial=\mathbb{Z}/4$, $\operatorname{coker}\partial=\mathbb{Z}/2$ and the map $\mathbb{Z}/2\mapsto \mathbb{Z}/4$ defined by ${x}\mapsto{\langle x,x\rangle}$ coincides with the aforementioned universal quadratic map. The loop crossed module of this reduced quadratic module is
$$\mathbb{Z}\oplus \mathbb{Z}/4\stackrel{\partial}\longrightarrow \mathbb{Z},$$
where the source is equipped with an exponential action of the target defined by
$$x^a=x+\langle\partial(x),a\rangle.$$
(Crossed modules usually consist of non-abelian groups and reduced quadratic modules too, but in this case everything is abelian because they are very small, this simplifies a lot the computations). A 3-cocycle
$$g\colon \mathbb{Z}/2\times \mathbb{Z}/2\times \mathbb{Z}/2\longrightarrow \mathbb{Z}/4$$
representing the cohomology class of this crossed module is defined by the following choices:
We first need a set-theoretic splitting of $\partial$, that we define as
$$s\colon \mathbb{Z}/2\longrightarrow \mathbb{Z},\qquad s(0)=0,\quad s(1)=1.$$
Now, for each pair of elements $x,y\in \mathbb{Z}/2$ we need $t(x,y)\in \mathbb{Z}\oplus \mathbb{Z}/4$ such that
$$\partial(t(x,y))=-s(y)-s(x)+s(x+y).$$
This measures the failure of $s$ to be a morphism.
We take $t(0,-)=(0,0)$, $t(-,0)=(0,0)$, and $t(1,1)=(1,0)$.
With these choices $g$ is
$$g(x,y,z)=t(x,y)^{s(z)}+t(x+y,z)-t(x,y+z)-t(y,z)\in\ker\partial=\mathbb{Z}/4.$$
Different choices produce cohomologous cocycles.
This cocycle is normalised because $t(0,-)$ and $t(-,0)$ vanish, so we only have to compute
$$\begin{array}{rcl}
g(1,1,1)&=&t(1,1)^{s(1)}+t(1+1,1)-t(1,1+1)-t(1,1)\\
&=&t(1,1)+\langle \partial t(1,1), s(1)\rangle +t(0,1)-t(1,0)-t(1,1)\\
&=&\langle \partial t(1,1), s(1)\rangle\\
&=&\langle \partial (1,0), 1\rangle\\
&=&\langle 2, 1\rangle\\
&=&(0,2).
\end{array}$$
The second coordinate (the kernel of $\partial$) is $2\in \mathbb{Z}/4$, therefore, $g=f$ above. This concludes the proof of the claim.
|
14,535,683 |
I am learning `maven` these days. During making Web application it shows error.
When I add servlets in the source location and add these changes in the `web.xml`. It shows `package missing errors`.
My imports in code are :-
1. import java.io.\*;
2. import javax.servlet.\*;
3. import javax.servlet.http.\*;
When I write `mvn compile` in `command prompt` in `windows`. It shows errors.
Errors are as follows:-
1. package javax.servlet does not exists.
2. package javax.servlet.http doeas not exist.
3. Some errors related to above two.
Help me.Looking for your kind response.
|
2013/01/26
|
[
"https://Stackoverflow.com/questions/14535683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1340736/"
] |
You probably just have to add the dependency to your web.xml.
check here maybe: <http://mvnrepository.com/artifact/javax.servlet/servlet-api>
```
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
```
|
I am not sure how have you created web application in first place. You can use Maven to create a sample webApp for you with jsut a simeple command. You can use lates Maven version (I used Maven 3.04) to use the below command
```
mvn archetype:generate
```
then It lists out the templates offered and you are asked to choose one number.
Then chose 436, which is a Java EE webapp template for java version 5 (You can choose what ever version you like)
```
Choose a number or apply filter (format: [groupId:]artifactId, case sensitive contains): 247: 436
Choose org.codehaus.mojo.archetypes:webapp-jee5 version:
1: 1.0
2: 1.0.1
3: 1.1
4: 1.2
5: 1.3
Choose a number: 5: 5
```
And then give the below required parameters
```
Define value for property 'groupId': : Priya.MyWebTutorial.org
Define value for property 'artifactId': : MyLearnersApp
Define value for property 'version': 1.0-SNAPSHOT: :
Define value for property 'package': Priya.MyWebTutorial.org: :
Confirm properties configuration:
groupId: Priya.MyWebTutorial.org
artifactId: MyLearnersApp
version: 1.0-SNAPSHOT
package: Priya.MyWebTutorial.org
Y: :
```
And you will have a webapp template created in the same folder, ready to use. You will have the dependencies already added in your generated pom.xml as below
```
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
```
When you compile this web app, the servlet and jsp jars need for your application are automatically downloded into your local repository by Maven.
|
3,260,055 |
From *Convex Optimization* by Boyd & Vandenberghe:
>
> Let $\Delta x\_{\text{snd}} = \arg \min\{\nabla f(x)^Tv : \|v\| = 1\}$
> be the normalized steepest descent direction with respect to the norm
> $\|\*\|$.
>
>
> Consider the norm $\|z\|\_P = (z^TPz)^{1/2} = \|P^{1/2}z\|\_2$ where $P
> \in S^n\_{++}$ the set of positive semi-definite matrices.
>
>
> Then $\Delta x\_{\text{snd}} =-(\nabla f(x)^TP^{-1}\nabla
> f(x))^{-1/2}P^{-1} \nabla f(x)$.
>
>
>
Can someone explain how $\Delta x\_{\text{snd}} =-(\nabla f(x)^TP^{-1}\nabla f(x))^{-1/2}P^{-1} \nabla f(x)$?
I see that $\Delta x\_{\text{snd}} = \arg \min\{\nabla f(x)^Tv : \|v\|\_P = (v^TPv)^{1/2} = \|P^{1/2}v\|\_2 = 1\}$
But from here I'm not seeing how the above equality is derived.
|
2019/06/12
|
[
"https://math.stackexchange.com/questions/3260055",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/334611/"
] |
Generally, the solution to $\min\_{\|x\|=1} g^T x$ is $x = -{1 \over \|g\|} g$.
This follows from Cauchy Schwartz.
The above problem can be written as
$\min\_{\|x\|\_P = 1} g^T x = \min\_{\|\sqrt{P}x\| = 1} g^T x = \min\_{\|y\| = 1} g^T \sqrt{P}^{-1} y $ (where the transformation $y=\sqrt{P} x$ was used).
So the solution (of the last problem) is
$y=-{1 \over \|\sqrt{P}^{-1} g\|} \sqrt{P}^{-1} g$ and converting back into the 'x' representation we have
$x = \sqrt{P}^{-1}y = -{1 \over \|\sqrt{P}^{-1} g\|} P^{-1} g $.
Note that $\|\sqrt{P}^{-1} g\| = \sqrt{g^TP^{-1} g}$.
|
**My attempt**: Perhaps you can finish it
$\nabla\_z ||P^{1/2}z||\_2 = \frac{P^{T/2}P^{1/2} z}{||P^{1/2}z||\_2}$. Now you want optimize
$$ \min \frac{z^T P^{T/2}P^{1/2}}{||P^{1/2}z||\_2} v \quad \text{s.t.} ||v||^2\_2 = 1,
$$
which is equivalent to
$$ \min \frac{z^T P}{||P^{1/2}z||\_2} v \quad \text{s.t.} ||v||^2\_2 = 1
$$
To minimize the expression $v$ should be in the null-space $ P $.
|
3,260,055 |
From *Convex Optimization* by Boyd & Vandenberghe:
>
> Let $\Delta x\_{\text{snd}} = \arg \min\{\nabla f(x)^Tv : \|v\| = 1\}$
> be the normalized steepest descent direction with respect to the norm
> $\|\*\|$.
>
>
> Consider the norm $\|z\|\_P = (z^TPz)^{1/2} = \|P^{1/2}z\|\_2$ where $P
> \in S^n\_{++}$ the set of positive semi-definite matrices.
>
>
> Then $\Delta x\_{\text{snd}} =-(\nabla f(x)^TP^{-1}\nabla
> f(x))^{-1/2}P^{-1} \nabla f(x)$.
>
>
>
Can someone explain how $\Delta x\_{\text{snd}} =-(\nabla f(x)^TP^{-1}\nabla f(x))^{-1/2}P^{-1} \nabla f(x)$?
I see that $\Delta x\_{\text{snd}} = \arg \min\{\nabla f(x)^Tv : \|v\|\_P = (v^TPv)^{1/2} = \|P^{1/2}v\|\_2 = 1\}$
But from here I'm not seeing how the above equality is derived.
|
2019/06/12
|
[
"https://math.stackexchange.com/questions/3260055",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/334611/"
] |
Generally, the solution to $\min\_{\|x\|=1} g^T x$ is $x = -{1 \over \|g\|} g$.
This follows from Cauchy Schwartz.
The above problem can be written as
$\min\_{\|x\|\_P = 1} g^T x = \min\_{\|\sqrt{P}x\| = 1} g^T x = \min\_{\|y\| = 1} g^T \sqrt{P}^{-1} y $ (where the transformation $y=\sqrt{P} x$ was used).
So the solution (of the last problem) is
$y=-{1 \over \|\sqrt{P}^{-1} g\|} \sqrt{P}^{-1} g$ and converting back into the 'x' representation we have
$x = \sqrt{P}^{-1}y = -{1 \over \|\sqrt{P}^{-1} g\|} P^{-1} g $.
Note that $\|\sqrt{P}^{-1} g\| = \sqrt{g^TP^{-1} g}$.
|
$$ \Delta x\_{\textrm{nsd}} = \textrm{argmin} \{ \nabla f(x)^Tv \mid \space\space\space \vert\vert v \vert\vert\_{P} \le 1 \} $$
$$ = \textrm{argmin} \{ \nabla f(x)^Tv \mid \space\space\space\vert\vert P^{1/2}v \vert\vert\_{2} \le 1 \} $$
$$ = \textrm{argmin} \{ \nabla f(x)^T P^{-1/2}P^{1/2}v \mid \space\space\space \vert\vert P^{1/2}v \vert\vert\_{2} \le 1 \} $$
$$ = \textrm{argmin} \{ (\nabla f(x)^T P^{-1/2})y \mid \space\space\space \vert\vert y \vert\vert\_{2} \le 1 \} $$
where we set $y = P^{1/2}v$.
Now we're back in the familiar Euclidean case and so immediately conclude that the $y$ which minimizes this inner product is the unit vector pointing in the opposite direction to $\nabla f(x)^T P^{-1/2}$:
$$y^{\*} = \frac{-P^{-1/2}\nabla f(x)^{T}}{\vert\vert P^{-1/2}\nabla f(x)^{T} \vert\vert\_{2}} $$
$$
\implies v^{\*} = \frac{-P^{-1/2}P^{-1/2}\nabla f(x)^{T}}{\vert\vert P^{-1/2}\nabla f(x)^{T} \vert\vert\_{2}} $$
$$ = \frac{-P^{-1}\nabla f(x)^{T}}{\vert\vert P^{-1/2}\nabla f(x)^{T} \vert\vert\_{2}} $$
$$ = \frac{-P^{-1}\nabla f(x)^{T}}{(\nabla f(x)^{T} P^{-1/2} \nabla f(x))^{1/2}} $$
And we're done. To get $v^{\*}$ we used $y = P^{1/2}v$ so $v = P^{-1/2}y$.
That $(\nabla f(x)^{T} P^{-1/2} \nabla f(x))^{1/2} = \vert\vert P^{-1/2}\nabla f(x)^{T} \vert\vert\_{2}$ is given in the textbook referenced in the question.
|
17,232 |
ISO 639-3 has many language codes for Arabic, but only one for English.
I'm an Arab who is familiar with multiple Arabic dialects. We do not call it anything but "لهجات" which is translated to "dialects".
We also call it "عامية" which is translated to "slang". I've never heard an Arabic man call its region's dialect a language. Yet the ISO classification for Arabic contain more languages than Arabic countries.
Arabic with over 30 language:
<http://www-01.sil.org/iso639-3/documentation.asp?id=ara>
English with just one:
<http://www-01.sil.org/iso639-3/documentation.asp?id=eng>
I know there are many difference between the American and British English. And there are differences between the South African, Canadian, North Ireland, Scottish and the Australian English. There is also the old Shakespeare period English language.
Still just one English language under the ISO 639-3.
**Update:** AFAIK No official reorganization for any dialect from any Arabic country. Arab countries teach only the main Standard Arabic language in schools and it's used in official documents.
It's the official language in the highest Arabic body, the [Arab League](language of the Arab <https://en.wikipedia.org/wiki/Arab_League>)
Also except for some variations in North Africa Arabs understand each other very clearly similar to different speaker of English (like English in India - English in Scotland).
|
2016/04/03
|
[
"https://linguistics.stackexchange.com/questions/17232",
"https://linguistics.stackexchange.com",
"https://linguistics.stackexchange.com/users/12873/"
] |
I'm not able to give you an authoritative answer, but here is my attempt at one. See "Macrolanguage" in [Wikipedia](https://en.wikipedia.org/wiki/ISO_639_macrolanguage) and in [SIL](http://www-01.sil.org/iso639-3/scope.asp#M) for more information.
The distinction between a language and a dialect is mostly a political or social question, not a linguistic one. Thus Serbian, Croatian, and Bosnian were universally regarded as one language (Serbo-Croat) until the breakup of Yugoslavia.
Having said that, mutual intelligibility is often taken as an important indicator. Although there have been British (especially Scottish) films that have been subtitled for US audiences, nearly all English dialects are mostly comprehensible to speakers of other dialects. This does not appear to be the case for Arabic: according to a [Wikipedia article](https://en.wikipedia.org/wiki/Varieties_of_Arabic), "Some varieties of Arabic in North Africa, for example, are incomprehensible to an Arabic speaker from the Levant or the Persian Gulf."
As far as I know, there has never been a strong move anywhere in the Anglosphere to treat different varieties of English as different languages: I don't know whether or not there has been in the Arabic world; but the people who assigned ISO639-3 codes (members of SIL) seem to have regarded the different varieties of Arabic as different enough to require them to be listed separately within a macrolanguage.
|
ISO639-3 is derived from [The Ethnologue](http://www.ethnologue.com/). The author of this work have a certain point of view on the definition of "language" (vs. "dialect") with a strong tendency to split languages into smaller units. Note that the authors of the Ethnologue have a open agenda that is different from doing science. Divide and Conquer.
|
17,232 |
ISO 639-3 has many language codes for Arabic, but only one for English.
I'm an Arab who is familiar with multiple Arabic dialects. We do not call it anything but "لهجات" which is translated to "dialects".
We also call it "عامية" which is translated to "slang". I've never heard an Arabic man call its region's dialect a language. Yet the ISO classification for Arabic contain more languages than Arabic countries.
Arabic with over 30 language:
<http://www-01.sil.org/iso639-3/documentation.asp?id=ara>
English with just one:
<http://www-01.sil.org/iso639-3/documentation.asp?id=eng>
I know there are many difference between the American and British English. And there are differences between the South African, Canadian, North Ireland, Scottish and the Australian English. There is also the old Shakespeare period English language.
Still just one English language under the ISO 639-3.
**Update:** AFAIK No official reorganization for any dialect from any Arabic country. Arab countries teach only the main Standard Arabic language in schools and it's used in official documents.
It's the official language in the highest Arabic body, the [Arab League](language of the Arab <https://en.wikipedia.org/wiki/Arab_League>)
Also except for some variations in North Africa Arabs understand each other very clearly similar to different speaker of English (like English in India - English in Scotland).
|
2016/04/03
|
[
"https://linguistics.stackexchange.com/questions/17232",
"https://linguistics.stackexchange.com",
"https://linguistics.stackexchange.com/users/12873/"
] |
Are the languages spoken in various Arabian countries actually mutually intelligible? If no then it makes more sense to regard them as separate languages.
In China the government likes to officially categorize various Chinese languages as "dialects", but the reality is that the difference is really huge between some of them, e.g. comparing Mandarin and Cantonese is more like comparing Italian with Spanish than American English with British English. Most Mandarin speakers don't understand nor speak Cantonese at all. Therefore there are many language codes for various Chinese languages as well and it makes sense to me.
I wonder whether the situation is similar in Arabic: If you can't even understand some of the Northern African Arabic then how can you claim they're the "same language"? Some people might try to do so politically but linguistically it would be far-fetched. The situation is just fundamentally different from American vs. British English I suppose.
|
I'm not able to give you an authoritative answer, but here is my attempt at one. See "Macrolanguage" in [Wikipedia](https://en.wikipedia.org/wiki/ISO_639_macrolanguage) and in [SIL](http://www-01.sil.org/iso639-3/scope.asp#M) for more information.
The distinction between a language and a dialect is mostly a political or social question, not a linguistic one. Thus Serbian, Croatian, and Bosnian were universally regarded as one language (Serbo-Croat) until the breakup of Yugoslavia.
Having said that, mutual intelligibility is often taken as an important indicator. Although there have been British (especially Scottish) films that have been subtitled for US audiences, nearly all English dialects are mostly comprehensible to speakers of other dialects. This does not appear to be the case for Arabic: according to a [Wikipedia article](https://en.wikipedia.org/wiki/Varieties_of_Arabic), "Some varieties of Arabic in North Africa, for example, are incomprehensible to an Arabic speaker from the Levant or the Persian Gulf."
As far as I know, there has never been a strong move anywhere in the Anglosphere to treat different varieties of English as different languages: I don't know whether or not there has been in the Arabic world; but the people who assigned ISO639-3 codes (members of SIL) seem to have regarded the different varieties of Arabic as different enough to require them to be listed separately within a macrolanguage.
|
17,232 |
ISO 639-3 has many language codes for Arabic, but only one for English.
I'm an Arab who is familiar with multiple Arabic dialects. We do not call it anything but "لهجات" which is translated to "dialects".
We also call it "عامية" which is translated to "slang". I've never heard an Arabic man call its region's dialect a language. Yet the ISO classification for Arabic contain more languages than Arabic countries.
Arabic with over 30 language:
<http://www-01.sil.org/iso639-3/documentation.asp?id=ara>
English with just one:
<http://www-01.sil.org/iso639-3/documentation.asp?id=eng>
I know there are many difference between the American and British English. And there are differences between the South African, Canadian, North Ireland, Scottish and the Australian English. There is also the old Shakespeare period English language.
Still just one English language under the ISO 639-3.
**Update:** AFAIK No official reorganization for any dialect from any Arabic country. Arab countries teach only the main Standard Arabic language in schools and it's used in official documents.
It's the official language in the highest Arabic body, the [Arab League](language of the Arab <https://en.wikipedia.org/wiki/Arab_League>)
Also except for some variations in North Africa Arabs understand each other very clearly similar to different speaker of English (like English in India - English in Scotland).
|
2016/04/03
|
[
"https://linguistics.stackexchange.com/questions/17232",
"https://linguistics.stackexchange.com",
"https://linguistics.stackexchange.com/users/12873/"
] |
Unifying and subdividing speech forms under an ISO code is not a rigorous ontological claim: it is the standardization statement "this linguistic thing is to be abbreviated that way". "Quechua", "Luyia", and "Arabic" (also "Latvian") are examples of macrolanguages, under ISO 639-3. The individual languages are different enough that they are not *all* mutually intelligible. Cypriot, Juba Arabic (pga), and Chadian are quite different, and it is well-known that Moroccan Arabic is "challenging". I haven't experiences Tajiki or Uzbeki Arabic but I don't find the claims to be too incredible: we can leave it at that (I am skeptical about N and S Levantine by the mutual intelligibility criterion). The point is that there are significant linguistic differences between these varieties of Arabic, and linguists have documented even more differences than are presently recognized in the ISO system. (See for example the numerous varieties documented in T. Prochazka's book *Saudi Arabian dialects*). All of the forms are still unified with a single identifier *ara* which refers to the Arabic macrolanguage; individual varieties also have their identifiers. The [Glottolog system](http://glottolog.org/resource/languoid/id/arab1395) makes even more distinctions (40) – subsuming Maltese under their arab1395 (not included under *ara* in the ISO system), subdividing Libyan Arabic into 4 varieties.
The same is true of the various Luyia languages, which are unified under *luy*, but also distinguished with particular identifiers (*lts* for Tachoni, *lri* for Marachi, and so on); idem the Quechua languages. Somali is presently not indicated as a "macrolanguage", it is an individual language, but the main reason for the failure to subdivide is the lack of information on the extent of difference.
It is thus not surprising that these languages enjoy subdivisions in ISO 639-3 classification. What *is* somewhat surprising is that there is no subdivision in the ISO analysis of English, where there are dozens of varieties that are mutually unintelligible in the same say that Moroccan, Syrian and Juba Arabic are. Glottolog does, however, subdivide ("Mercian") [English](http://glottolog.org/resource/languoid/id/macr1271) into 35 varieties, plus 4 Scots varieties (which ISO registers as a distinct language, *sco*, from English).
|
I'm not able to give you an authoritative answer, but here is my attempt at one. See "Macrolanguage" in [Wikipedia](https://en.wikipedia.org/wiki/ISO_639_macrolanguage) and in [SIL](http://www-01.sil.org/iso639-3/scope.asp#M) for more information.
The distinction between a language and a dialect is mostly a political or social question, not a linguistic one. Thus Serbian, Croatian, and Bosnian were universally regarded as one language (Serbo-Croat) until the breakup of Yugoslavia.
Having said that, mutual intelligibility is often taken as an important indicator. Although there have been British (especially Scottish) films that have been subtitled for US audiences, nearly all English dialects are mostly comprehensible to speakers of other dialects. This does not appear to be the case for Arabic: according to a [Wikipedia article](https://en.wikipedia.org/wiki/Varieties_of_Arabic), "Some varieties of Arabic in North Africa, for example, are incomprehensible to an Arabic speaker from the Levant or the Persian Gulf."
As far as I know, there has never been a strong move anywhere in the Anglosphere to treat different varieties of English as different languages: I don't know whether or not there has been in the Arabic world; but the people who assigned ISO639-3 codes (members of SIL) seem to have regarded the different varieties of Arabic as different enough to require them to be listed separately within a macrolanguage.
|
17,232 |
ISO 639-3 has many language codes for Arabic, but only one for English.
I'm an Arab who is familiar with multiple Arabic dialects. We do not call it anything but "لهجات" which is translated to "dialects".
We also call it "عامية" which is translated to "slang". I've never heard an Arabic man call its region's dialect a language. Yet the ISO classification for Arabic contain more languages than Arabic countries.
Arabic with over 30 language:
<http://www-01.sil.org/iso639-3/documentation.asp?id=ara>
English with just one:
<http://www-01.sil.org/iso639-3/documentation.asp?id=eng>
I know there are many difference between the American and British English. And there are differences between the South African, Canadian, North Ireland, Scottish and the Australian English. There is also the old Shakespeare period English language.
Still just one English language under the ISO 639-3.
**Update:** AFAIK No official reorganization for any dialect from any Arabic country. Arab countries teach only the main Standard Arabic language in schools and it's used in official documents.
It's the official language in the highest Arabic body, the [Arab League](language of the Arab <https://en.wikipedia.org/wiki/Arab_League>)
Also except for some variations in North Africa Arabs understand each other very clearly similar to different speaker of English (like English in India - English in Scotland).
|
2016/04/03
|
[
"https://linguistics.stackexchange.com/questions/17232",
"https://linguistics.stackexchange.com",
"https://linguistics.stackexchange.com/users/12873/"
] |
Are the languages spoken in various Arabian countries actually mutually intelligible? If no then it makes more sense to regard them as separate languages.
In China the government likes to officially categorize various Chinese languages as "dialects", but the reality is that the difference is really huge between some of them, e.g. comparing Mandarin and Cantonese is more like comparing Italian with Spanish than American English with British English. Most Mandarin speakers don't understand nor speak Cantonese at all. Therefore there are many language codes for various Chinese languages as well and it makes sense to me.
I wonder whether the situation is similar in Arabic: If you can't even understand some of the Northern African Arabic then how can you claim they're the "same language"? Some people might try to do so politically but linguistically it would be far-fetched. The situation is just fundamentally different from American vs. British English I suppose.
|
ISO639-3 is derived from [The Ethnologue](http://www.ethnologue.com/). The author of this work have a certain point of view on the definition of "language" (vs. "dialect") with a strong tendency to split languages into smaller units. Note that the authors of the Ethnologue have a open agenda that is different from doing science. Divide and Conquer.
|
17,232 |
ISO 639-3 has many language codes for Arabic, but only one for English.
I'm an Arab who is familiar with multiple Arabic dialects. We do not call it anything but "لهجات" which is translated to "dialects".
We also call it "عامية" which is translated to "slang". I've never heard an Arabic man call its region's dialect a language. Yet the ISO classification for Arabic contain more languages than Arabic countries.
Arabic with over 30 language:
<http://www-01.sil.org/iso639-3/documentation.asp?id=ara>
English with just one:
<http://www-01.sil.org/iso639-3/documentation.asp?id=eng>
I know there are many difference between the American and British English. And there are differences between the South African, Canadian, North Ireland, Scottish and the Australian English. There is also the old Shakespeare period English language.
Still just one English language under the ISO 639-3.
**Update:** AFAIK No official reorganization for any dialect from any Arabic country. Arab countries teach only the main Standard Arabic language in schools and it's used in official documents.
It's the official language in the highest Arabic body, the [Arab League](language of the Arab <https://en.wikipedia.org/wiki/Arab_League>)
Also except for some variations in North Africa Arabs understand each other very clearly similar to different speaker of English (like English in India - English in Scotland).
|
2016/04/03
|
[
"https://linguistics.stackexchange.com/questions/17232",
"https://linguistics.stackexchange.com",
"https://linguistics.stackexchange.com/users/12873/"
] |
Unifying and subdividing speech forms under an ISO code is not a rigorous ontological claim: it is the standardization statement "this linguistic thing is to be abbreviated that way". "Quechua", "Luyia", and "Arabic" (also "Latvian") are examples of macrolanguages, under ISO 639-3. The individual languages are different enough that they are not *all* mutually intelligible. Cypriot, Juba Arabic (pga), and Chadian are quite different, and it is well-known that Moroccan Arabic is "challenging". I haven't experiences Tajiki or Uzbeki Arabic but I don't find the claims to be too incredible: we can leave it at that (I am skeptical about N and S Levantine by the mutual intelligibility criterion). The point is that there are significant linguistic differences between these varieties of Arabic, and linguists have documented even more differences than are presently recognized in the ISO system. (See for example the numerous varieties documented in T. Prochazka's book *Saudi Arabian dialects*). All of the forms are still unified with a single identifier *ara* which refers to the Arabic macrolanguage; individual varieties also have their identifiers. The [Glottolog system](http://glottolog.org/resource/languoid/id/arab1395) makes even more distinctions (40) – subsuming Maltese under their arab1395 (not included under *ara* in the ISO system), subdividing Libyan Arabic into 4 varieties.
The same is true of the various Luyia languages, which are unified under *luy*, but also distinguished with particular identifiers (*lts* for Tachoni, *lri* for Marachi, and so on); idem the Quechua languages. Somali is presently not indicated as a "macrolanguage", it is an individual language, but the main reason for the failure to subdivide is the lack of information on the extent of difference.
It is thus not surprising that these languages enjoy subdivisions in ISO 639-3 classification. What *is* somewhat surprising is that there is no subdivision in the ISO analysis of English, where there are dozens of varieties that are mutually unintelligible in the same say that Moroccan, Syrian and Juba Arabic are. Glottolog does, however, subdivide ("Mercian") [English](http://glottolog.org/resource/languoid/id/macr1271) into 35 varieties, plus 4 Scots varieties (which ISO registers as a distinct language, *sco*, from English).
|
ISO639-3 is derived from [The Ethnologue](http://www.ethnologue.com/). The author of this work have a certain point of view on the definition of "language" (vs. "dialect") with a strong tendency to split languages into smaller units. Note that the authors of the Ethnologue have a open agenda that is different from doing science. Divide and Conquer.
|
17,232 |
ISO 639-3 has many language codes for Arabic, but only one for English.
I'm an Arab who is familiar with multiple Arabic dialects. We do not call it anything but "لهجات" which is translated to "dialects".
We also call it "عامية" which is translated to "slang". I've never heard an Arabic man call its region's dialect a language. Yet the ISO classification for Arabic contain more languages than Arabic countries.
Arabic with over 30 language:
<http://www-01.sil.org/iso639-3/documentation.asp?id=ara>
English with just one:
<http://www-01.sil.org/iso639-3/documentation.asp?id=eng>
I know there are many difference between the American and British English. And there are differences between the South African, Canadian, North Ireland, Scottish and the Australian English. There is also the old Shakespeare period English language.
Still just one English language under the ISO 639-3.
**Update:** AFAIK No official reorganization for any dialect from any Arabic country. Arab countries teach only the main Standard Arabic language in schools and it's used in official documents.
It's the official language in the highest Arabic body, the [Arab League](language of the Arab <https://en.wikipedia.org/wiki/Arab_League>)
Also except for some variations in North Africa Arabs understand each other very clearly similar to different speaker of English (like English in India - English in Scotland).
|
2016/04/03
|
[
"https://linguistics.stackexchange.com/questions/17232",
"https://linguistics.stackexchange.com",
"https://linguistics.stackexchange.com/users/12873/"
] |
"Also except for some variations in North Africa Arabs" - this isn't just "some variations" - Moroccan Arabic and Tunisian Arabic are significantly different from Lebanese or Saudi (and from each other as well - with Algerian being a sort of middle between the two), far more so than British and American, more like the difference between Portuguese and Spanish or Spanish and Italian.
As to people being able to understand each other, especially across the Middle Eastern variants of Arabic, that has a lot more to do with TV and Pop Music than with linguistic unity. Everybody understands Egyptian for example, because of exposure to Egyptian movies, but if you examine Egyptian Arabic, it is actually very different from other forms of Arabic.
As a native speaker of Arabic myself (Maghrebi Arabic), I would argue that Arabic as a single language with the different regional variations being mere dialects or slang has a lot more to do with Arab nationalism than it does with proper linguistic classification.
|
ISO639-3 is derived from [The Ethnologue](http://www.ethnologue.com/). The author of this work have a certain point of view on the definition of "language" (vs. "dialect") with a strong tendency to split languages into smaller units. Note that the authors of the Ethnologue have a open agenda that is different from doing science. Divide and Conquer.
|
17,232 |
ISO 639-3 has many language codes for Arabic, but only one for English.
I'm an Arab who is familiar with multiple Arabic dialects. We do not call it anything but "لهجات" which is translated to "dialects".
We also call it "عامية" which is translated to "slang". I've never heard an Arabic man call its region's dialect a language. Yet the ISO classification for Arabic contain more languages than Arabic countries.
Arabic with over 30 language:
<http://www-01.sil.org/iso639-3/documentation.asp?id=ara>
English with just one:
<http://www-01.sil.org/iso639-3/documentation.asp?id=eng>
I know there are many difference between the American and British English. And there are differences between the South African, Canadian, North Ireland, Scottish and the Australian English. There is also the old Shakespeare period English language.
Still just one English language under the ISO 639-3.
**Update:** AFAIK No official reorganization for any dialect from any Arabic country. Arab countries teach only the main Standard Arabic language in schools and it's used in official documents.
It's the official language in the highest Arabic body, the [Arab League](language of the Arab <https://en.wikipedia.org/wiki/Arab_League>)
Also except for some variations in North Africa Arabs understand each other very clearly similar to different speaker of English (like English in India - English in Scotland).
|
2016/04/03
|
[
"https://linguistics.stackexchange.com/questions/17232",
"https://linguistics.stackexchange.com",
"https://linguistics.stackexchange.com/users/12873/"
] |
Are the languages spoken in various Arabian countries actually mutually intelligible? If no then it makes more sense to regard them as separate languages.
In China the government likes to officially categorize various Chinese languages as "dialects", but the reality is that the difference is really huge between some of them, e.g. comparing Mandarin and Cantonese is more like comparing Italian with Spanish than American English with British English. Most Mandarin speakers don't understand nor speak Cantonese at all. Therefore there are many language codes for various Chinese languages as well and it makes sense to me.
I wonder whether the situation is similar in Arabic: If you can't even understand some of the Northern African Arabic then how can you claim they're the "same language"? Some people might try to do so politically but linguistically it would be far-fetched. The situation is just fundamentally different from American vs. British English I suppose.
|
"Also except for some variations in North Africa Arabs" - this isn't just "some variations" - Moroccan Arabic and Tunisian Arabic are significantly different from Lebanese or Saudi (and from each other as well - with Algerian being a sort of middle between the two), far more so than British and American, more like the difference between Portuguese and Spanish or Spanish and Italian.
As to people being able to understand each other, especially across the Middle Eastern variants of Arabic, that has a lot more to do with TV and Pop Music than with linguistic unity. Everybody understands Egyptian for example, because of exposure to Egyptian movies, but if you examine Egyptian Arabic, it is actually very different from other forms of Arabic.
As a native speaker of Arabic myself (Maghrebi Arabic), I would argue that Arabic as a single language with the different regional variations being mere dialects or slang has a lot more to do with Arab nationalism than it does with proper linguistic classification.
|
17,232 |
ISO 639-3 has many language codes for Arabic, but only one for English.
I'm an Arab who is familiar with multiple Arabic dialects. We do not call it anything but "لهجات" which is translated to "dialects".
We also call it "عامية" which is translated to "slang". I've never heard an Arabic man call its region's dialect a language. Yet the ISO classification for Arabic contain more languages than Arabic countries.
Arabic with over 30 language:
<http://www-01.sil.org/iso639-3/documentation.asp?id=ara>
English with just one:
<http://www-01.sil.org/iso639-3/documentation.asp?id=eng>
I know there are many difference between the American and British English. And there are differences between the South African, Canadian, North Ireland, Scottish and the Australian English. There is also the old Shakespeare period English language.
Still just one English language under the ISO 639-3.
**Update:** AFAIK No official reorganization for any dialect from any Arabic country. Arab countries teach only the main Standard Arabic language in schools and it's used in official documents.
It's the official language in the highest Arabic body, the [Arab League](language of the Arab <https://en.wikipedia.org/wiki/Arab_League>)
Also except for some variations in North Africa Arabs understand each other very clearly similar to different speaker of English (like English in India - English in Scotland).
|
2016/04/03
|
[
"https://linguistics.stackexchange.com/questions/17232",
"https://linguistics.stackexchange.com",
"https://linguistics.stackexchange.com/users/12873/"
] |
Unifying and subdividing speech forms under an ISO code is not a rigorous ontological claim: it is the standardization statement "this linguistic thing is to be abbreviated that way". "Quechua", "Luyia", and "Arabic" (also "Latvian") are examples of macrolanguages, under ISO 639-3. The individual languages are different enough that they are not *all* mutually intelligible. Cypriot, Juba Arabic (pga), and Chadian are quite different, and it is well-known that Moroccan Arabic is "challenging". I haven't experiences Tajiki or Uzbeki Arabic but I don't find the claims to be too incredible: we can leave it at that (I am skeptical about N and S Levantine by the mutual intelligibility criterion). The point is that there are significant linguistic differences between these varieties of Arabic, and linguists have documented even more differences than are presently recognized in the ISO system. (See for example the numerous varieties documented in T. Prochazka's book *Saudi Arabian dialects*). All of the forms are still unified with a single identifier *ara* which refers to the Arabic macrolanguage; individual varieties also have their identifiers. The [Glottolog system](http://glottolog.org/resource/languoid/id/arab1395) makes even more distinctions (40) – subsuming Maltese under their arab1395 (not included under *ara* in the ISO system), subdividing Libyan Arabic into 4 varieties.
The same is true of the various Luyia languages, which are unified under *luy*, but also distinguished with particular identifiers (*lts* for Tachoni, *lri* for Marachi, and so on); idem the Quechua languages. Somali is presently not indicated as a "macrolanguage", it is an individual language, but the main reason for the failure to subdivide is the lack of information on the extent of difference.
It is thus not surprising that these languages enjoy subdivisions in ISO 639-3 classification. What *is* somewhat surprising is that there is no subdivision in the ISO analysis of English, where there are dozens of varieties that are mutually unintelligible in the same say that Moroccan, Syrian and Juba Arabic are. Glottolog does, however, subdivide ("Mercian") [English](http://glottolog.org/resource/languoid/id/macr1271) into 35 varieties, plus 4 Scots varieties (which ISO registers as a distinct language, *sco*, from English).
|
"Also except for some variations in North Africa Arabs" - this isn't just "some variations" - Moroccan Arabic and Tunisian Arabic are significantly different from Lebanese or Saudi (and from each other as well - with Algerian being a sort of middle between the two), far more so than British and American, more like the difference between Portuguese and Spanish or Spanish and Italian.
As to people being able to understand each other, especially across the Middle Eastern variants of Arabic, that has a lot more to do with TV and Pop Music than with linguistic unity. Everybody understands Egyptian for example, because of exposure to Egyptian movies, but if you examine Egyptian Arabic, it is actually very different from other forms of Arabic.
As a native speaker of Arabic myself (Maghrebi Arabic), I would argue that Arabic as a single language with the different regional variations being mere dialects or slang has a lot more to do with Arab nationalism than it does with proper linguistic classification.
|
15,649,184 |
Im trying to get different images to load when hovering over the different image map zones. Is this even possible with htlm/css or java? If so how?
Thanks
Here's my code so far:
```
<img id="navbar" src="img/index-navbar.png" usemap="#navmap"/>
<map name="navmap">
<area id="index-hover" shape="poly" coords="0,113,125,77,126,129,0,168,0,113" href="index.html" alt="" title="" />
<area id="selfstudy-hover" shape="poly" coords="127,77,281,66,271,118,128,129,127,77" href="selfstudy.html" alt="" title="" />
<area id="exhibits-hover" shape="poly" coords="284,66,432,73,433,123,274,118,284,66" href="exhibits.html" alt="" title="" />
<area shape="poly" coords="434,73,602,87,593,138,435,123,434,73" href="committees.html" alt="" title="" />
<area shape="poly" coords="605,88,787,98,788,150,597,139,605,88" href="newsletters.html" alt="" title="" />
<area shape="poly" coords="789,98,852,95,959,59,959,114,887,143,789,151,789,98" href="selfstudy-design.html" alt="" title="" />
</map>
```
|
2013/03/26
|
[
"https://Stackoverflow.com/questions/15649184",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1899891/"
] |
hopefully this helps, i did something like this years ago on specialolympics.org
your html
```
<div class="world_map_container">
<img src="http://www.specialolympics.org/RegionsImages/map/transparent.gif" usemap="#the_world_map" id="transparent_map">
<img src="http://www.specialolympics.org/RegionsImages/map/world_map.png"><map name="the_world_map" id="the_world_map">
<area shape="poly" coords="69,86,83,71,83,51,70,30,52,16,18,36,5,53,23,74,53,83," href="http://www.specialolympics.org/Regions/north-america/_Region-Front/North-America.aspx" id="area_northamerica">
<area shape="poly" coords="63,94,77,89,99,99,87,138,72,138,63,108," href="http://www.specialolympics.org/Regions/latin-america/_Region-Front/Latin-America.aspx" id="area_southamerica">
<area shape="poly" coords="120,70,178,63,220,60,262,57,232,28,191,29,147,32,122,62," href="http://www.specialolympics.org/Regions/europe-eurasia/_Region-Front/Europe-Eurasia.aspx" id="area_eurasia">
<area shape="poly" coords="115,94,134,92,146,90,167,99,160,122,131,125,120,106," href="http://www.specialolympics.org/Regions/africa/_Region-Front/Africa.aspx" id="area_africa">
<area shape="poly" coords="112,84,137,87,152,87,152,80,139,74,120,79," href="http://www.specialolympics.org/Regions/middle-east-north-africa/_Region-Front/Middle-East-North-Africa.aspx" id="area_middleeast">
<area shape="poly" coords="209,68,202,71,190,73,186,81,195,85,206,88,216,84,216,75," href="http://www.specialolympics.org/Regions/east-asia/_Region-Section-Front/East-Asia.aspx" id="area_eastasia">
<area shape="poly" coords="192,96,218,91,248,100,259,132,218,133,199,120,197,110," href="http://www.specialolympics.org/Regions/asia-pacific/_Region-Front/Asia-Pacific.aspx" id="area_asiapacific">
</map>
<ul>
<li id="northamerica" style=""><a href="#">north america</a></li>
<li id="southamerica"><a href="#">south america</a></li><li id="eurasia"><a href="#">eurasia</a></li>
<li id="africa"><a href="#">Africa</a></li><li id="middleeast"><a href="#">Middle East</a></li>
<li id="eastasia"><a href="#">East Asia</a></li><li id="asiapacific"><a href="#">Asia Pacific</a></li>
</ul>
</div>
```
your css
```
div.world_map_container #transparent_map {
border: medium none;
height: 140px;
position: absolute;
width: 270px;
z-index: 30;
}
ul li {
display: none;
position: absolute;
text-indent: -9999px;
z-index: 20;
}
#northamerica {
background: url("/RegionsImages/map/north_america.png") no-repeat scroll 0 0 transparent;
height: 140px;
right: 0;
top: 0;
width: 270px;
}
#southamerica {
background: url("/RegionsImages/map/south_america.png") no-repeat scroll 0 0 transparent;
height: 140px;
right: 0;
top: 0;
width: 270px;
}
```
your js
```
$('.world_map_container area').each(function () {
// Assigning an action to the mouseover event
$(this).mouseover(function (e) {
var country_id = $(this).attr('id').replace('area_', '');
$('#' + country_id).css('display', 'block');
});
// Assigning an action to the mouseout event
$(this).mouseout(function (e) {
var country_id = $(this).attr('id').replace('area_', '');
$('#' + country_id).css('display', 'none');
});
});
```
you can see on this site now on the right rail <http://specialolympics.org/>
essentially you place a transparent image over the load image and you switch out map area on the hover and replace with each background area.
|
I did something similar to this yeeeeeaaaaaarrrrssss ago using CSS and JS. [View and deconstruct the code here.](http://www.mackie.com/products/hrmk2series/cutaway/diagram.html)
You could probably do it with pure CSS these days as there's unified browser support for it. I would do absolutely positioned divs over a background and then use `a {display: none;} a:hover {display: block;}` to make your images show up. Image maps are soooo 20th century ;)
...unless of course you want them to do things onClick, which would still require JavaScript.
|
31,163,728 |
I am using the CSVJDBC driver for retrieving results from CSV files. All record fields are interpreted as Strings. How can I utilise the MAX aggregate function in order to obtain the maximim Integer of a column? As far as I know, csvjdbc does not support casting.
Consider this sample file:
```
sequenceNumber,decimalNumber,randomInteger,email,testNumber
0,0.4868176550817932,560801,[email protected],0.0
1,0.9889360969432277,903488,[email protected],1.0
2,0.8161798688893893,367870,[email protected],2.0
3,0.926163166852633,588581,[email protected],3.0
4,0.05084859872223901,563000,[email protected],4.0
5,0.7636864392027013,375299,[email protected],5.0
6,0.31433980690632457,544036,[email protected],6.0
7,0.4061012200967966,41792,[email protected],7.0
8,0.3541002754332119,196272,[email protected],8.0
9,0.4189826302561652,798405,[email protected],9.0
10,0.9076084714059381,135783,[email protected],10.0
11,0.565716974613909,865847,[email protected],11.0
12,0.9484076609924861,224744,[email protected],12.0
13,0.05223710002804138,977787,[email protected],13.0
15,0.6270851001160621,469901,[email protected],14.0
```
I use the following code snippet:
```
import org.relique.jdbc.csv.CsvDriver;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class CSVDemo
{
public static void main(String[] args)
{
try
{
// Load the driver.
Class.forName("org.relique.jdbc.csv.CsvDriver");
// Create a connection. The first command line parameter is
// the directory containing the .csv files.
// A single connection is thread-safe for use by several threads.
String CSVDIRECTORY = "/tmp/csv-directory/";
String CSVDB ="mediumList";
Connection conn = DriverManager.getConnection("jdbc:relique:csv:" + CSVDIRECTORY);
// Create a Statement object to execute the query with.
// A Statement is not thread-safe.
Statement stmt = conn.createStatement();
ResultSet results = stmt.executeQuery("SELECT MAX(decimalNumber) FROM "+CSVDB);
// Dump out the results to a CSV file with the same format
// using CsvJdbc helper function
boolean append = true;
CsvDriver.writeToCsv(results, System.out, append);
// Clean up
conn.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
```
When I execute the query
I get as expected:
```
MAX([DECIMALNUMBER])
0.9889360969432277
```
But when I want the maximum sequenceNumber, which is 19 with this
```
ResultSet results = stmt.executeQuery("SELECT MAX(sequenceNumber) FROM "+CSVDB);
```
I get 9 as a result:
```
MAX([SEQUENCENUMBER])
9
```
It works for the decimalNumber and it also works for the text. It does not work for testNumber, as csvjdbs returns the lexicographic largest value instead of the Integer value. Is there a possibility to solve this directly or to I need to fetch all records and select the maximum value with Java?
Basic Solution:
===============
This is my basic solution, which needs to fetch all the numbers first:
```
ResultSet results = stmt.executeQuery("SELECT sequenceNumber FROM "+CSVDB);
int max=-1;
while(results.next()){
String sum = results.getString(1);
int currentSeq = Integer.parseInt(sum);
System.out.println("current_ "+sum);
if(currentSeq>max){
max=currentSeq;
}
```
Is there a more elegant way?
Solution based on Joop Eggen
============================
```
public int getMaxSequenceAggregate() {
int max = 0;
try {
Properties props = new Properties();
Connection connection;
props.put("columnTypes", "Int,Double,Int,String,Int");
connection = DriverManager.getConnection("jdbc:relique:csv:" + this.directoryPath, props);
PreparedStatement statement = null;
ResultSet result;
statement = connection.prepareStatement("SELECT MAX(sequenceNumber) FROM " + this.filePath);
result = statement.executeQuery();
while (result.next()) {
max = result.getInt(1);
LOGGER.info("maximum sequence: " + max);
}
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
return max;
}
```
|
2015/07/01
|
[
"https://Stackoverflow.com/questions/31163728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1206601/"
] |
You should better specify the column types as it seems the first column is taken as String, where `"9" > "10"`.
```
Properties props = new Properties();
props.put("columnTypes", "Integer,Double,Integer,String,Integer");
Connection conn = DriverManager.getConnection("jdbc:relique:csv:" + CSVDIRECTORY, props);
```
|
As follows from the [CSV/JDBC documentation](http://csvjdbc.sourceforge.net/doc.html):
>
> If columnTypes is set to an empty string then column types are inferred from the data.
>
>
>
Which I guess is desirable in most use cases.
So, using [Joop Eggen](https://stackoverflow.com/users/984823/joop-eggen)'s example this can be simplified as:
```
Properties props = new Properties();
props.put("columnTypes", "");
Connection conn = DriverManager.getConnection("jdbc:relique:csv:" + CSVDIRECTORY, props);
```
I tried this and it demonstrates dynamic type detection similar to other JDBC drivers.
Wonder why this is not the default setting though.
|
1,132,846 |
Let $f: \mathbb{R^n} \to \mathbb{R^n}$ such that $f(x)= ||x||^2 x$. I want to show that $f$ is bijective.
We know local bijection using inverse function theorem at all points other than zero.Can we say a global inverse exists?
|
2015/02/04
|
[
"https://math.stackexchange.com/questions/1132846",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/138157/"
] |
It is convenient to write your function as
$$f(x) = ||x||^3 \cdot \frac{x}{||x||}$$
More generally, you can have
$$f(x) = \phi(||x||) \cdot \frac{x}{||x||}$$
It is perhaps safe to assume extra that $\phi(0) = 0$. Now, if your function of $1$ variable $\phi\colon [0, \infty)\to [0, \infty)$ is bijective then $f$ is also bijective and the inverse will be
$$f^{-1}(y) = \phi^{-1}(||y||) \cdot \frac{y}{||y||}$$
Check how it works in our example.
|
**Hint**
$$\big\| \lVert x\rVert^2 x \big\| = \| x \|^3$$
To prove 1-1, if $f(x)=f(y)$ use the above to show first that $\|x\|=\|y\|$.
To prove onto, if for given $x$ you want $f(x)=y$ what does the hint tell you about $\|x \|$ and $\| y\|$?
|
20,225,726 |
I have a working solution to automatically refresh content on a web page by using the Javascript function:
```
window.setInterval(function()
{
}, 1000);
```
But this creates a number of GET requests when viewing the development console:

Whereas in comparison to other websites which use a method of AJAX to refresh page content.. There is only one at the most 2 requests in the development console? So just by doing this, where have I gone wrong? Because I can see a possible downfall with the current solution.. The entire code:
```
<script>
window.setInterval(function()
{
$(function ()
{
$.ajax({
url: 'Ajax/AjaxRecentEnteries.php', data: "", dataType: 'json', success: function(rows)
{
$('#output').empty();
for (var i in rows)
{
var row = rows[i];
var id = row[0];
var Title = row[1];
var Cat = row[2]
$('#output').append("<br>Page: <a href=Page.php?ID="+id+">"+Title+"</a>");
}
}
});
});
}, 1000);
</script>
```
|
2013/11/26
|
[
"https://Stackoverflow.com/questions/20225726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2360657/"
] |
The only way to sort cross-tab columns via designer is choosing between descending or ascending order, this means crystal report will order your fields by alphabetical order.
A possible workaround is, for example, putting numbers with an underscore before the string you want to order in your datasource (like 01\_July (2012), 02\_August (2012)...13\_June (2013)) and use the order ascending, then to hide the numbers, go in the "cross-tab expert" section and on the cross-tab tab choose "group option" under the columns (sorry I only have it in Italian)

and on the option tab choose the options below

click on the formula button and use the function
```
Right(yourField,Length(yourField)-3)
```
to exclude the prefix so you will not have "01\_July (2012)" on the cross-tab colum but "July (2012)". This should do the trick
|
Another use-full workaround is.
create a new formula say `column1` =
`ToText({yourField}, "yyyy") + '-' + ToText({yourField},"MM")`.
use this field as cross tab column.
now your cross tab columns will be sorted as
`2020-01 | 2020-02 | 2020-03 |...`
now Cross-Tab expert> columns> Group Options > tab: Options > ✓ customize Group Name field > ✓ use a formula as group name.
add `Left({@column1}, 5) & MonthName(ToNumber(Right({@column1}, 2)),True)`
thus final outcome
`2020-Jan | 2020-Feb | 2020-Mar |...`
sorted columns based on month date but printed by month name!
|
26,175,561 |
Say I have 5 vectors:
```
a <- c(1,2,3)
b <- c(2,3,4)
c <- c(1,2,5,8)
d <- c(2,3,4,6)
e <- c(2,7,8,9)
```
I know I can calculate the intersection between all of them by using `Reduce()` together with `intersect()`, like this:
```
Reduce(intersect, list(a, b, c, d, e))
[1] 2
```
But how can I find elements that are common in, say, at least 2 vectors? i.e.:
```
[1] 1 2 3 4 8
```
|
2014/10/03
|
[
"https://Stackoverflow.com/questions/26175561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1540663/"
] |
It is much simpler than a lot of people are making it look. This should be very efficient.
1. Put everything into a vector:
```
x <- unlist(list(a, b, c, d, e))
```
2. Look for duplicates
```
unique(x[duplicated(x)])
# [1] 2 3 1 4 8
```
and `sort` if needed.
Note: In case there can be duplicates within a list element (which your example does not seem to implicate), then replace `x` with `x <- unlist(lapply(list(a, b, c, d, e), unique))`
---
Edit: as the OP has expressed interest in a more general solution where n >= 2, I would do:
```
which(tabulate(x) >= n)
```
if the data is only made of natural integers (1, 2, etc.) as in the example. If not:
```
f <- table(x)
names(f)[f >= n]
```
This is now not too far from James solution but it avoids the costly-ish `sort`. And it is miles faster than computing all possible combinations.
|
You could try all possible combinations, for example:
```
## create a list
l <- list(a, b, c, d)
## get combinations
cbn <- combn(1:length(l), 2)
## Intersect them
unique(unlist(apply(cbn, 2, function(x) intersect(l[[x[1]]], l[[x[2]]]))))
## 2 3 1 4
```
|
26,175,561 |
Say I have 5 vectors:
```
a <- c(1,2,3)
b <- c(2,3,4)
c <- c(1,2,5,8)
d <- c(2,3,4,6)
e <- c(2,7,8,9)
```
I know I can calculate the intersection between all of them by using `Reduce()` together with `intersect()`, like this:
```
Reduce(intersect, list(a, b, c, d, e))
[1] 2
```
But how can I find elements that are common in, say, at least 2 vectors? i.e.:
```
[1] 1 2 3 4 8
```
|
2014/10/03
|
[
"https://Stackoverflow.com/questions/26175561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1540663/"
] |
It is much simpler than a lot of people are making it look. This should be very efficient.
1. Put everything into a vector:
```
x <- unlist(list(a, b, c, d, e))
```
2. Look for duplicates
```
unique(x[duplicated(x)])
# [1] 2 3 1 4 8
```
and `sort` if needed.
Note: In case there can be duplicates within a list element (which your example does not seem to implicate), then replace `x` with `x <- unlist(lapply(list(a, b, c, d, e), unique))`
---
Edit: as the OP has expressed interest in a more general solution where n >= 2, I would do:
```
which(tabulate(x) >= n)
```
if the data is only made of natural integers (1, 2, etc.) as in the example. If not:
```
f <- table(x)
names(f)[f >= n]
```
This is now not too far from James solution but it avoids the costly-ish `sort`. And it is miles faster than computing all possible combinations.
|
A variation of @rengis method would be:
```
unique(unlist(Map(`intersect`, cbn[1,], cbn[2,])))
#[1] 2 3 1 4 8
```
where,
```
l <- mget(letters[1:5])
cbn <- combn(l,2)
```
|
26,175,561 |
Say I have 5 vectors:
```
a <- c(1,2,3)
b <- c(2,3,4)
c <- c(1,2,5,8)
d <- c(2,3,4,6)
e <- c(2,7,8,9)
```
I know I can calculate the intersection between all of them by using `Reduce()` together with `intersect()`, like this:
```
Reduce(intersect, list(a, b, c, d, e))
[1] 2
```
But how can I find elements that are common in, say, at least 2 vectors? i.e.:
```
[1] 1 2 3 4 8
```
|
2014/10/03
|
[
"https://Stackoverflow.com/questions/26175561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1540663/"
] |
You could try all possible combinations, for example:
```
## create a list
l <- list(a, b, c, d)
## get combinations
cbn <- combn(1:length(l), 2)
## Intersect them
unique(unlist(apply(cbn, 2, function(x) intersect(l[[x[1]]], l[[x[2]]]))))
## 2 3 1 4
```
|
Yet another approach, applying a vectorised function with `outer`:
```
L <- list(a, b, c, d, e)
f <- function(x, y) intersect(x, y)
fv <- Vectorize(f, list("x","y"))
o <- outer(L, L, fv)
table(unlist(o[upper.tri(o)]))
# 1 2 3 4 8
# 1 10 3 1 1
```
The output above gives the number of pairs of vectors that share each of the duplicated elements 1, 2, 3, 4, and 8.
|
26,175,561 |
Say I have 5 vectors:
```
a <- c(1,2,3)
b <- c(2,3,4)
c <- c(1,2,5,8)
d <- c(2,3,4,6)
e <- c(2,7,8,9)
```
I know I can calculate the intersection between all of them by using `Reduce()` together with `intersect()`, like this:
```
Reduce(intersect, list(a, b, c, d, e))
[1] 2
```
But how can I find elements that are common in, say, at least 2 vectors? i.e.:
```
[1] 1 2 3 4 8
```
|
2014/10/03
|
[
"https://Stackoverflow.com/questions/26175561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1540663/"
] |
It is much simpler than a lot of people are making it look. This should be very efficient.
1. Put everything into a vector:
```
x <- unlist(list(a, b, c, d, e))
```
2. Look for duplicates
```
unique(x[duplicated(x)])
# [1] 2 3 1 4 8
```
and `sort` if needed.
Note: In case there can be duplicates within a list element (which your example does not seem to implicate), then replace `x` with `x <- unlist(lapply(list(a, b, c, d, e), unique))`
---
Edit: as the OP has expressed interest in a more general solution where n >= 2, I would do:
```
which(tabulate(x) >= n)
```
if the data is only made of natural integers (1, 2, etc.) as in the example. If not:
```
f <- table(x)
names(f)[f >= n]
```
This is now not too far from James solution but it avoids the costly-ish `sort`. And it is miles faster than computing all possible combinations.
|
When the vector is huge, solutions like `duplicated` or `tabulate` might overflow your system. In that case, dplyr comes in handy with the following code
```
library(dplyr) combination_of_vectors <- c(a, b, c, d, e)
#For more than 1
combination_of_vectors %>% as_tibble() %>% group_by(x) %>% filter(n()>1)
#For more than 2
combination_of_vectors %>% as_tibble() %>% group_by(x) %>% filter(n()>2)
#For more than 3
combination_of_vectors %>% as_tibble() %>% group_by(x) %>% filter(n()>2)
```
Hope it helps somebody
|
26,175,561 |
Say I have 5 vectors:
```
a <- c(1,2,3)
b <- c(2,3,4)
c <- c(1,2,5,8)
d <- c(2,3,4,6)
e <- c(2,7,8,9)
```
I know I can calculate the intersection between all of them by using `Reduce()` together with `intersect()`, like this:
```
Reduce(intersect, list(a, b, c, d, e))
[1] 2
```
But how can I find elements that are common in, say, at least 2 vectors? i.e.:
```
[1] 1 2 3 4 8
```
|
2014/10/03
|
[
"https://Stackoverflow.com/questions/26175561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1540663/"
] |
It is much simpler than a lot of people are making it look. This should be very efficient.
1. Put everything into a vector:
```
x <- unlist(list(a, b, c, d, e))
```
2. Look for duplicates
```
unique(x[duplicated(x)])
# [1] 2 3 1 4 8
```
and `sort` if needed.
Note: In case there can be duplicates within a list element (which your example does not seem to implicate), then replace `x` with `x <- unlist(lapply(list(a, b, c, d, e), unique))`
---
Edit: as the OP has expressed interest in a more general solution where n >= 2, I would do:
```
which(tabulate(x) >= n)
```
if the data is only made of natural integers (1, 2, etc.) as in the example. If not:
```
f <- table(x)
names(f)[f >= n]
```
This is now not too far from James solution but it avoids the costly-ish `sort`. And it is miles faster than computing all possible combinations.
|
Here's another option:
```
# For each vector, get a vector of values without duplicates
deduplicated_vectors <- lapply(list(a,b,c,d,e), unique)
# Flatten the lists, then sort and use rle to determine how many
# lists each value appears in
rl <- rle(sort(unlist(deduplicated_vectors)))
# Get the values that appear in two or more lists
rl$values[rl$lengths >= 2]
```
|
26,175,561 |
Say I have 5 vectors:
```
a <- c(1,2,3)
b <- c(2,3,4)
c <- c(1,2,5,8)
d <- c(2,3,4,6)
e <- c(2,7,8,9)
```
I know I can calculate the intersection between all of them by using `Reduce()` together with `intersect()`, like this:
```
Reduce(intersect, list(a, b, c, d, e))
[1] 2
```
But how can I find elements that are common in, say, at least 2 vectors? i.e.:
```
[1] 1 2 3 4 8
```
|
2014/10/03
|
[
"https://Stackoverflow.com/questions/26175561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1540663/"
] |
You could try all possible combinations, for example:
```
## create a list
l <- list(a, b, c, d)
## get combinations
cbn <- combn(1:length(l), 2)
## Intersect them
unique(unlist(apply(cbn, 2, function(x) intersect(l[[x[1]]], l[[x[2]]]))))
## 2 3 1 4
```
|
When the vector is huge, solutions like `duplicated` or `tabulate` might overflow your system. In that case, dplyr comes in handy with the following code
```
library(dplyr) combination_of_vectors <- c(a, b, c, d, e)
#For more than 1
combination_of_vectors %>% as_tibble() %>% group_by(x) %>% filter(n()>1)
#For more than 2
combination_of_vectors %>% as_tibble() %>% group_by(x) %>% filter(n()>2)
#For more than 3
combination_of_vectors %>% as_tibble() %>% group_by(x) %>% filter(n()>2)
```
Hope it helps somebody
|
26,175,561 |
Say I have 5 vectors:
```
a <- c(1,2,3)
b <- c(2,3,4)
c <- c(1,2,5,8)
d <- c(2,3,4,6)
e <- c(2,7,8,9)
```
I know I can calculate the intersection between all of them by using `Reduce()` together with `intersect()`, like this:
```
Reduce(intersect, list(a, b, c, d, e))
[1] 2
```
But how can I find elements that are common in, say, at least 2 vectors? i.e.:
```
[1] 1 2 3 4 8
```
|
2014/10/03
|
[
"https://Stackoverflow.com/questions/26175561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1540663/"
] |
You could try all possible combinations, for example:
```
## create a list
l <- list(a, b, c, d)
## get combinations
cbn <- combn(1:length(l), 2)
## Intersect them
unique(unlist(apply(cbn, 2, function(x) intersect(l[[x[1]]], l[[x[2]]]))))
## 2 3 1 4
```
|
A variation of @rengis method would be:
```
unique(unlist(Map(`intersect`, cbn[1,], cbn[2,])))
#[1] 2 3 1 4 8
```
where,
```
l <- mget(letters[1:5])
cbn <- combn(l,2)
```
|
26,175,561 |
Say I have 5 vectors:
```
a <- c(1,2,3)
b <- c(2,3,4)
c <- c(1,2,5,8)
d <- c(2,3,4,6)
e <- c(2,7,8,9)
```
I know I can calculate the intersection between all of them by using `Reduce()` together with `intersect()`, like this:
```
Reduce(intersect, list(a, b, c, d, e))
[1] 2
```
But how can I find elements that are common in, say, at least 2 vectors? i.e.:
```
[1] 1 2 3 4 8
```
|
2014/10/03
|
[
"https://Stackoverflow.com/questions/26175561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1540663/"
] |
You could try all possible combinations, for example:
```
## create a list
l <- list(a, b, c, d)
## get combinations
cbn <- combn(1:length(l), 2)
## Intersect them
unique(unlist(apply(cbn, 2, function(x) intersect(l[[x[1]]], l[[x[2]]]))))
## 2 3 1 4
```
|
This is an approach that counts the number of vectors each unique value occurs in.
```
unique_vals <- unique(c(a, b, c, d, e))
setNames(rowSums(!!(sapply(list(a, b, c, d, e), match, x = unique_vals)),
na.rm = TRUE), unique_vals)
# 1 2 3 4 5 8 6 7 9
# 2 5 3 2 1 2 1 1 1
```
|
26,175,561 |
Say I have 5 vectors:
```
a <- c(1,2,3)
b <- c(2,3,4)
c <- c(1,2,5,8)
d <- c(2,3,4,6)
e <- c(2,7,8,9)
```
I know I can calculate the intersection between all of them by using `Reduce()` together with `intersect()`, like this:
```
Reduce(intersect, list(a, b, c, d, e))
[1] 2
```
But how can I find elements that are common in, say, at least 2 vectors? i.e.:
```
[1] 1 2 3 4 8
```
|
2014/10/03
|
[
"https://Stackoverflow.com/questions/26175561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1540663/"
] |
It is much simpler than a lot of people are making it look. This should be very efficient.
1. Put everything into a vector:
```
x <- unlist(list(a, b, c, d, e))
```
2. Look for duplicates
```
unique(x[duplicated(x)])
# [1] 2 3 1 4 8
```
and `sort` if needed.
Note: In case there can be duplicates within a list element (which your example does not seem to implicate), then replace `x` with `x <- unlist(lapply(list(a, b, c, d, e), unique))`
---
Edit: as the OP has expressed interest in a more general solution where n >= 2, I would do:
```
which(tabulate(x) >= n)
```
if the data is only made of natural integers (1, 2, etc.) as in the example. If not:
```
f <- table(x)
names(f)[f >= n]
```
This is now not too far from James solution but it avoids the costly-ish `sort`. And it is miles faster than computing all possible combinations.
|
This is an approach that counts the number of vectors each unique value occurs in.
```
unique_vals <- unique(c(a, b, c, d, e))
setNames(rowSums(!!(sapply(list(a, b, c, d, e), match, x = unique_vals)),
na.rm = TRUE), unique_vals)
# 1 2 3 4 5 8 6 7 9
# 2 5 3 2 1 2 1 1 1
```
|
26,175,561 |
Say I have 5 vectors:
```
a <- c(1,2,3)
b <- c(2,3,4)
c <- c(1,2,5,8)
d <- c(2,3,4,6)
e <- c(2,7,8,9)
```
I know I can calculate the intersection between all of them by using `Reduce()` together with `intersect()`, like this:
```
Reduce(intersect, list(a, b, c, d, e))
[1] 2
```
But how can I find elements that are common in, say, at least 2 vectors? i.e.:
```
[1] 1 2 3 4 8
```
|
2014/10/03
|
[
"https://Stackoverflow.com/questions/26175561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1540663/"
] |
It is much simpler than a lot of people are making it look. This should be very efficient.
1. Put everything into a vector:
```
x <- unlist(list(a, b, c, d, e))
```
2. Look for duplicates
```
unique(x[duplicated(x)])
# [1] 2 3 1 4 8
```
and `sort` if needed.
Note: In case there can be duplicates within a list element (which your example does not seem to implicate), then replace `x` with `x <- unlist(lapply(list(a, b, c, d, e), unique))`
---
Edit: as the OP has expressed interest in a more general solution where n >= 2, I would do:
```
which(tabulate(x) >= n)
```
if the data is only made of natural integers (1, 2, etc.) as in the example. If not:
```
f <- table(x)
names(f)[f >= n]
```
This is now not too far from James solution but it avoids the costly-ish `sort`. And it is miles faster than computing all possible combinations.
|
Yet another approach, applying a vectorised function with `outer`:
```
L <- list(a, b, c, d, e)
f <- function(x, y) intersect(x, y)
fv <- Vectorize(f, list("x","y"))
o <- outer(L, L, fv)
table(unlist(o[upper.tri(o)]))
# 1 2 3 4 8
# 1 10 3 1 1
```
The output above gives the number of pairs of vectors that share each of the duplicated elements 1, 2, 3, 4, and 8.
|
68,380,054 |
I have a dataframe like this:
```
df = spark.createDataFrame(
[
(dt.datetime(2021, 5, 1, 10, 30, 0), 2.15, "a"),
(dt.datetime(2021, 5, 1, 10, 30, 10), 2.12, "a"),
(dt.datetime(2021, 5, 1, 10, 30, 20), 2.13, "a"),
(dt.datetime(2021, 5, 1, 10, 30, 50), 2.14, "a"),
(dt.datetime(2021, 5, 1, 10, 31, 5), 2.13, "a"),
(dt.datetime(2021, 5, 1, 10, 31, 10), 2.16, "a"),
(dt.datetime(2021, 5, 1, 10, 31, 10), 2.16, "b"),
],
["ts", "value", "group"]
)
```
I want to get the rank of the value column, using all the previous values (ordered by the timestamp ts). For example:
```
+-------------------+-----+-----+----+
| ts|value|group|rank|
+-------------------+-----+-----+----+
|2021-05-01 10:30:00| 2.15| a| 1|
|2021-05-01 10:30:10| 2.12| a| 1|
|2021-05-01 10:30:20| 2.13| a| 2|
|2021-05-01 10:30:50| 2.14| a| 3|
|2021-05-01 10:31:05| 2.13| a| 2|
|2021-05-01 10:31:10| 2.16| a| 5|
|2021-05-01 10:31:10| 2.16| b| 1|
+-------------------+-----+-----+----+
```
I tried the following code:
```
w = (
Window
.partitionBy("group")
.orderBy("ts")
.rowsBetween(Window.unboundedPreceding, Window.currentRow)
)
df.select(
"*",
f.rank().over(w).alias("rank")
).show()
```
but is basically ranking the columns only on the timestamp.
Any idea how to do it?
|
2021/07/14
|
[
"https://Stackoverflow.com/questions/68380054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6765102/"
] |
`rank` function ranks the data by `orderBy` clause, so you cannot rank it by another column. You can use this as an alternative
```
df = (df
.withColumn("rank", F.array_sort(F.collect_set('value').over(w)))
.withColumn('rank', F.expr("array_position(rank, value)")))
df.show()
+-------------------+-----+-----+----+
| ts|value|group|rank|
+-------------------+-----+-----+----+
|2021-05-01 10:31:10| 2.16| b| 1|
|2021-05-01 10:30:00| 2.15| a| 1|
|2021-05-01 10:30:10| 2.12| a| 1|
|2021-05-01 10:30:20| 2.13| a| 2|
|2021-05-01 10:30:50| 2.14| a| 3|
|2021-05-01 10:31:05| 2.13| a| 2|
|2021-05-01 10:31:10| 2.16| a| 5|
+-------------------+-----+-----+----+
```
if you want to get `dense_rank`, use `collect_list`
|
Chnage your **`orderBy()`** column to **value**
```
import datetime as dt
df = spark.createDataFrame(
[
(dt.datetime(2021, 5, 1, 10, 30, 0), 2.15, "a"),
(dt.datetime(2021, 5, 1, 10, 30, 10), 2.12, "a"),
(dt.datetime(2021, 5, 1, 10, 30, 20), 2.13, "a"),
(dt.datetime(2021, 5, 1, 10, 30, 50), 2.14, "a"),
(dt.datetime(2021, 5, 1, 10, 31, 5), 2.13, "a"),
(dt.datetime(2021, 5, 1, 10, 31, 10), 2.16, "b"),
(dt.datetime(2021, 5, 1, 10, 31, 11), 2.17, "b"),
],
["ts", "value", "group"]
)
w = (
W
.partitionBy("group")
.orderBy("value")
)
df.select(
"*",
F.rank().over(w).alias("rank")
).show()
+-------------------+-----+-----+----+
| ts|value|group|rank|
+-------------------+-----+-----+----+
|2021-05-01 10:30:10| 2.12| a| 1|
|2021-05-01 10:30:20| 2.13| a| 2|
|2021-05-01 10:31:05| 2.13| a| 2|
|2021-05-01 10:30:50| 2.14| a| 4|
|2021-05-01 10:30:00| 2.15| a| 5|
|2021-05-01 10:31:10| 2.16| b| 1|
|2021-05-01 10:31:11| 2.17| b| 2|
+-------------------+-----+-----+----+
```
|
20,775,504 |
If I have an array:
```
var array1=new Array();
array1[0]="two";
array1[1]="three";
array1[2]="four";
```
And another array:
```
var array2=new Array();
array2[0]="one";
array2[1]="two";
array2[2]="three";
array2[3]="four";
array2[4]="five";
```
How can I return a true value that Array1 exists in Array2?
|
2013/12/25
|
[
"https://Stackoverflow.com/questions/20775504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/632545/"
] |
Using set theory we know that A is a subset of B if and only if for every element of A there is an equivalent element in B.
I made a plnkr showing this: <http://plnkr.co/edit/9l5QplwWq1m7ZAkXV9PX>
Using a simple loop you could do it like this:
```
function isSubsetOf(arrayA, arrayB) {
for (var i = 0; i < arrayA.length;i++) {
var val = arrayA[i];
if (arrayB.indexOf(val) !== -1) {
continue;
} else {
return false;
}
}
return true;
}
```
|
convert array to list using `Arrays.asList(array2)` and same for array1 then call collections `contains` method
|
20,775,504 |
If I have an array:
```
var array1=new Array();
array1[0]="two";
array1[1]="three";
array1[2]="four";
```
And another array:
```
var array2=new Array();
array2[0]="one";
array2[1]="two";
array2[2]="three";
array2[3]="four";
array2[4]="five";
```
How can I return a true value that Array1 exists in Array2?
|
2013/12/25
|
[
"https://Stackoverflow.com/questions/20775504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/632545/"
] |
Try like this:
```
var arr1= ["two", "three"];
var arr2= ["two", "three", "four", "five"];
var isarraySubset = arr1.every(function(val) { return arr2.indexOf(val) >= 0; }));
console.log(isarraySubset ); // true
```
**Note:-**
This solution will work if your supported browsers are of ECMA-262 standard.
**According MDN**,
>
> "Tests whether all elements in the array pass the test implemented by
> the provided function."
>
>
>
Here is the signature of the method:
```
array.every(callback[, thisObject])
```
where `callback` is a function to test for each element, and `thisObject` refers to the object that we are testing array against
|
convert array to list using `Arrays.asList(array2)` and same for array1 then call collections `contains` method
|
20,775,504 |
If I have an array:
```
var array1=new Array();
array1[0]="two";
array1[1]="three";
array1[2]="four";
```
And another array:
```
var array2=new Array();
array2[0]="one";
array2[1]="two";
array2[2]="three";
array2[3]="four";
array2[4]="five";
```
How can I return a true value that Array1 exists in Array2?
|
2013/12/25
|
[
"https://Stackoverflow.com/questions/20775504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/632545/"
] |
Using set theory we know that A is a subset of B if and only if for every element of A there is an equivalent element in B.
I made a plnkr showing this: <http://plnkr.co/edit/9l5QplwWq1m7ZAkXV9PX>
Using a simple loop you could do it like this:
```
function isSubsetOf(arrayA, arrayB) {
for (var i = 0; i < arrayA.length;i++) {
var val = arrayA[i];
if (arrayB.indexOf(val) !== -1) {
continue;
} else {
return false;
}
}
return true;
}
```
|
```
var checkArray = [];
for ( var i; i<array1.length; i++ ){
if ( array2.indexOf( array1[i] ) !== -1 ) {
checkArray.push(array1[i]);
}
}
console.log("duplicate values : "+checkArray)// duplicate values : two,three,four
```
this may be not the most performant way ( i didnt test it, its pseudo-code) but at the end checkArray should contain all values of array1 that are in array2
|
20,775,504 |
If I have an array:
```
var array1=new Array();
array1[0]="two";
array1[1]="three";
array1[2]="four";
```
And another array:
```
var array2=new Array();
array2[0]="one";
array2[1]="two";
array2[2]="three";
array2[3]="four";
array2[4]="five";
```
How can I return a true value that Array1 exists in Array2?
|
2013/12/25
|
[
"https://Stackoverflow.com/questions/20775504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/632545/"
] |
Try like this:
```
var arr1= ["two", "three"];
var arr2= ["two", "three", "four", "five"];
var isarraySubset = arr1.every(function(val) { return arr2.indexOf(val) >= 0; }));
console.log(isarraySubset ); // true
```
**Note:-**
This solution will work if your supported browsers are of ECMA-262 standard.
**According MDN**,
>
> "Tests whether all elements in the array pass the test implemented by
> the provided function."
>
>
>
Here is the signature of the method:
```
array.every(callback[, thisObject])
```
where `callback` is a function to test for each element, and `thisObject` refers to the object that we are testing array against
|
```
var checkArray = [];
for ( var i; i<array1.length; i++ ){
if ( array2.indexOf( array1[i] ) !== -1 ) {
checkArray.push(array1[i]);
}
}
console.log("duplicate values : "+checkArray)// duplicate values : two,three,four
```
this may be not the most performant way ( i didnt test it, its pseudo-code) but at the end checkArray should contain all values of array1 that are in array2
|
20,775,504 |
If I have an array:
```
var array1=new Array();
array1[0]="two";
array1[1]="three";
array1[2]="four";
```
And another array:
```
var array2=new Array();
array2[0]="one";
array2[1]="two";
array2[2]="three";
array2[3]="four";
array2[4]="five";
```
How can I return a true value that Array1 exists in Array2?
|
2013/12/25
|
[
"https://Stackoverflow.com/questions/20775504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/632545/"
] |
Using set theory we know that A is a subset of B if and only if for every element of A there is an equivalent element in B.
I made a plnkr showing this: <http://plnkr.co/edit/9l5QplwWq1m7ZAkXV9PX>
Using a simple loop you could do it like this:
```
function isSubsetOf(arrayA, arrayB) {
for (var i = 0; i < arrayA.length;i++) {
var val = arrayA[i];
if (arrayB.indexOf(val) !== -1) {
continue;
} else {
return false;
}
}
return true;
}
```
|
If your requirement is to return true only if the sequence [two, three, four] is in array2, here is a fast but not 100% correct method:
```
var sep = 'zzz_some_highly_unlikely_occurring_string_zzz';
array2.join(sep).indexOf( array1.join(sep) );
```
|
20,775,504 |
If I have an array:
```
var array1=new Array();
array1[0]="two";
array1[1]="three";
array1[2]="four";
```
And another array:
```
var array2=new Array();
array2[0]="one";
array2[1]="two";
array2[2]="three";
array2[3]="four";
array2[4]="five";
```
How can I return a true value that Array1 exists in Array2?
|
2013/12/25
|
[
"https://Stackoverflow.com/questions/20775504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/632545/"
] |
Using set theory we know that A is a subset of B if and only if for every element of A there is an equivalent element in B.
I made a plnkr showing this: <http://plnkr.co/edit/9l5QplwWq1m7ZAkXV9PX>
Using a simple loop you could do it like this:
```
function isSubsetOf(arrayA, arrayB) {
for (var i = 0; i < arrayA.length;i++) {
var val = arrayA[i];
if (arrayB.indexOf(val) !== -1) {
continue;
} else {
return false;
}
}
return true;
}
```
|
```
var a1="";
for(var tmp:array1)
a1+=tmp;
var a2="";
for(var tmp:array2)
a2+=tmp;
```
Now check if a1 exists in a2
```
a2.indexOf(a1)>-1
```
Will return true if array1 is there in array2
|
20,775,504 |
If I have an array:
```
var array1=new Array();
array1[0]="two";
array1[1]="three";
array1[2]="four";
```
And another array:
```
var array2=new Array();
array2[0]="one";
array2[1]="two";
array2[2]="three";
array2[3]="four";
array2[4]="five";
```
How can I return a true value that Array1 exists in Array2?
|
2013/12/25
|
[
"https://Stackoverflow.com/questions/20775504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/632545/"
] |
Try like this:
```
var arr1= ["two", "three"];
var arr2= ["two", "three", "four", "five"];
var isarraySubset = arr1.every(function(val) { return arr2.indexOf(val) >= 0; }));
console.log(isarraySubset ); // true
```
**Note:-**
This solution will work if your supported browsers are of ECMA-262 standard.
**According MDN**,
>
> "Tests whether all elements in the array pass the test implemented by
> the provided function."
>
>
>
Here is the signature of the method:
```
array.every(callback[, thisObject])
```
where `callback` is a function to test for each element, and `thisObject` refers to the object that we are testing array against
|
If your requirement is to return true only if the sequence [two, three, four] is in array2, here is a fast but not 100% correct method:
```
var sep = 'zzz_some_highly_unlikely_occurring_string_zzz';
array2.join(sep).indexOf( array1.join(sep) );
```
|
20,775,504 |
If I have an array:
```
var array1=new Array();
array1[0]="two";
array1[1]="three";
array1[2]="four";
```
And another array:
```
var array2=new Array();
array2[0]="one";
array2[1]="two";
array2[2]="three";
array2[3]="four";
array2[4]="five";
```
How can I return a true value that Array1 exists in Array2?
|
2013/12/25
|
[
"https://Stackoverflow.com/questions/20775504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/632545/"
] |
Try like this:
```
var arr1= ["two", "three"];
var arr2= ["two", "three", "four", "five"];
var isarraySubset = arr1.every(function(val) { return arr2.indexOf(val) >= 0; }));
console.log(isarraySubset ); // true
```
**Note:-**
This solution will work if your supported browsers are of ECMA-262 standard.
**According MDN**,
>
> "Tests whether all elements in the array pass the test implemented by
> the provided function."
>
>
>
Here is the signature of the method:
```
array.every(callback[, thisObject])
```
where `callback` is a function to test for each element, and `thisObject` refers to the object that we are testing array against
|
```
var a1="";
for(var tmp:array1)
a1+=tmp;
var a2="";
for(var tmp:array2)
a2+=tmp;
```
Now check if a1 exists in a2
```
a2.indexOf(a1)>-1
```
Will return true if array1 is there in array2
|
420,134 |
I am building an electric go-kart. I would like to use regenerative braking. I would like to have a brake pedal that controls the amount of torque (slowing the motor and wheels down) that the back emf from the motor creates.
In a hypothetical situation, the motor (90amp 36volts permanent magnet dc motor) will be spun up when the car accelerates. It will then spin freely once up to speed. This part of the circuit I have figured out this part of the circuit already.
[](https://i.stack.imgur.com/Q33as.png)
(in this image the important switch is the pedal microswitch which closes every time the throttle is engaged Also, the Main, Foward (F) and Reverse(R) notations refer to contractors used to provide power to and switch the polarity of the motors respectively)
If we now treat the motor as a generator, from what I understand the amount of current that we draw from that generator the more torque will be applied to slowing the motor down. If we take the extreme and fully connect the motor leads together with zero resistance the motor will lock up.
Where I am confused is how to draw variable current from the motor and control it with the brake pedal. For safety purposes, I plan on installing a mechanical hand brake as well.
Any help on this would be appreciated, I am sure that I do not have a full understanding of this mechanism.
Note this diagram is from a Curtis motor controller manual. Here is a picture of the cover. [](https://i.stack.imgur.com/Uusfy.png)
|
2019/02/02
|
[
"https://electronics.stackexchange.com/questions/420134",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/179628/"
] |
I don't think you realize how much is involved in building such a powerful motor controller. I will explain some basic concepts to hopefully give you and idea of what you are trying to achieve, but I suggest you purchase a speed controller with appropriate ratings. Building a safe and reliable speed controller for 90A is a big deal.
To a first approximation, motor current = motor torque. If the current is flowing from motor into battery (regen) then the torque is acting in the "braking" direction. If the current is flowing from battery into motor, then it is acting to push the vehicle in the desired direction. To produce a regulated braking torque, you will need to produce regulated motor current flowing from motor into battery. This can be done using PWM control in conjunction with a full bridge motor drive circuit. Please note that regen must be limited to avoid charging the battery at too high of a current, and also to avoid overcharging a battery that is already fully charged. Your solution must accommodate these constraints.
In order to control the motor current, you will need some kind of control system which can sense current and adjust PWM duty cycle to produce the desired current. For example it could be a micro controller with features included to facilitate PWM control.
Here is an image of an H bridge which I found online [here](https://sourcelion.wordpress.com/2014/02/23/h-bridge-design/).
[](https://i.stack.imgur.com/R012w.jpg)
When Q4 is on, the duty cycle of Q1 can be adjusted to apply variable forward voltage to the motor. When this voltage is greater than the back EMF, there will be forward current and the motor will push the vehicle forward. When the applied voltage is less than the back EMF, this will produce regen current and braking.
By adding shunt current sense in the motor path, you can use a microprocessor to control PWM duty cycle to achieve the desired motor current.
|
V=IR + E. For a given speed, thus a given electromotive force (E) you will need to vary voltage in order to vary current. You will need to include a DC converter which is able to absorb current from the motor. Maybe a full bridge with optional filtering between it and the motor. Then, you will need to design the control and connect it somehow to the pedals. It can't be done just as it is, because you only have on-off speed control.
P.S. The full bridge is indeed implemented with mechanical switches, thus your gokart would suddenly start and suddenly brake. You need to switch faster than it can respond and thus vary the average value of V and I you apply. That is the purpose of the converter.
|
420,134 |
I am building an electric go-kart. I would like to use regenerative braking. I would like to have a brake pedal that controls the amount of torque (slowing the motor and wheels down) that the back emf from the motor creates.
In a hypothetical situation, the motor (90amp 36volts permanent magnet dc motor) will be spun up when the car accelerates. It will then spin freely once up to speed. This part of the circuit I have figured out this part of the circuit already.
[](https://i.stack.imgur.com/Q33as.png)
(in this image the important switch is the pedal microswitch which closes every time the throttle is engaged Also, the Main, Foward (F) and Reverse(R) notations refer to contractors used to provide power to and switch the polarity of the motors respectively)
If we now treat the motor as a generator, from what I understand the amount of current that we draw from that generator the more torque will be applied to slowing the motor down. If we take the extreme and fully connect the motor leads together with zero resistance the motor will lock up.
Where I am confused is how to draw variable current from the motor and control it with the brake pedal. For safety purposes, I plan on installing a mechanical hand brake as well.
Any help on this would be appreciated, I am sure that I do not have a full understanding of this mechanism.
Note this diagram is from a Curtis motor controller manual. Here is a picture of the cover. [](https://i.stack.imgur.com/Uusfy.png)
|
2019/02/02
|
[
"https://electronics.stackexchange.com/questions/420134",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/179628/"
] |
I don't think you realize how much is involved in building such a powerful motor controller. I will explain some basic concepts to hopefully give you and idea of what you are trying to achieve, but I suggest you purchase a speed controller with appropriate ratings. Building a safe and reliable speed controller for 90A is a big deal.
To a first approximation, motor current = motor torque. If the current is flowing from motor into battery (regen) then the torque is acting in the "braking" direction. If the current is flowing from battery into motor, then it is acting to push the vehicle in the desired direction. To produce a regulated braking torque, you will need to produce regulated motor current flowing from motor into battery. This can be done using PWM control in conjunction with a full bridge motor drive circuit. Please note that regen must be limited to avoid charging the battery at too high of a current, and also to avoid overcharging a battery that is already fully charged. Your solution must accommodate these constraints.
In order to control the motor current, you will need some kind of control system which can sense current and adjust PWM duty cycle to produce the desired current. For example it could be a micro controller with features included to facilitate PWM control.
Here is an image of an H bridge which I found online [here](https://sourcelion.wordpress.com/2014/02/23/h-bridge-design/).
[](https://i.stack.imgur.com/R012w.jpg)
When Q4 is on, the duty cycle of Q1 can be adjusted to apply variable forward voltage to the motor. When this voltage is greater than the back EMF, there will be forward current and the motor will push the vehicle forward. When the applied voltage is less than the back EMF, this will produce regen current and braking.
By adding shunt current sense in the motor path, you can use a microprocessor to control PWM duty cycle to achieve the desired motor current.
|
You can use field oriented control to control the torque of the motor.The field oriented control does the torque control by regulating the current .first you have to select a proper motor as per the torque requirements .You can select PMSM/Induction motor/Bldc motor for this purpose.Then you have to design the motor controller for the motor.If you are not familiar with circuit design you can buy ready made curtis/sevcon controller.
how to get regenerative breaking:
Our aim is to activate the regenerative breaking as soon as the throttle/accelerator is released.Suppose if the motor is running in clockwise direction with a positive torque to extract the energy from the motor back to battery you have to apply a negative torque to the motor from the controller.The amount of negative torque applied will decide the stopping distance of the motor,also the energy dumped back to the battery.
if you wish to design your own motor controller hardware and software you can refer to texas instrument reference design.
Here is the link :<http://www.ti.com/tool/TIDA-00364>
|
221,577 |
I see several explanations online, what was the true inspiration for the character's final production name "Michael Burnham?"
Star Trek: Discovery's lead female role was initially announced under the pseudonym "Commander Rainsford" but somehow that was changed. What’s behind the new character name Michael?
|
2019/10/14
|
[
"https://scifi.stackexchange.com/questions/221577",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/120362/"
] |
This was addressed in an interview with Discovery showrunner Aaron Harberts.
>
> **Q:** ***Why is Michael Burnham’s name… Michael?***
>
>
> All right, so here we go. **We've worked on a number of Bryan Fuller shows… Wonderfalls, Pushing Daisies. Many of his female protagonists have typically what you would call male names.** Chuck was one. Jaye was another. When we all sat down, of course, the idea was going to be that she was going to have a male name, or typically male name. We were just pitching around the writers' room. We had a couple on the board and I said, "Well, how about Michael?" Because I had remembered a gossip columnist in Chicago. I used to work in Chicago in publicity, and Michael Sneed, she wrote for the Chicago Sun Times. Then, there was the bass player for The Bangles, a musician named Michael Steele. **I'd always thought that the name Michael was just really cool and different**. We pitched that to Bryan and he was like, "Let me think about that." That's how we seized on it, but **I think it's a really cool name,** and maybe we'll see some more women Michaels. Who knows?
>
>
> [INTERVIEW: Discovery Showrunner Aaron Harberts, Part 2](https://www.startrek.com/article/interview-discovery-showrunner-aaron-harberts-part-2)
>
>
>
Obviously, in-universe her father's name is Michael Burnham, so giving her a name after her father wouldn't be an especially odd thing to do, even if it's not the most usual name for a female child. You may note that [other individuals](https://en.wikipedia.org/wiki/John_Wayne) have had traditionally female or male family names throughout history.
|
The lead character for *Star Trek: Discovery* [was originally named "LCDR Rainsford"](https://deadline.com/2016/12/star-trek-discovery-sonequa-martin-green-cast-lead-rainsford-1201871015/) and it was decided that she would only ever be called "Number One" in honor of the First Lieutenant on Captain Pike's Enterprise, who [had no name](https://scifi.stackexchange.com/questions/209351/does-christopher-pikes-first-officer-have-a-name/221574#221574) in the original series.
[In an interview with Denofgeeks.com](https://www.denofgeek.com/uk/tv/star-trek-discovery/53379/sonequa-martin-green-interview-star-trek-discovery) Sonequa Martin-Green reveals there are three reasons driving the decision to change her character's name:
* First, it is character creator Bryan Fuller's stylistic signature to give leading ladies traditionally male first names. As he came on to this project he wanted to bring that with him, and the rest of the writing staff agreed. He specifically thought Michael was a good fit as a couple famous female Michael's already exist: Columnist Michael Sneed, & Bangles' bassist Michael Steele.
* Second, co-creator [Aaron Harberts](https://en.m.wikipedia.org/wiki/Aaron_Harberts) spoke to Martin-Green about a connection with the plot to the biblical Archangel Michael, which would play an important part in the Discovery story.
>
> In the finale her character is traveling through time, saving the galaxy in a superpowered angel suit.
>
> [](https://i.stack.imgur.com/epX6O.png)
>
>
>
She states in her interview:
>
> Aaron [Harberts] also speaks about parallels with the archangel Michael, and then once it filtered down to me, I realised that I needed to incorporate it into my life.
>
>
>
* The third motivation for the name Michael was that her in-universe father's name was [Mike Burnham](https://memory-alpha.fandom.com/wiki/Mike_Burnham). Being named after her father portrayed a certain "gender fluidity" which the producers used frequently in production. Martin-Green notes:
>
> I got really incredible feedback from the producers when I decided that I was named after my biological father. What I love about that is that, in the future, there is such gender fluidity that a girl can be named after her dad and perhaps a son named after his mother. So I love how it turns into this beautiful, poignant yet very quiet political statement.
>
>
>
Out of universe the second and third motivations tie together very closely. The imagery of Michael the Archangel having a female name would be contradictory, as [angels have no gender](https://www.christianity.com/wiki/angels-and-demons/are-angels-male-or-female.html) in the Christian faiths. A female angel bearing a male name is consistent with the gender fluidity associated with angels.
Characters in Star Trek have often been inspired by a wide variety of sources; such as the super-powerful [character Q named after a devoted fan](https://scifi.stackexchange.com/questions/221372/who-inspired-the-star-trek-character-q), or being named for a simple word as was the case with [First Officer Una](https://scifi.stackexchange.com/questions/209351/does-christopher-pikes-first-officer-have-a-name/221574#221574). In this case, these are the three main reasons Discovery's female lead is called Michael.
|
17,698,053 |
I am trying to solve a problem by fetching the maximum number from each row in a triangle. So far am able to generate a triangle but how do I fetch the max number from each row?
Here is my code
---------------
`private static Integer solve(Triangle triangle)
{
//triangle is extending an ArrayList
System.out.println(triangle);
return 0;
}`
This is what am producing so far:
```
6
3 5
9 7 1
4 6 8 4
```
but now I want to get the result which says:
"In this triangle the maximum total is: 6 + 5 + 9 + 8 = 26"
Here is the complete code:
--------------------------
```
public class HellTriangle {
private static final int TRIANGLE_HEIGHT = 10;
public static void start() {
Triangle triangle = generateTriangle();
//System.out.println(triangle);
long start = System.currentTimeMillis();
Integer result = solve(triangle);
long end = System.currentTimeMillis();
System.out.println("Result:" + result);
System.out.println("Resolution time: " + (end - start) + "ms");
}
private static Triangle generateTriangle() {
Triangle triangle = new Triangle();
Random random = new Random();
for (int i = 0; i < TRIANGLE_HEIGHT; i++) {
Row row = new Row();
for (int j = 0; j <= i; j++) {
row.add(random.nextInt(100));
}
triangle.add(row);
}
return triangle;
}
private static class Row extends ArrayList<Integer> {
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size(); i++) {
sb.append(String.format("%02d", get(i)));
//rows.add(get(i));
if (i < (size() - 1)) {
sb.append(" ");
}
}
return sb.toString();
}
}
private static class Triangle extends ArrayList<Row> {
public String toString() {
// sb is used to make modification to the String
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size(); i++) {
for (int j = 0; j < (TRIANGLE_HEIGHT - 1 - i); j++) {
sb.append(" ");
}
sb.append(get(i));
if (i < (size() - 1)) {
sb.append("\n");
}
}
return sb.toString();
}
}
private static Integer solve(Triangle triangle) {
System.out.println(triangle);
return 0;
}
public static void main(String[] args) {
start();
}
}
```
Any help would be appreciated!
|
2013/07/17
|
[
"https://Stackoverflow.com/questions/17698053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1257986/"
] |
As there is no ordering in your rows and this would lead to O(n) to get the maximum value per row i would look up the maximum value during insertion. Something like that (not tested and you probably have to override the other add methods also, depending on your use case):
```
public class Row extends ArrayList<Integer> {
public String toString() {
...
}
private Integer max = null;
@Override
public boolean add(Integer elem) {
if (elem != null && (max == null || max < elem)) {
max = elem;
}
return super.add(elem);
}
public Integer getMax() {
return max;
}
}
```
|
Try
```
private static int getTriangleMax(final Triangle rows)
{
int max = 0;
for (final Row row : rows)
{
final int rowMax = getRowMax(row);
max += rowMax;
}
return max;
}
private static int getRowMax(final Row row)
{
int rowMax = Integer.MIN_VALUE;
for (final Integer integer : row)
{
if (rowMax < integer)
{
rowMax = integer;
}
}
return rowMax;
}
```
|
17,698,053 |
I am trying to solve a problem by fetching the maximum number from each row in a triangle. So far am able to generate a triangle but how do I fetch the max number from each row?
Here is my code
---------------
`private static Integer solve(Triangle triangle)
{
//triangle is extending an ArrayList
System.out.println(triangle);
return 0;
}`
This is what am producing so far:
```
6
3 5
9 7 1
4 6 8 4
```
but now I want to get the result which says:
"In this triangle the maximum total is: 6 + 5 + 9 + 8 = 26"
Here is the complete code:
--------------------------
```
public class HellTriangle {
private static final int TRIANGLE_HEIGHT = 10;
public static void start() {
Triangle triangle = generateTriangle();
//System.out.println(triangle);
long start = System.currentTimeMillis();
Integer result = solve(triangle);
long end = System.currentTimeMillis();
System.out.println("Result:" + result);
System.out.println("Resolution time: " + (end - start) + "ms");
}
private static Triangle generateTriangle() {
Triangle triangle = new Triangle();
Random random = new Random();
for (int i = 0; i < TRIANGLE_HEIGHT; i++) {
Row row = new Row();
for (int j = 0; j <= i; j++) {
row.add(random.nextInt(100));
}
triangle.add(row);
}
return triangle;
}
private static class Row extends ArrayList<Integer> {
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size(); i++) {
sb.append(String.format("%02d", get(i)));
//rows.add(get(i));
if (i < (size() - 1)) {
sb.append(" ");
}
}
return sb.toString();
}
}
private static class Triangle extends ArrayList<Row> {
public String toString() {
// sb is used to make modification to the String
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size(); i++) {
for (int j = 0; j < (TRIANGLE_HEIGHT - 1 - i); j++) {
sb.append(" ");
}
sb.append(get(i));
if (i < (size() - 1)) {
sb.append("\n");
}
}
return sb.toString();
}
}
private static Integer solve(Triangle triangle) {
System.out.println(triangle);
return 0;
}
public static void main(String[] args) {
start();
}
}
```
Any help would be appreciated!
|
2013/07/17
|
[
"https://Stackoverflow.com/questions/17698053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1257986/"
] |
Here, just change with your `solve()`
```
private static void solve(Triangle triangle) {
System.out.println(triangle);
ArrayList<Integer> result = new ArrayList<Integer>();
int total = 0;
for(Row row : triangle){
Collections.sort(row);
total += row.get(row.size()-1);
result.add(row.get(row.size()-1));
}
for(Integer intr : result)
System.out.println("Largest elements of the rows: " + intr);
System.out.println("Total: " + total);
}
```
|
Try
```
private static int getTriangleMax(final Triangle rows)
{
int max = 0;
for (final Row row : rows)
{
final int rowMax = getRowMax(row);
max += rowMax;
}
return max;
}
private static int getRowMax(final Row row)
{
int rowMax = Integer.MIN_VALUE;
for (final Integer integer : row)
{
if (rowMax < integer)
{
rowMax = integer;
}
}
return rowMax;
}
```
|
17,698,053 |
I am trying to solve a problem by fetching the maximum number from each row in a triangle. So far am able to generate a triangle but how do I fetch the max number from each row?
Here is my code
---------------
`private static Integer solve(Triangle triangle)
{
//triangle is extending an ArrayList
System.out.println(triangle);
return 0;
}`
This is what am producing so far:
```
6
3 5
9 7 1
4 6 8 4
```
but now I want to get the result which says:
"In this triangle the maximum total is: 6 + 5 + 9 + 8 = 26"
Here is the complete code:
--------------------------
```
public class HellTriangle {
private static final int TRIANGLE_HEIGHT = 10;
public static void start() {
Triangle triangle = generateTriangle();
//System.out.println(triangle);
long start = System.currentTimeMillis();
Integer result = solve(triangle);
long end = System.currentTimeMillis();
System.out.println("Result:" + result);
System.out.println("Resolution time: " + (end - start) + "ms");
}
private static Triangle generateTriangle() {
Triangle triangle = new Triangle();
Random random = new Random();
for (int i = 0; i < TRIANGLE_HEIGHT; i++) {
Row row = new Row();
for (int j = 0; j <= i; j++) {
row.add(random.nextInt(100));
}
triangle.add(row);
}
return triangle;
}
private static class Row extends ArrayList<Integer> {
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size(); i++) {
sb.append(String.format("%02d", get(i)));
//rows.add(get(i));
if (i < (size() - 1)) {
sb.append(" ");
}
}
return sb.toString();
}
}
private static class Triangle extends ArrayList<Row> {
public String toString() {
// sb is used to make modification to the String
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size(); i++) {
for (int j = 0; j < (TRIANGLE_HEIGHT - 1 - i); j++) {
sb.append(" ");
}
sb.append(get(i));
if (i < (size() - 1)) {
sb.append("\n");
}
}
return sb.toString();
}
}
private static Integer solve(Triangle triangle) {
System.out.println(triangle);
return 0;
}
public static void main(String[] args) {
start();
}
}
```
Any help would be appreciated!
|
2013/07/17
|
[
"https://Stackoverflow.com/questions/17698053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1257986/"
] |
Here, just change with your `solve()`
```
private static void solve(Triangle triangle) {
System.out.println(triangle);
ArrayList<Integer> result = new ArrayList<Integer>();
int total = 0;
for(Row row : triangle){
Collections.sort(row);
total += row.get(row.size()-1);
result.add(row.get(row.size()-1));
}
for(Integer intr : result)
System.out.println("Largest elements of the rows: " + intr);
System.out.println("Total: " + total);
}
```
|
As there is no ordering in your rows and this would lead to O(n) to get the maximum value per row i would look up the maximum value during insertion. Something like that (not tested and you probably have to override the other add methods also, depending on your use case):
```
public class Row extends ArrayList<Integer> {
public String toString() {
...
}
private Integer max = null;
@Override
public boolean add(Integer elem) {
if (elem != null && (max == null || max < elem)) {
max = elem;
}
return super.add(elem);
}
public Integer getMax() {
return max;
}
}
```
|
17,698,053 |
I am trying to solve a problem by fetching the maximum number from each row in a triangle. So far am able to generate a triangle but how do I fetch the max number from each row?
Here is my code
---------------
`private static Integer solve(Triangle triangle)
{
//triangle is extending an ArrayList
System.out.println(triangle);
return 0;
}`
This is what am producing so far:
```
6
3 5
9 7 1
4 6 8 4
```
but now I want to get the result which says:
"In this triangle the maximum total is: 6 + 5 + 9 + 8 = 26"
Here is the complete code:
--------------------------
```
public class HellTriangle {
private static final int TRIANGLE_HEIGHT = 10;
public static void start() {
Triangle triangle = generateTriangle();
//System.out.println(triangle);
long start = System.currentTimeMillis();
Integer result = solve(triangle);
long end = System.currentTimeMillis();
System.out.println("Result:" + result);
System.out.println("Resolution time: " + (end - start) + "ms");
}
private static Triangle generateTriangle() {
Triangle triangle = new Triangle();
Random random = new Random();
for (int i = 0; i < TRIANGLE_HEIGHT; i++) {
Row row = new Row();
for (int j = 0; j <= i; j++) {
row.add(random.nextInt(100));
}
triangle.add(row);
}
return triangle;
}
private static class Row extends ArrayList<Integer> {
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size(); i++) {
sb.append(String.format("%02d", get(i)));
//rows.add(get(i));
if (i < (size() - 1)) {
sb.append(" ");
}
}
return sb.toString();
}
}
private static class Triangle extends ArrayList<Row> {
public String toString() {
// sb is used to make modification to the String
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size(); i++) {
for (int j = 0; j < (TRIANGLE_HEIGHT - 1 - i); j++) {
sb.append(" ");
}
sb.append(get(i));
if (i < (size() - 1)) {
sb.append("\n");
}
}
return sb.toString();
}
}
private static Integer solve(Triangle triangle) {
System.out.println(triangle);
return 0;
}
public static void main(String[] args) {
start();
}
}
```
Any help would be appreciated!
|
2013/07/17
|
[
"https://Stackoverflow.com/questions/17698053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1257986/"
] |
As there is no ordering in your rows and this would lead to O(n) to get the maximum value per row i would look up the maximum value during insertion. Something like that (not tested and you probably have to override the other add methods also, depending on your use case):
```
public class Row extends ArrayList<Integer> {
public String toString() {
...
}
private Integer max = null;
@Override
public boolean add(Integer elem) {
if (elem != null && (max == null || max < elem)) {
max = elem;
}
return super.add(elem);
}
public Integer getMax() {
return max;
}
}
```
|
Simple-Solution:
1.Add the static list as here:
```
private static List maxRowVal=new ArrayList();
```
2.Replace your generateTriangle() function with this:
```
private static Triangle generateTriangle()
{
Triangle triangle = new Triangle();
Random random = new Random();
for (int i = 0; i < TRIANGLE_HEIGHT; i++) {
Row row = new Row();
int maxTemp=0;
for (int j = 0; j <= i; j++) {
int rand=random.nextInt(100);
row.add(rand);
if(rand>maxTemp)
maxTemp=rand; //will get max value for the row
}
maxRowVal.add(maxTemp);
triangle.add(row);
}
return triangle;
}
```
Simple indeed!!
|
17,698,053 |
I am trying to solve a problem by fetching the maximum number from each row in a triangle. So far am able to generate a triangle but how do I fetch the max number from each row?
Here is my code
---------------
`private static Integer solve(Triangle triangle)
{
//triangle is extending an ArrayList
System.out.println(triangle);
return 0;
}`
This is what am producing so far:
```
6
3 5
9 7 1
4 6 8 4
```
but now I want to get the result which says:
"In this triangle the maximum total is: 6 + 5 + 9 + 8 = 26"
Here is the complete code:
--------------------------
```
public class HellTriangle {
private static final int TRIANGLE_HEIGHT = 10;
public static void start() {
Triangle triangle = generateTriangle();
//System.out.println(triangle);
long start = System.currentTimeMillis();
Integer result = solve(triangle);
long end = System.currentTimeMillis();
System.out.println("Result:" + result);
System.out.println("Resolution time: " + (end - start) + "ms");
}
private static Triangle generateTriangle() {
Triangle triangle = new Triangle();
Random random = new Random();
for (int i = 0; i < TRIANGLE_HEIGHT; i++) {
Row row = new Row();
for (int j = 0; j <= i; j++) {
row.add(random.nextInt(100));
}
triangle.add(row);
}
return triangle;
}
private static class Row extends ArrayList<Integer> {
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size(); i++) {
sb.append(String.format("%02d", get(i)));
//rows.add(get(i));
if (i < (size() - 1)) {
sb.append(" ");
}
}
return sb.toString();
}
}
private static class Triangle extends ArrayList<Row> {
public String toString() {
// sb is used to make modification to the String
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size(); i++) {
for (int j = 0; j < (TRIANGLE_HEIGHT - 1 - i); j++) {
sb.append(" ");
}
sb.append(get(i));
if (i < (size() - 1)) {
sb.append("\n");
}
}
return sb.toString();
}
}
private static Integer solve(Triangle triangle) {
System.out.println(triangle);
return 0;
}
public static void main(String[] args) {
start();
}
}
```
Any help would be appreciated!
|
2013/07/17
|
[
"https://Stackoverflow.com/questions/17698053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1257986/"
] |
As there is no ordering in your rows and this would lead to O(n) to get the maximum value per row i would look up the maximum value during insertion. Something like that (not tested and you probably have to override the other add methods also, depending on your use case):
```
public class Row extends ArrayList<Integer> {
public String toString() {
...
}
private Integer max = null;
@Override
public boolean add(Integer elem) {
if (elem != null && (max == null || max < elem)) {
max = elem;
}
return super.add(elem);
}
public Integer getMax() {
return max;
}
}
```
|
This is not exactly what you asked for, but I would like to show you a different way to go about this problem. People have done this for me before, and I really appreciated seeing different ways to solve a problems. Good luck with your coding!
Below is the code in its entirety, so you can just copy, paste and run it.
```
public class SSCCE {
public static void main(String[] args) {
// Here you specify the size of your triangle. Change the number dim to
// whatever you want. The triangle will be represented by a 2d-array.
final int dim = 5;
int[][] triangle = new int[dim][dim];
// Walks through the triangle and fills it with random numbers from 1-9.
for (int r = 0; r < dim; r++) {
for (int c = 0; c < r + 1; c++) {
triangle[r][c] = (int) (9 * Math.random()) + 1;
}
}
// This piece just prints the triangle so you can see what's in it.
for (int r = 0; r < dim; r++) {
for (int c = 0; c < r + 1; c++) {
System.out.print(triangle[r][c] + " ");
}
System.out.println();
}
// This part finds the maximum of each row. It prints each rows maximum
// as well as the sum of all the maximums at the end.
int sum = 0;
System.out.print("\nIn this triangle the maximum total is: ");
for (int r = 0; r < dim; r++) {
int currentMax = 0;
for (int c = 0; c < r + 1; c++) {
if (triangle[r][c] > currentMax) {
currentMax = triangle[r][c];
}
}
sum += currentMax;
if (r != 0) {
System.out.print(" + ");
}
System.out.print(currentMax);
}
System.out.println(" = " + sum + ".");
}
}
```
Output:
```
9
9 2
1 7 3
1 7 3 3
5 7 5 1 9
In this triangle the maximum total is: 9 + 9 + 7 + 7 + 9 = 41.
```
|
17,698,053 |
I am trying to solve a problem by fetching the maximum number from each row in a triangle. So far am able to generate a triangle but how do I fetch the max number from each row?
Here is my code
---------------
`private static Integer solve(Triangle triangle)
{
//triangle is extending an ArrayList
System.out.println(triangle);
return 0;
}`
This is what am producing so far:
```
6
3 5
9 7 1
4 6 8 4
```
but now I want to get the result which says:
"In this triangle the maximum total is: 6 + 5 + 9 + 8 = 26"
Here is the complete code:
--------------------------
```
public class HellTriangle {
private static final int TRIANGLE_HEIGHT = 10;
public static void start() {
Triangle triangle = generateTriangle();
//System.out.println(triangle);
long start = System.currentTimeMillis();
Integer result = solve(triangle);
long end = System.currentTimeMillis();
System.out.println("Result:" + result);
System.out.println("Resolution time: " + (end - start) + "ms");
}
private static Triangle generateTriangle() {
Triangle triangle = new Triangle();
Random random = new Random();
for (int i = 0; i < TRIANGLE_HEIGHT; i++) {
Row row = new Row();
for (int j = 0; j <= i; j++) {
row.add(random.nextInt(100));
}
triangle.add(row);
}
return triangle;
}
private static class Row extends ArrayList<Integer> {
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size(); i++) {
sb.append(String.format("%02d", get(i)));
//rows.add(get(i));
if (i < (size() - 1)) {
sb.append(" ");
}
}
return sb.toString();
}
}
private static class Triangle extends ArrayList<Row> {
public String toString() {
// sb is used to make modification to the String
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size(); i++) {
for (int j = 0; j < (TRIANGLE_HEIGHT - 1 - i); j++) {
sb.append(" ");
}
sb.append(get(i));
if (i < (size() - 1)) {
sb.append("\n");
}
}
return sb.toString();
}
}
private static Integer solve(Triangle triangle) {
System.out.println(triangle);
return 0;
}
public static void main(String[] args) {
start();
}
}
```
Any help would be appreciated!
|
2013/07/17
|
[
"https://Stackoverflow.com/questions/17698053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1257986/"
] |
Here, just change with your `solve()`
```
private static void solve(Triangle triangle) {
System.out.println(triangle);
ArrayList<Integer> result = new ArrayList<Integer>();
int total = 0;
for(Row row : triangle){
Collections.sort(row);
total += row.get(row.size()-1);
result.add(row.get(row.size()-1));
}
for(Integer intr : result)
System.out.println("Largest elements of the rows: " + intr);
System.out.println("Total: " + total);
}
```
|
Simple-Solution:
1.Add the static list as here:
```
private static List maxRowVal=new ArrayList();
```
2.Replace your generateTriangle() function with this:
```
private static Triangle generateTriangle()
{
Triangle triangle = new Triangle();
Random random = new Random();
for (int i = 0; i < TRIANGLE_HEIGHT; i++) {
Row row = new Row();
int maxTemp=0;
for (int j = 0; j <= i; j++) {
int rand=random.nextInt(100);
row.add(rand);
if(rand>maxTemp)
maxTemp=rand; //will get max value for the row
}
maxRowVal.add(maxTemp);
triangle.add(row);
}
return triangle;
}
```
Simple indeed!!
|
17,698,053 |
I am trying to solve a problem by fetching the maximum number from each row in a triangle. So far am able to generate a triangle but how do I fetch the max number from each row?
Here is my code
---------------
`private static Integer solve(Triangle triangle)
{
//triangle is extending an ArrayList
System.out.println(triangle);
return 0;
}`
This is what am producing so far:
```
6
3 5
9 7 1
4 6 8 4
```
but now I want to get the result which says:
"In this triangle the maximum total is: 6 + 5 + 9 + 8 = 26"
Here is the complete code:
--------------------------
```
public class HellTriangle {
private static final int TRIANGLE_HEIGHT = 10;
public static void start() {
Triangle triangle = generateTriangle();
//System.out.println(triangle);
long start = System.currentTimeMillis();
Integer result = solve(triangle);
long end = System.currentTimeMillis();
System.out.println("Result:" + result);
System.out.println("Resolution time: " + (end - start) + "ms");
}
private static Triangle generateTriangle() {
Triangle triangle = new Triangle();
Random random = new Random();
for (int i = 0; i < TRIANGLE_HEIGHT; i++) {
Row row = new Row();
for (int j = 0; j <= i; j++) {
row.add(random.nextInt(100));
}
triangle.add(row);
}
return triangle;
}
private static class Row extends ArrayList<Integer> {
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size(); i++) {
sb.append(String.format("%02d", get(i)));
//rows.add(get(i));
if (i < (size() - 1)) {
sb.append(" ");
}
}
return sb.toString();
}
}
private static class Triangle extends ArrayList<Row> {
public String toString() {
// sb is used to make modification to the String
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size(); i++) {
for (int j = 0; j < (TRIANGLE_HEIGHT - 1 - i); j++) {
sb.append(" ");
}
sb.append(get(i));
if (i < (size() - 1)) {
sb.append("\n");
}
}
return sb.toString();
}
}
private static Integer solve(Triangle triangle) {
System.out.println(triangle);
return 0;
}
public static void main(String[] args) {
start();
}
}
```
Any help would be appreciated!
|
2013/07/17
|
[
"https://Stackoverflow.com/questions/17698053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1257986/"
] |
Here, just change with your `solve()`
```
private static void solve(Triangle triangle) {
System.out.println(triangle);
ArrayList<Integer> result = new ArrayList<Integer>();
int total = 0;
for(Row row : triangle){
Collections.sort(row);
total += row.get(row.size()-1);
result.add(row.get(row.size()-1));
}
for(Integer intr : result)
System.out.println("Largest elements of the rows: " + intr);
System.out.println("Total: " + total);
}
```
|
This is not exactly what you asked for, but I would like to show you a different way to go about this problem. People have done this for me before, and I really appreciated seeing different ways to solve a problems. Good luck with your coding!
Below is the code in its entirety, so you can just copy, paste and run it.
```
public class SSCCE {
public static void main(String[] args) {
// Here you specify the size of your triangle. Change the number dim to
// whatever you want. The triangle will be represented by a 2d-array.
final int dim = 5;
int[][] triangle = new int[dim][dim];
// Walks through the triangle and fills it with random numbers from 1-9.
for (int r = 0; r < dim; r++) {
for (int c = 0; c < r + 1; c++) {
triangle[r][c] = (int) (9 * Math.random()) + 1;
}
}
// This piece just prints the triangle so you can see what's in it.
for (int r = 0; r < dim; r++) {
for (int c = 0; c < r + 1; c++) {
System.out.print(triangle[r][c] + " ");
}
System.out.println();
}
// This part finds the maximum of each row. It prints each rows maximum
// as well as the sum of all the maximums at the end.
int sum = 0;
System.out.print("\nIn this triangle the maximum total is: ");
for (int r = 0; r < dim; r++) {
int currentMax = 0;
for (int c = 0; c < r + 1; c++) {
if (triangle[r][c] > currentMax) {
currentMax = triangle[r][c];
}
}
sum += currentMax;
if (r != 0) {
System.out.print(" + ");
}
System.out.print(currentMax);
}
System.out.println(" = " + sum + ".");
}
}
```
Output:
```
9
9 2
1 7 3
1 7 3 3
5 7 5 1 9
In this triangle the maximum total is: 9 + 9 + 7 + 7 + 9 = 41.
```
|
55,041,434 |
I got an Exception
*Got AttributeError when attempting to get a value for field `weight` on serializer `WeightHistorySerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance.
Original exception text was: 'QuerySet' object has no attribute 'weight'.*
When I tried to retrive data.
models.py
```
class WeightHistory(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
weight = models.FloatField(null=False, blank=False)
created_at = models.DateTimeField(auto_now_add=True)
```
serializers.py
```
class WeightHistorySerializer(serializers. HyperlinkedModelSerializer):
class Meta:
model = WeightHistory
fields = (
'id',
'weight',
'user_id',
'created_at'
)
read_only_fields = ('id',)
```
views.py
```
def weight_history_detail(request, user_id):
# Retrieve, update or delete a weight_history/detail.
try:
weight_history = WeightHistory.objects.filter(user_id=user_id)
except WeightHistory.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == 'GET':
serializer = WeightHistorySerializer(weight_history)
return Response(serializer.data)
```
If it change to
```
weight_history = WeightHistory.objects.get(user_id=user_id)
```
It returns only one row, But I want all the rows with given user\_id. So, What should I do to get all list with given user\_id.
|
2019/03/07
|
[
"https://Stackoverflow.com/questions/55041434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11100610/"
] |
```
'QuerySet' object has no attribute 'weight'.
```
Yes. `QuerySet` is a `Set`, a list of objects.
```
<QuerySet [<Object1>, <Object2>,..]>
```
And that list has no attribute `weight`. Instead, the objects inside the `QuerySet` has the attribute `weight`.
```
weight_history = WeightHistory.objects.filter(user_id=user_id)
```
`filter` returns a `QuerySet`, a list of `WeightHistory` objects with `user_id=user_id`.
And you are trying to serialize the list as a single object.
Instead of this:
```
serializer = WeightHistorySerializer(weight_history)
```
Do this:
```
serializer = WeightHistorySerializer(weight_history, many=True)
```
`many=True` tells the serializer that a list of objects being passed for serialization.
Moreover,
```
try:
weight_history = WeightHistory.objects.filter(user_id=user_id)
except WeightHistory.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
```
This doesn't throw an exception at all. `filter` returns an empty QuerySet if no objects exist. `<QuerySet []>`.
So the final code is:
```
def weight_history_detail(request, user_id):
# Retrieve, update or delete a weight_history/detail.
weight_history = WeightHistory.objects.filter(user_id=user_id)
if weight_history.count()<1:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == 'GET':
serializer = WeightHistorySerializer(weight_history, many=True)
return Response(serializer.data)
```
|
>
> views.py
>
>
>
```
def weight_history_detail(request, user_id):
# Retrieve, update or delete a weight_history/detail.
try:
weight_history = WeightHistory.objects.get(user_id=user_id) #get
except WeightHistory.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == 'GET':
serializer = WeightHistorySerializer(weight_history)
return Response(serializer.data)
```
use `get` instead of `filter` it will solve you error
|
56,990,015 |
Yesterday, I decided to start playing with Python for the first time, so please go easy on me, I have little to no programming experience.
As my first little project, I am trying to make a script that shuffles a deck of cards and deals 5-card hands from the shuffled deck.
I am trying to store the hands in a 2-dimensional array / matrix.
This is the code I am having trouble with:
```py
import random
sorted_deck = ["AH","KH","QH","JH","TH","9H","8H","7H","6H","5H","4H","3H","2H",
"AS","KS","QS","JS","TS","9S","8S","7S","6S","5S","4S","3S","2S",
"AD","KD","QD","JD","TD","9D","8D","7D","6D","5D","4D","3D","2D",
"AC","KC","QC","JC","TC","9C","8C","7C","6C","5C","4C","3C","2C"]
def shuffle():
sorted_deck_current = list()
sorted_deck_current.clear()
sorted_deck_current = sorted_deck.copy()
shuffled_deck = list()
shuffled_deck.clear()
for n in range(0,52):
r = random.randrange( 0, len(sorted_deck_current) )
shuffled_deck.append( sorted_deck_current[r] )
sorted_deck_current.pop( r )
return shuffled_deck
for n in range(2): # Check that the shuffle()-function works
fresh_shuffled = shuffle()
print( "Shuffled deck: " + str(fresh_shuffled) )
many_hands = list()
temp_hand = list()
temp_deck = list()
many_hands.clear()
for n in range(5): # Draw 5 hands from freshly shuffled decks
temp_hand.clear()
temp_deck.clear()
temp_deck = shuffle()
for i in range(5):
temp_hand.append( temp_deck[i] )
many_hands.append( temp_hand )
print( many_hands[n] )
for q in range(5): # Try and output the 5 different hands again
print( many_hands[q] )
exit()
```
My `for n in range(5)` loop towards the end of the code outputs 5 different hands, which is what I want.
The `for q in range(5)` loop outputs the same hand 5 times, which happens to be the last hand of the previous loop.
I can not figure out why this happens.
If anyone could explain this behaviour to me, it would be much appreciated.
|
2019/07/11
|
[
"https://Stackoverflow.com/questions/56990015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11770349/"
] |
You're creating `temp_hand` before you start the first `for` loop. Thereafter, you always end up modifying the same object, and then re-adding it to `many_hands`. In essence, you just added the same object five times. If you're familiar with C, it's like pass-by-reference: python doesn't copy the value of the list before appending it, it just appends a reference to the list.
So then later, when you try to print `many_hands`, it prints the same object 5 times.
The solution to this is to initialize `temp_hand` *inside* the `for` loop, rather than outside, so that it gets re-initialized (to a new reference) every iteration. That is, replace the line
```
temp_hand.clear()
```
which modifies the single list that you currently have, without changing its reference, with
```
temp_hand = list()
```
which creates a new empty list at a new reference and assigns it to `temp_hand`.
---
As an aside, it's usually preferred to use list literals (that is, `[]`) instead of the `list()` constructor when you're initializing an empty list. This is mostly because it stands out from code around it as being *definitely a list*, rather than a function call that happens to return one.
|
Instead of creating a new list for each hand, you empty & fill `temp_hand` for each hand, so that `many_hands` is a list of 5 references to that same list/hand.
If instead of `temp_hand.clear()` you do `temp_hand = list()` (making it a new, empty list), you should get what you expect.
|
56,990,015 |
Yesterday, I decided to start playing with Python for the first time, so please go easy on me, I have little to no programming experience.
As my first little project, I am trying to make a script that shuffles a deck of cards and deals 5-card hands from the shuffled deck.
I am trying to store the hands in a 2-dimensional array / matrix.
This is the code I am having trouble with:
```py
import random
sorted_deck = ["AH","KH","QH","JH","TH","9H","8H","7H","6H","5H","4H","3H","2H",
"AS","KS","QS","JS","TS","9S","8S","7S","6S","5S","4S","3S","2S",
"AD","KD","QD","JD","TD","9D","8D","7D","6D","5D","4D","3D","2D",
"AC","KC","QC","JC","TC","9C","8C","7C","6C","5C","4C","3C","2C"]
def shuffle():
sorted_deck_current = list()
sorted_deck_current.clear()
sorted_deck_current = sorted_deck.copy()
shuffled_deck = list()
shuffled_deck.clear()
for n in range(0,52):
r = random.randrange( 0, len(sorted_deck_current) )
shuffled_deck.append( sorted_deck_current[r] )
sorted_deck_current.pop( r )
return shuffled_deck
for n in range(2): # Check that the shuffle()-function works
fresh_shuffled = shuffle()
print( "Shuffled deck: " + str(fresh_shuffled) )
many_hands = list()
temp_hand = list()
temp_deck = list()
many_hands.clear()
for n in range(5): # Draw 5 hands from freshly shuffled decks
temp_hand.clear()
temp_deck.clear()
temp_deck = shuffle()
for i in range(5):
temp_hand.append( temp_deck[i] )
many_hands.append( temp_hand )
print( many_hands[n] )
for q in range(5): # Try and output the 5 different hands again
print( many_hands[q] )
exit()
```
My `for n in range(5)` loop towards the end of the code outputs 5 different hands, which is what I want.
The `for q in range(5)` loop outputs the same hand 5 times, which happens to be the last hand of the previous loop.
I can not figure out why this happens.
If anyone could explain this behaviour to me, it would be much appreciated.
|
2019/07/11
|
[
"https://Stackoverflow.com/questions/56990015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11770349/"
] |
First the fix, make a new list object at each iteration:
```
for draw in range(5): # try avoid single letter variables
temp_hand = [] # Make a NEW list object. BTW, [] is nicer and more common syntax than list()
temp_deck = shuffle()
temp_hand = temp_deck[:5] # Use slicing to get the first 5 elements, not a loop!
many_hands.append(temp_hand) # This will get a different list object appended each time which is what you want.
```
So what went wrong? In python, when you assign a list to a variable, you don't assign a copy of the list but rather a reference to it. Try this code:
```
list1 = [1, 2, 3] # Make a new list object
list2 = list1 # Assigns a reference to the existing list1
list1[0] = 9
print(list2)
```
you will see that `list2` has changed. This is because `list1` and `list2` point to the same object. You can check this in python using `is` or `id`:
```
print(f"list1 id: {id(list1)}")
print(f"list2 id: {id(list2)}")
```
They're the same. Also `list1 is list2` returns `True`.
But now try this:
```
list1 = [1, 2, 3]
list2 = [1, 2, 3]
```
now `list1 == list2` is `True` but `list1 is list2` is `False`. They are separate objects.
```
list1 = [1, 2, 3]
list2 = [1, 2, 3]
list1[0] = 9
print(list2)
```
This time `list2` hasn't changed.
In your original code you were keeping the reference to `temp_hand` alive by calling `.append()` instead of creating a new list object in each iteration. So in each loop you shuffle `temp_hand` and printed it and saw the new hand. But what you weren't looking at is what happened to the values already in `many_hands`. These were all point to the same object so they were *all* changing each iteration.
Here is another way to prove this:
```
list1 = []
for _ in range(5):
list1.clear()
list1.append(1) # It is really your use of append that is the culprit as this is where you EDIT an existing list instead of ASSIGNING a new one
list2 = [1]
print(f"list1 id: {id(list1)}, list2 id: {id(list2)}")
```
See how `list1` is always the same but `list2` changes each time?
---
btw my code in the beginning can be even shorter but I want to illustrate creating a list using `[]` but really `shuffle` makes a new list itself so you could have done this:
```
for draw in range(5): # try avoid single letter variables
temp_hand = shuffle()[:5]
many_hands.append(temp_hand)
```
|
Instead of creating a new list for each hand, you empty & fill `temp_hand` for each hand, so that `many_hands` is a list of 5 references to that same list/hand.
If instead of `temp_hand.clear()` you do `temp_hand = list()` (making it a new, empty list), you should get what you expect.
|
56,639,698 |
I am trying to classify some numeric data with TensorFlow. I was working on [this](https://www.tensorflow.org/tutorials/eager/custom_training_walkthrough#tensorflow_programming) tutorial, but imported some other data out of a csv instead. Running the line
```
predictions = model(features)
```
causes the error
```
InvalidArgumentError: In[0] is not a matrix [Op:MatMul]
```
when feature is defined as
```
<tf.Tensor: id=8, shape=(1000,), dtype=float32, numpy=array([-0.15328342,...)
```
and
labels as
```
<tf.Tensor: id=9, shape=(), dtype=string, numpy=b'left'>
```
My code is
```
tf.enable_eager_execution()
...
X_train, X_test, y_train, y_test =
train_test_split(df.drop(['label'], axis=1), df["label"], test_size=0.25, random_state=42)
dataset =
tf.data.Dataset.from_tensor_slices(((X_train.values,y_train.values)))
dataset.label_name=label_name
dataset.column_names=column_names
dataset.num_epochs=1
features, labels = next(iter(dataset))
model = tf.keras.Sequential([
tf.keras.layers.Dense(2000, activation=tf.nn.relu, input_shape=(1000,)),
tf.keras.layers.Dense(2000, activation=tf.nn.relu),
tf.keras.layers.Dense(1000)
])
predictions = model(features)
predictions[:1000]
```
**Changes**
```
predictions = model.predict(features)
Error when checking input: expected dense_24_input to have shape (1000,) but got array with shape (1,)
```
**It looks like there is a problem with defining my tensors.**
```
print("Features: {}".format(feature_names))
print("Label: {}".format(label_name))
```
returns
```
Features: Index(['v1', 'v2', 'v3', 'v4', 'v5', 'v6', 'v7', 'v8', 'v9', 'v10',
...
'v991', 'v992', 'v993', 'v994', 'v995', 'v996', 'v997', 'v998', 'v999',
'v1000'],
dtype='object', length=1000)
Label: label
```
but there is only a single tensor without a name (shape=(1000,))
|
2019/06/17
|
[
"https://Stackoverflow.com/questions/56639698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9236660/"
] |
Try:
```
predictions = model.predict(features)
```
|
Ok,
I faced the same type of issue, and tryed the same fix. Your neural network is also very similar to the one I've implemented. At a certaint point I got also an error like this
```
Error when checking input: expected dense_15_input to have shape (1000,) but got array with shape (1,)
```
After 1 day of mumbling I've modified my input declaration (just an example, don't focus on the numbers) from
```
x = tf.Variable(np.array([0.060, 0.060, 0.06, 0.040, 0.060]), trainable=True, dtype=tf.float64)
```
to (check square brackets!):
```
x = tf.Variable([np.array([0.060, 0.060, 0.06, 0.040, 0.060])], trainable=True, dtype=tf.float64)
```
and BAM! Using
```
prediction = model(x)
```
works great! (No idea why)
|
10,181,017 |
The main issue is that I want to audit user behavior (with triggers), but we are currently using connection pooling with our database, so don't have their username/id directly inside the db.
1. I understand that there is an EXECUTE AS LOGIN function in MSSQL Server. Is there something similar in MySQL or Postgres?
2. Do I have other options, other than auditing from the ORM and not the database?
Thanks!
|
2012/04/16
|
[
"https://Stackoverflow.com/questions/10181017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/223478/"
] |
In general, don't do that. You're breaking some of the assumptions about how UIViewControllers will be used and it is likely to cause you problems in the future. You're not going to be able to count on the subview's controller receiving all of the UIViewController lifecycle method calls you might expect.
Valid solutions are to use the iOS 5 container view controller methods to add the subview's controller as a child view controller or to have a non-UIViewController controller class responsible for managing that subview if you need to encapsulate that behavior.
|
Try this
```
- (void)viewWillAppear: (BOOL)animated {
[super viewWillAppear: animated];
[self.messageViewController viewWillAppear];
}
- (void)viewDidAppear: (BOOL)animated {
[super viewDidAppear: animated];
[self.messageViewController viewDidAppear];
}
```
|
10,181,017 |
The main issue is that I want to audit user behavior (with triggers), but we are currently using connection pooling with our database, so don't have their username/id directly inside the db.
1. I understand that there is an EXECUTE AS LOGIN function in MSSQL Server. Is there something similar in MySQL or Postgres?
2. Do I have other options, other than auditing from the ORM and not the database?
Thanks!
|
2012/04/16
|
[
"https://Stackoverflow.com/questions/10181017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/223478/"
] |
You need to create a Container View Controller. While iOS 5 explicitly supports container controllers, you can create container controllers in previous versions. All iOS 5 does is do some automatic forwarding of rotation/appearance events (optional...and personally I find them annoying, sending the events before I'm ready) and give you some extra methods to use in your implementation. The real issue in creating a Container View Controller is sending all the appropriate events to the sub-controllers and making sure you manage your controllers in a way that is consistent with Apple's implementation. Otherwise, you'll get odd behavior in your sub-controllers. You really need to make sure you fully understand how view controllers work in their entirety before you do this. I recommend reading the following:
Here's some links to info: <http://developer.apple.com/library/ios/#documentation/uikit/reference/UIViewController_Class/Reference/Reference.html> -Scroll down to: Implementing a Container View Controller
Also here for the view controller life cycle, which will help you figure out which calls need to be made in which order: <http://developer.apple.com/library/ios/#featuredarticles/ViewControllerPGforiPhoneOS/ViewLoadingandUnloading/ViewLoadingandUnloading.html#//apple_ref/doc/uid/TP40007457-CH10-SW1>
I do recommend reading the entire View Controller Programming Guide....you can gleam a lot of information from there: <http://developer.apple.com/library/ios/#featuredarticles/ViewControllerPGforiPhoneOS/Introduction/Introduction.html#//apple_ref/doc/uid/TP40007457-CH1-SW1>
|
In general, don't do that. You're breaking some of the assumptions about how UIViewControllers will be used and it is likely to cause you problems in the future. You're not going to be able to count on the subview's controller receiving all of the UIViewController lifecycle method calls you might expect.
Valid solutions are to use the iOS 5 container view controller methods to add the subview's controller as a child view controller or to have a non-UIViewController controller class responsible for managing that subview if you need to encapsulate that behavior.
|
10,181,017 |
The main issue is that I want to audit user behavior (with triggers), but we are currently using connection pooling with our database, so don't have their username/id directly inside the db.
1. I understand that there is an EXECUTE AS LOGIN function in MSSQL Server. Is there something similar in MySQL or Postgres?
2. Do I have other options, other than auditing from the ORM and not the database?
Thanks!
|
2012/04/16
|
[
"https://Stackoverflow.com/questions/10181017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/223478/"
] |
You need to create a Container View Controller. While iOS 5 explicitly supports container controllers, you can create container controllers in previous versions. All iOS 5 does is do some automatic forwarding of rotation/appearance events (optional...and personally I find them annoying, sending the events before I'm ready) and give you some extra methods to use in your implementation. The real issue in creating a Container View Controller is sending all the appropriate events to the sub-controllers and making sure you manage your controllers in a way that is consistent with Apple's implementation. Otherwise, you'll get odd behavior in your sub-controllers. You really need to make sure you fully understand how view controllers work in their entirety before you do this. I recommend reading the following:
Here's some links to info: <http://developer.apple.com/library/ios/#documentation/uikit/reference/UIViewController_Class/Reference/Reference.html> -Scroll down to: Implementing a Container View Controller
Also here for the view controller life cycle, which will help you figure out which calls need to be made in which order: <http://developer.apple.com/library/ios/#featuredarticles/ViewControllerPGforiPhoneOS/ViewLoadingandUnloading/ViewLoadingandUnloading.html#//apple_ref/doc/uid/TP40007457-CH10-SW1>
I do recommend reading the entire View Controller Programming Guide....you can gleam a lot of information from there: <http://developer.apple.com/library/ios/#featuredarticles/ViewControllerPGforiPhoneOS/Introduction/Introduction.html#//apple_ref/doc/uid/TP40007457-CH1-SW1>
|
Try this
```
- (void)viewWillAppear: (BOOL)animated {
[super viewWillAppear: animated];
[self.messageViewController viewWillAppear];
}
- (void)viewDidAppear: (BOOL)animated {
[super viewDidAppear: animated];
[self.messageViewController viewDidAppear];
}
```
|
40,681,213 |
[In dvb](http://www.interactivetvweb.org/tutorials/mhp/tuner_control):
>
> the receiver has to know which frequency the new transport stream is being broadcast on (and this alone is not trivial). Second, the receiver has to tell the tuner to change to the new frequency.
>
>
>
My question is how the receiver knows which frequency the new transport stream is being broadcast, i mean given a range of frequency (min\_freq, max\_freq),how the receiver knows the good frequency, what is the mechanism behind.
|
2016/11/18
|
[
"https://Stackoverflow.com/questions/40681213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6644375/"
] |
I suspect
```
sys.path.insert(0, '/home/username/public_html')
```
is an absolute path, but flask application is looking to a relative path respect to flask gateway, and cannot find it.
Have you tried to wrap the libraries in the app instance - move the absolute path in the app instance?
As an example, see <http://werkzeug.pocoo.org/>:
from werkzeug.wrappers import Request, Response
```
@Request.application
def application(request):
return Response('Hello World!')
if __name__ == '__main__':
from werkzeug.serving import run_simple
# move absolute path here
run_simple('localhost', 4000, application)
```
|
I suspect that `fcgi` is not supported on that host. Just because a host lets you run a Python script on the command line does not mean that they have configured mod\_fcgi in Apache.
Try this: `apachectl -t -D DUMP_MODULES | grep cgi`. You should see `fcgi_module` or `fastcgi_module`, or possibly a `cgi_module`.
If you only see a `cgi_module`, then you should be able to use `AddHandler cgi-script .py` instead of `AddHandler fcgid-script .fcgi`.
If you see none of those, then you can try `wsgi`: `apachectl -t -D DUMP_MODULES | grep wsgi`. If you see `wsgi_module`, then you know you can use `wsgi`. At that point, [you might be able to follow instructions here under `.htaccess`](https://code.google.com/archive/p/modwsgi/wikis/ConfigurationGuidelines.wiki).
|
1,822,278 |
I have been keeping the shift/reduce errors away. Now finally i think i met my match.
```
Int[] a
a[0] = 1
```
The problem is int[] is defined as
```
Type OptSquareBrackets
```
while a[0] is defined as
```
Var | Var '[' expr ']'
```
Var and Type both are defined as VAR which is any valid variable `[a-zA-Z][a-zA-Z0-9_]`. Apart from adding a dummy token (such as `**Decl** Type OptSquareBrackets` instead) is there a way to write this to not have a conflict? From this one rule i get 1 shift/reduce and 1 reduce/reduce warning.
|
2009/11/30
|
[
"https://Stackoverflow.com/questions/1822278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
something like this might be better:
```
$(function() {
$("form").each(function() {
$("#Agreement", this).click(function() {
$('input:submit', this.form).attr("disabled", this.checked ? "" : "disabled");
});
});
});
```
It looks like you're re-using `id="Agreement"` within each form - you shouldn't do that.
You could even do this if you change id to class:
```
$(function() {
$("form .Agreement").click(function() {
$('input:submit', this.form).attr("disabled", this.checked ? "" : "disabled");
});
});
```
|
I would approach it by having a function disableSubmit(objId, checkState), then actually just coding on each checkbox an attribute onclick="disableSubmite('submit1', this.checked);
```
disableSubmit(objId, checkState)
{
$(#objId).attr("disabled", checkState ? "" : "disabled");
}
```
Jquery is cool, but sometimes you just need to attach the JS directly to the object that fires it off.
|
89,532 |
It seems silly to ask about using two-factor authentication without TLS/SSL but, I have a vendor that is using public IP without TLS and asking for login creds.
Would the login be more secure if two-factor authentication was enabled without TLS?
Using something like Google Authenticator and, knowing the keys are ephemeral the window for stealing the credentials would be about <30 seconds, correct? It seems a bit more secure but not by much. What are your thoughts?
|
2015/05/18
|
[
"https://security.stackexchange.com/questions/89532",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/39849/"
] |
2FA will decrease the chance that an attacker can steal a complete set of login credentials because, as you point out, the second factor is likely limited by lifetime or a once-use policy.
But 2FA will not affect snooping or [session hijacking](https://www.owasp.org/index.php/Session_hijacking_attack). So, while an attacker may find it more difficult to login as you, they can watch your communication stream and send messages that appear to be from your session.
Besides providing confidentiality, SSL also ensures that you are actually talking to the server. Without SSL, a [MiTM attack](https://en.wikipedia.org/wiki/Man-in-the-middle_attack) can pretend to be the server. For example, you can try to logout from the server to kill your session but a MiTM can intercept the logout command and return you to a page that makes it looked like you were logged out though you really weren't.
So it may prevent future false login attempts but doesn't really make you secure at all.
|
As you have stated yourself: it is *slightly* more secure because it is limited to a < 30 seconds timeframe, but that really doesn't matter much in the grand scheme of things: it is still very insecure and it will mostly just increase the effort legitimate users will have to put in.
|
663,197 |
This is about .NET libraries (DLLs).
What are the options for measuring code that is covered by unit test cases? Is it actually worth the efforts (measuring the code coverage)? I wonder it might be too easy to cover 70% of code and almost impossible to go beyond 90%.
[EDIT]
Another interesting question (put up by "E Rolnicki") is:
What is considered a reasonable coverage %?
|
2009/03/19
|
[
"https://Stackoverflow.com/questions/663197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23671/"
] |
If you are doing Test Driven Development your code should be hitting at least 70% without trying. Some areas you just can't or is pointless to have test coverage, thats where NoCoverage attributes for NCover come in handy (you can mark classes to be excluded by code coverage).
Code coverage shouldn't be adhered to religiously, it should simply be a useful way to give you hints at areas you have missed with testing. It should be your friend, not Nazi-like!
|
Visual Studio Team System Developer Edition includes code coverage. This can be included when running unit tests.
Open up the .testrunconfig and select which assemblies you want data for.
|
663,197 |
This is about .NET libraries (DLLs).
What are the options for measuring code that is covered by unit test cases? Is it actually worth the efforts (measuring the code coverage)? I wonder it might be too easy to cover 70% of code and almost impossible to go beyond 90%.
[EDIT]
Another interesting question (put up by "E Rolnicki") is:
What is considered a reasonable coverage %?
|
2009/03/19
|
[
"https://Stackoverflow.com/questions/663197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23671/"
] |
NCover (both the commercial one and the open source one with the same name) and the code coverage tool in Visual Studio are pretty much your main tools in the MS world.
Code coverage is a reverse metric. It doesn't really show you what code is adequately tested. Like Nick mentioned, you can have test that cover but don't really test much. Code coverage instead tells you what area of your code have absolutely no tests. From there, you can decide if it makes sense to write tests for this code.
In general, I think you should do code coverage since it doesn't take much effort to set up and it at least give you more info about your code than what you had before.
I agree that getting that last fraction of code is probably the toughest and there may be a point where the ROI on it just doesn't make sense.
|
If you are doing Test Driven Development your code should be hitting at least 70% without trying. Some areas you just can't or is pointless to have test coverage, thats where NoCoverage attributes for NCover come in handy (you can mark classes to be excluded by code coverage).
Code coverage shouldn't be adhered to religiously, it should simply be a useful way to give you hints at areas you have missed with testing. It should be your friend, not Nazi-like!
|
663,197 |
This is about .NET libraries (DLLs).
What are the options for measuring code that is covered by unit test cases? Is it actually worth the efforts (measuring the code coverage)? I wonder it might be too easy to cover 70% of code and almost impossible to go beyond 90%.
[EDIT]
Another interesting question (put up by "E Rolnicki") is:
What is considered a reasonable coverage %?
|
2009/03/19
|
[
"https://Stackoverflow.com/questions/663197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23671/"
] |
There are two things to take into account when looking at Code Coverage.
1. Code coverage is a battle of diminishing returns: beyond a certain point each additional percentage yields less value. Some code (like core libraries) should be 100% covered whereas UI code/interaction can be very difficult to cover.
- Code coverage is a metric that can be deceiving: 100% code coverage does not equate to a fully tested application.
Take for example this snippet:
```
if (a == 2)
{
do_A_Stuff();
}
if (b == 3)
{
do_B_Stuff();
}
```
Run a test where a = 2 and a second test where b = 3. That's 100% code coverage. But what happens when with a test where a = 2 & b = 3? These are "Variable Relationships" and can lead to overconfidence in coverage metrics.
|
I haven't used it personally, but one of my co-workers swears by nCover (<http://www.ncover.com/>).
As far as coverage goes, in Ruby at least, 70% is easy, 90% is doable, and 100% is seldom a possibility.
|
663,197 |
This is about .NET libraries (DLLs).
What are the options for measuring code that is covered by unit test cases? Is it actually worth the efforts (measuring the code coverage)? I wonder it might be too easy to cover 70% of code and almost impossible to go beyond 90%.
[EDIT]
Another interesting question (put up by "E Rolnicki") is:
What is considered a reasonable coverage %?
|
2009/03/19
|
[
"https://Stackoverflow.com/questions/663197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23671/"
] |
If you are doing Test Driven Development your code should be hitting at least 70% without trying. Some areas you just can't or is pointless to have test coverage, thats where NoCoverage attributes for NCover come in handy (you can mark classes to be excluded by code coverage).
Code coverage shouldn't be adhered to religiously, it should simply be a useful way to give you hints at areas you have missed with testing. It should be your friend, not Nazi-like!
|
I haven't used it personally, but one of my co-workers swears by nCover (<http://www.ncover.com/>).
As far as coverage goes, in Ruby at least, 70% is easy, 90% is doable, and 100% is seldom a possibility.
|
663,197 |
This is about .NET libraries (DLLs).
What are the options for measuring code that is covered by unit test cases? Is it actually worth the efforts (measuring the code coverage)? I wonder it might be too easy to cover 70% of code and almost impossible to go beyond 90%.
[EDIT]
Another interesting question (put up by "E Rolnicki") is:
What is considered a reasonable coverage %?
|
2009/03/19
|
[
"https://Stackoverflow.com/questions/663197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23671/"
] |
There are two things to take into account when looking at Code Coverage.
1. Code coverage is a battle of diminishing returns: beyond a certain point each additional percentage yields less value. Some code (like core libraries) should be 100% covered whereas UI code/interaction can be very difficult to cover.
- Code coverage is a metric that can be deceiving: 100% code coverage does not equate to a fully tested application.
Take for example this snippet:
```
if (a == 2)
{
do_A_Stuff();
}
if (b == 3)
{
do_B_Stuff();
}
```
Run a test where a = 2 and a second test where b = 3. That's 100% code coverage. But what happens when with a test where a = 2 & b = 3? These are "Variable Relationships" and can lead to overconfidence in coverage metrics.
|
Visual Studio Team System Developer Edition includes code coverage. This can be included when running unit tests.
Open up the .testrunconfig and select which assemblies you want data for.
|
663,197 |
This is about .NET libraries (DLLs).
What are the options for measuring code that is covered by unit test cases? Is it actually worth the efforts (measuring the code coverage)? I wonder it might be too easy to cover 70% of code and almost impossible to go beyond 90%.
[EDIT]
Another interesting question (put up by "E Rolnicki") is:
What is considered a reasonable coverage %?
|
2009/03/19
|
[
"https://Stackoverflow.com/questions/663197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23671/"
] |
[NCover](http://www.ncover.com/) will help show you coverage. Coverage is incredibly useful, unfortunately it can obviously be gamed. If you have bad developers covering code just to get the %age up, yes, it will ultimately be useless and hide uncovered areas. Once you fire those people you can fix it and get back to useful information. Setting coverage goals that are unattainable is a sure-fire way to get bad coverage.
|
Visual Studio Team System Developer Edition includes code coverage. This can be included when running unit tests.
Open up the .testrunconfig and select which assemblies you want data for.
|
663,197 |
This is about .NET libraries (DLLs).
What are the options for measuring code that is covered by unit test cases? Is it actually worth the efforts (measuring the code coverage)? I wonder it might be too easy to cover 70% of code and almost impossible to go beyond 90%.
[EDIT]
Another interesting question (put up by "E Rolnicki") is:
What is considered a reasonable coverage %?
|
2009/03/19
|
[
"https://Stackoverflow.com/questions/663197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23671/"
] |
NCover (both the commercial one and the open source one with the same name) and the code coverage tool in Visual Studio are pretty much your main tools in the MS world.
Code coverage is a reverse metric. It doesn't really show you what code is adequately tested. Like Nick mentioned, you can have test that cover but don't really test much. Code coverage instead tells you what area of your code have absolutely no tests. From there, you can decide if it makes sense to write tests for this code.
In general, I think you should do code coverage since it doesn't take much effort to set up and it at least give you more info about your code than what you had before.
I agree that getting that last fraction of code is probably the toughest and there may be a point where the ROI on it just doesn't make sense.
|
I haven't used it personally, but one of my co-workers swears by nCover (<http://www.ncover.com/>).
As far as coverage goes, in Ruby at least, 70% is easy, 90% is doable, and 100% is seldom a possibility.
|
663,197 |
This is about .NET libraries (DLLs).
What are the options for measuring code that is covered by unit test cases? Is it actually worth the efforts (measuring the code coverage)? I wonder it might be too easy to cover 70% of code and almost impossible to go beyond 90%.
[EDIT]
Another interesting question (put up by "E Rolnicki") is:
What is considered a reasonable coverage %?
|
2009/03/19
|
[
"https://Stackoverflow.com/questions/663197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23671/"
] |
NCover (both the commercial one and the open source one with the same name) and the code coverage tool in Visual Studio are pretty much your main tools in the MS world.
Code coverage is a reverse metric. It doesn't really show you what code is adequately tested. Like Nick mentioned, you can have test that cover but don't really test much. Code coverage instead tells you what area of your code have absolutely no tests. From there, you can decide if it makes sense to write tests for this code.
In general, I think you should do code coverage since it doesn't take much effort to set up and it at least give you more info about your code than what you had before.
I agree that getting that last fraction of code is probably the toughest and there may be a point where the ROI on it just doesn't make sense.
|
[NCover](http://www.ncover.com/) will help show you coverage. Coverage is incredibly useful, unfortunately it can obviously be gamed. If you have bad developers covering code just to get the %age up, yes, it will ultimately be useless and hide uncovered areas. Once you fire those people you can fix it and get back to useful information. Setting coverage goals that are unattainable is a sure-fire way to get bad coverage.
|
663,197 |
This is about .NET libraries (DLLs).
What are the options for measuring code that is covered by unit test cases? Is it actually worth the efforts (measuring the code coverage)? I wonder it might be too easy to cover 70% of code and almost impossible to go beyond 90%.
[EDIT]
Another interesting question (put up by "E Rolnicki") is:
What is considered a reasonable coverage %?
|
2009/03/19
|
[
"https://Stackoverflow.com/questions/663197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23671/"
] |
[NCover](http://www.ncover.com/) will help show you coverage. Coverage is incredibly useful, unfortunately it can obviously be gamed. If you have bad developers covering code just to get the %age up, yes, it will ultimately be useless and hide uncovered areas. Once you fire those people you can fix it and get back to useful information. Setting coverage goals that are unattainable is a sure-fire way to get bad coverage.
|
I haven't used it personally, but one of my co-workers swears by nCover (<http://www.ncover.com/>).
As far as coverage goes, in Ruby at least, 70% is easy, 90% is doable, and 100% is seldom a possibility.
|
663,197 |
This is about .NET libraries (DLLs).
What are the options for measuring code that is covered by unit test cases? Is it actually worth the efforts (measuring the code coverage)? I wonder it might be too easy to cover 70% of code and almost impossible to go beyond 90%.
[EDIT]
Another interesting question (put up by "E Rolnicki") is:
What is considered a reasonable coverage %?
|
2009/03/19
|
[
"https://Stackoverflow.com/questions/663197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23671/"
] |
NCover (both the commercial one and the open source one with the same name) and the code coverage tool in Visual Studio are pretty much your main tools in the MS world.
Code coverage is a reverse metric. It doesn't really show you what code is adequately tested. Like Nick mentioned, you can have test that cover but don't really test much. Code coverage instead tells you what area of your code have absolutely no tests. From there, you can decide if it makes sense to write tests for this code.
In general, I think you should do code coverage since it doesn't take much effort to set up and it at least give you more info about your code than what you had before.
I agree that getting that last fraction of code is probably the toughest and there may be a point where the ROI on it just doesn't make sense.
|
Visual Studio Team System Developer Edition includes code coverage. This can be included when running unit tests.
Open up the .testrunconfig and select which assemblies you want data for.
|
1,660,558 |
I am a newbie to Amazon SQS and ruby on rails. And i am working on a project that some XML messages must be send to SQS. How do i do that?
Now i have this in the controller after the .save
```
def create
@thing = Thing.new(params[:thing])
respond_to do |format|
if @thing.save
message = @thing.to_xml
```
and in the model
```
inputqueue.send_message(message)
```
Is this the way i can send an XML file to SQS or??
|
2009/11/02
|
[
"https://Stackoverflow.com/questions/1660558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/167123/"
] |
I'm not sure I understand exactly, but let me try and get this straight. Every time you create a particular model, you'd like to send an XML message off to Amazon SQS? If that's the case, then...
keep your controller as so:
```
def create
@thing = Thing.new(params[:thing])
if @thing.save
#render view/partial/other
else
#display errors to user
end
```
Then, you'll use an [Observer](http://api.rubyonrails.org/classes/ActiveRecord/Observer.html) to make the call to Amazon. Put your observer right inside your models directory:
```
/app/models/Thing.rb
/app/models/ThingObserver.rb
```
Your observer might look something like:
```
class ThingObserver < ActiveRecord::Observer
def after_create(thing)
AmazonSQSPlugin.send(thing.to_xml)
end
end
```
The code in the observer will be run after every create. If the after\_create in the observer returns **false**, the entire create is rolled back, as if it never happened.
You might have to edit your environment config to get the observer to fire though, depending on how your application is currently set up.
|
RightAws::SqsGen2.queue(queue\_name, message) is the right way to go for sending the message.
|
64,124,298 |
I have a cumulative sum that I need to reverse. How do I do this in SQL Server?
Example:
```
+---+-------------------+-----+
| id| date|value|
+---+-------------------+-----+
| J1|2016-10-01 11:45:30| 100|
| J1|2016-10-02 11:30:30| 200|
| J1|2016-10-05 16:20:00| 400|
| J9|2016-10-06 08:35:00| 800|
| J9|2016-10-07 01:20:00| 900|
+---+-------------------+-----+
```
Desired DataFrame:
```
+---+-------------------+-----+---------+
| id| date|value|non_cum_value|
+---+-------------------+-----+---------+
| J1|2016-10-01 11:45:30| 100| 0|
| J1|2016-10-02 11:30:30| 200| 100|
| J1|2016-10-05 16:20:00| 400| 200|
| J9|2016-10-06 08:35:00| 800| 400|
| J9|2016-10-07 01:20:00| 900| 100|
+---+-------------------+-----+---------+
```
My code:
```
select t1.id, t1.value, DIFFERENCE(t1.value) as 'cum_sum'
from @t t1
inner join @t t2 on t1.id >= t2.id
group by t1.id, t1.value
order by t1.id
```
|
2020/09/29
|
[
"https://Stackoverflow.com/questions/64124298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4984061/"
] |
This no longer works
```
ion-label {
white-space: normal !important;
}
.alert-radio-label.sc-ion-alert-md {
white-space: pre-line !important;
}
```
The updated answer is
```
.item.sc-ion-label-md-h, .item .sc-ion-label-md-h{
white-space: normal !important;
}
.item.sc-ion-label-ios-h, .item .sc-ion-label-ios-h{
white-space: normal !important;
}
```
this turns of the white-space: nowrap which was the real culprit
|
Try adding ng-deep which will pierce the shadow DOM.
```
::ng-deep .ionic-selectable-item {
overflow-wrap: break-word!important;
min-height: 20px;
font-size: 10px;
}
```
|
64,124,298 |
I have a cumulative sum that I need to reverse. How do I do this in SQL Server?
Example:
```
+---+-------------------+-----+
| id| date|value|
+---+-------------------+-----+
| J1|2016-10-01 11:45:30| 100|
| J1|2016-10-02 11:30:30| 200|
| J1|2016-10-05 16:20:00| 400|
| J9|2016-10-06 08:35:00| 800|
| J9|2016-10-07 01:20:00| 900|
+---+-------------------+-----+
```
Desired DataFrame:
```
+---+-------------------+-----+---------+
| id| date|value|non_cum_value|
+---+-------------------+-----+---------+
| J1|2016-10-01 11:45:30| 100| 0|
| J1|2016-10-02 11:30:30| 200| 100|
| J1|2016-10-05 16:20:00| 400| 200|
| J9|2016-10-06 08:35:00| 800| 400|
| J9|2016-10-07 01:20:00| 900| 100|
+---+-------------------+-----+---------+
```
My code:
```
select t1.id, t1.value, DIFFERENCE(t1.value) as 'cum_sum'
from @t t1
inner join @t t2 on t1.id >= t2.id
group by t1.id, t1.value
order by t1.id
```
|
2020/09/29
|
[
"https://Stackoverflow.com/questions/64124298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4984061/"
] |
Try adding ng-deep which will pierce the shadow DOM.
```
::ng-deep .ionic-selectable-item {
overflow-wrap: break-word!important;
min-height: 20px;
font-size: 10px;
}
```
|
Try adding ng-template inside ionic-selectable. [Here](https://stackblitz.com/edit/ionic-selectable-item-template?file=app%2Fpages%2Fhome%2Fhome.html) is the example.
|
64,124,298 |
I have a cumulative sum that I need to reverse. How do I do this in SQL Server?
Example:
```
+---+-------------------+-----+
| id| date|value|
+---+-------------------+-----+
| J1|2016-10-01 11:45:30| 100|
| J1|2016-10-02 11:30:30| 200|
| J1|2016-10-05 16:20:00| 400|
| J9|2016-10-06 08:35:00| 800|
| J9|2016-10-07 01:20:00| 900|
+---+-------------------+-----+
```
Desired DataFrame:
```
+---+-------------------+-----+---------+
| id| date|value|non_cum_value|
+---+-------------------+-----+---------+
| J1|2016-10-01 11:45:30| 100| 0|
| J1|2016-10-02 11:30:30| 200| 100|
| J1|2016-10-05 16:20:00| 400| 200|
| J9|2016-10-06 08:35:00| 800| 400|
| J9|2016-10-07 01:20:00| 900| 100|
+---+-------------------+-----+---------+
```
My code:
```
select t1.id, t1.value, DIFFERENCE(t1.value) as 'cum_sum'
from @t t1
inner join @t t2 on t1.id >= t2.id
group by t1.id, t1.value
order by t1.id
```
|
2020/09/29
|
[
"https://Stackoverflow.com/questions/64124298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4984061/"
] |
This no longer works
```
ion-label {
white-space: normal !important;
}
.alert-radio-label.sc-ion-alert-md {
white-space: pre-line !important;
}
```
The updated answer is
```
.item.sc-ion-label-md-h, .item .sc-ion-label-md-h{
white-space: normal !important;
}
.item.sc-ion-label-ios-h, .item .sc-ion-label-ios-h{
white-space: normal !important;
}
```
this turns of the white-space: nowrap which was the real culprit
|
Try adding ng-template inside ionic-selectable. [Here](https://stackblitz.com/edit/ionic-selectable-item-template?file=app%2Fpages%2Fhome%2Fhome.html) is the example.
|
8,952,353 |
I am using an XML (HttpPost) on ListView to display a list of items in my application.
XML File passes the following sample data:
```
id=5
name=Name2
score=20
```
The problem I am facing is with the OnItemClick:
**public void** onItemClick(AdapterView parent, View view, int position, long id)
{
lv.getItemAtPosition(position);
```
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle("Selected Name: " + lv.getItemAtPosition(position));
```
Here lv is the listview.
The out put shows:
**Selected Name: {id=5, name=Name2, score=20}**
What should I be doing if I need an output like:
**Selected Name: Name2**
Thanks
Ram
|
2012/01/21
|
[
"https://Stackoverflow.com/questions/8952353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1057263/"
] |
I have a feeling that you're using pre C++11.
Change this:
```
vector<bitset<8>> bvc;
```
to this:
```
vector<bitset<8> > bvc;
```
Otherwise, the `>>` is parsed as the right-shift operator. This was "fixed" in C++11.
|
Change `vector<bitset<8>> bvc` to `vector<bitset<8> > bvc`. Note the space. `>>` is an operator.
Yes, pretty nasty syntax issue.
|
5,462,852 |
I am trying to build CppUnit (first line in ReadMe says version 1.13) with Visual Studio 2010. Following the instructions (found on web forums, couldn't find much in CppUnit documentation); I cannot find a valid file extension. All file extensions end with ",v" what is this weird ",v" extension and what is the purpose of it?
I am frustrated at this point, if someone can help with how to load CppUnit in VS2010 project and build it....that would be a great help !
|
2011/03/28
|
[
"https://Stackoverflow.com/questions/5462852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/677036/"
] |
Are you referring to this project?
<http://sourceforge.net/projects/cppunit>
If so, use TortoiseSVN for example to get the latest code from svn:
<https://cppunit.svn.sourceforge.net/svnroot/cppunit>
It contains "INSTALL-VS.Net2008.txt" with instructions for Visual Studio 2008 but it can also be applied to Visual Studio 2010.
You may have to edit src\msvc6\testrunner\MsDevCallerListCtrl.cpp and replace
`version("9.0")`
with
`version("10.0")`
You can safely ignore any build errors as long as the sln outputs cppunit(d).lib or whichever dependencies you need.
Have fun! :)
|
I've successfully converted CPPUNIT 1.12.1 to be a VS2010 solution. It's described here: <http://blogs.powersoft.ca/erict/archive/2012/02/21/cppunit-in-vs2010ndashwith-a-sample.aspx> and the solution can be downloaded from there.
|
5,462,852 |
I am trying to build CppUnit (first line in ReadMe says version 1.13) with Visual Studio 2010. Following the instructions (found on web forums, couldn't find much in CppUnit documentation); I cannot find a valid file extension. All file extensions end with ",v" what is this weird ",v" extension and what is the purpose of it?
I am frustrated at this point, if someone can help with how to load CppUnit in VS2010 project and build it....that would be a great help !
|
2011/03/28
|
[
"https://Stackoverflow.com/questions/5462852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/677036/"
] |
Are you referring to this project?
<http://sourceforge.net/projects/cppunit>
If so, use TortoiseSVN for example to get the latest code from svn:
<https://cppunit.svn.sourceforge.net/svnroot/cppunit>
It contains "INSTALL-VS.Net2008.txt" with instructions for Visual Studio 2008 but it can also be applied to Visual Studio 2010.
You may have to edit src\msvc6\testrunner\MsDevCallerListCtrl.cpp and replace
`version("9.0")`
with
`version("10.0")`
You can safely ignore any build errors as long as the sln outputs cppunit(d).lib or whichever dependencies you need.
Have fun! :)
|
I just found a version which is really easy to build in VS2010(aka push 1 button):
<http://www.comp.nus.edu.sg/~cs3215/tools/cppunitAll.html>
It's really nice because it has a .sln file which you can open directly. Also it includes a tutorial ;)
Found it with google.de
It's version 1.12.1
Have fun!
|
5,462,852 |
I am trying to build CppUnit (first line in ReadMe says version 1.13) with Visual Studio 2010. Following the instructions (found on web forums, couldn't find much in CppUnit documentation); I cannot find a valid file extension. All file extensions end with ",v" what is this weird ",v" extension and what is the purpose of it?
I am frustrated at this point, if someone can help with how to load CppUnit in VS2010 project and build it....that would be a great help !
|
2011/03/28
|
[
"https://Stackoverflow.com/questions/5462852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/677036/"
] |
I've successfully converted CPPUNIT 1.12.1 to be a VS2010 solution. It's described here: <http://blogs.powersoft.ca/erict/archive/2012/02/21/cppunit-in-vs2010ndashwith-a-sample.aspx> and the solution can be downloaded from there.
|
I just found a version which is really easy to build in VS2010(aka push 1 button):
<http://www.comp.nus.edu.sg/~cs3215/tools/cppunitAll.html>
It's really nice because it has a .sln file which you can open directly. Also it includes a tutorial ;)
Found it with google.de
It's version 1.12.1
Have fun!
|
4,474,041 |
I'd like to edit the syntax highlighting for PHP in Notepad++:
1. To have variables starting with `$_` in a different color than variables starting with only `$`
2. To have operators like `{} () []` in different colors than operators like `& =`
Is it possible to change the highlighting to be this in-depth? How?
|
2010/12/17
|
[
"https://Stackoverflow.com/questions/4474041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/422039/"
] |
This is Possible
----------------
In Notepad++, define a new language by clicking *View* **>** *User-Defined Dialogue...*
Give the language a name (e.g. myPHP). Set the ext (file extension abbreviation) to **php**. Define the color coding for the global variables and for the brackets, braces and parentheses, etc. Close the Dialoague.
That is all. The formatting for myPHP which conflicts with the formatting for PHP will override the formatting for PHP, i.e. if the file has a .php extension.
More information: [Notepad++ Wiki](http://docs.notepad-plus-plus.org/index.php?title=User_Defined_Languages#Built-in_versus_User_Defined_Languages)
|
To edit the syntax highlighting in `Notepad++`, follow these steps:
* Go to `Settings`, then `Style`. The configurator dialog opens.
* Select language `php`
* Select the style based on your criteria
* Save
|
13,374,336 |
I have created an android project using eclipse.the default system generated code looked as below
```
package com.rmycustomclass.bengler;
import android.app.Activity;
import android.os.Bundle;
public class RMyCustomClassActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
```
I wanted to try a simple custom control , so i changed the code as below. when i searched the web to create a simple custom control there are mentioned like "create class by subclassing a View". so tried as below by modifying the code.but it was not running and always force closed.
```
package com.rmycustomclass.bengler;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
public class RMyCustomClassActivity extends View {
private Paint myPaint;
public RMyCustomClassActivity(Context cxt, AttributeSet attribute){
super(cxt,attribute);
init();
}
public RMyCustomClassActivity(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
init();
}
public void init(){
myPaint = new Paint();
myPaint.setTextSize(12);
myPaint.setColor(0xFF668800);
myPaint.setStyle(Paint.Style.FILL);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawText("TEEEST", 100, 100, myPaint);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
this.setMeasuredDimension(150,200);
}
}
```
Below is my xml file
```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="fill_parent" android:orientation="vertical">
<TextView
android:id="@+id/textView1"
android:text="Enter text"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/tableLayout1">
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:layout_weight="1">
</Button>
<Button android:layout_width="wrap_content" android:id="@+id/button1" android:layout_height="40dip" android:text="My button" android:layout_weight="1"></Button>
<test.control
android:id="@+id/control"
android:layout_height="match_parent"> </test.control>
</TableLayout>
</LinearLayout>
```
|
2012/11/14
|
[
"https://Stackoverflow.com/questions/13374336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/352627/"
] |
When you create a project in eclipse it links your activity (RMyCustomClassActivity in your case) as the launcher in Android manifest...But since you have changed the activity to a View
android runtime cannot find the activity to launch...See your manifest file and you will find your class as the launcher activity
|
add android:layout\_width="match\_parent"
```
<test.control
android:id="@+id/control"
android:layout_height="match_parent"
android:layout_width="match_parent"
>
```
|
16,238,693 |
my script creates an empty array and then fill it. But if new arguments come then script is expected to destroy old one and create new one.
```
var Passengers = new Array();
function FillPassengers(count){
for(var i=0;i<count;i++)
Passengers[i] = i;
}
```
I wanna destroy the old one because new count may be less than old one and last elements of array still will store old array? is that right and if it is how can I destroy it?
|
2013/04/26
|
[
"https://Stackoverflow.com/questions/16238693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1706861/"
] |
This will create a new empty array `Passengers = []`.
Not sure about what you should do.
Or just `Passengers.length = 0;`
|
You can simply do this to empty an array (without changing the array object itself):
```
Passengers.length = 0;
```
Or, with your code:
```
function FillPassengers(count){
for(var i=0;i<count;i++)
Passengers[i] = i;
Passengers.length = count;
}
```
|
16,238,693 |
my script creates an empty array and then fill it. But if new arguments come then script is expected to destroy old one and create new one.
```
var Passengers = new Array();
function FillPassengers(count){
for(var i=0;i<count;i++)
Passengers[i] = i;
}
```
I wanna destroy the old one because new count may be less than old one and last elements of array still will store old array? is that right and if it is how can I destroy it?
|
2013/04/26
|
[
"https://Stackoverflow.com/questions/16238693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1706861/"
] |
You can simply do this to empty an array (without changing the array object itself):
```
Passengers.length = 0;
```
Or, with your code:
```
function FillPassengers(count){
for(var i=0;i<count;i++)
Passengers[i] = i;
Passengers.length = count;
}
```
|
You can just re-assign a new *Array* instance
```
Passengers = [ ];
```
respectively
```
Passengers = new Array();
```
The garbage collector till take care of the rest.
|
16,238,693 |
my script creates an empty array and then fill it. But if new arguments come then script is expected to destroy old one and create new one.
```
var Passengers = new Array();
function FillPassengers(count){
for(var i=0;i<count;i++)
Passengers[i] = i;
}
```
I wanna destroy the old one because new count may be less than old one and last elements of array still will store old array? is that right and if it is how can I destroy it?
|
2013/04/26
|
[
"https://Stackoverflow.com/questions/16238693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1706861/"
] |
You can simply do this to empty an array (without changing the array object itself):
```
Passengers.length = 0;
```
Or, with your code:
```
function FillPassengers(count){
for(var i=0;i<count;i++)
Passengers[i] = i;
Passengers.length = count;
}
```
|
Very Simple
```
riz = [];
```
or
```
riz.length = 0;
```
|
16,238,693 |
my script creates an empty array and then fill it. But if new arguments come then script is expected to destroy old one and create new one.
```
var Passengers = new Array();
function FillPassengers(count){
for(var i=0;i<count;i++)
Passengers[i] = i;
}
```
I wanna destroy the old one because new count may be less than old one and last elements of array still will store old array? is that right and if it is how can I destroy it?
|
2013/04/26
|
[
"https://Stackoverflow.com/questions/16238693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1706861/"
] |
This will create a new empty array `Passengers = []`.
Not sure about what you should do.
Or just `Passengers.length = 0;`
|
You can just re-assign a new *Array* instance
```
Passengers = [ ];
```
respectively
```
Passengers = new Array();
```
The garbage collector till take care of the rest.
|
16,238,693 |
my script creates an empty array and then fill it. But if new arguments come then script is expected to destroy old one and create new one.
```
var Passengers = new Array();
function FillPassengers(count){
for(var i=0;i<count;i++)
Passengers[i] = i;
}
```
I wanna destroy the old one because new count may be less than old one and last elements of array still will store old array? is that right and if it is how can I destroy it?
|
2013/04/26
|
[
"https://Stackoverflow.com/questions/16238693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1706861/"
] |
This will create a new empty array `Passengers = []`.
Not sure about what you should do.
Or just `Passengers.length = 0;`
|
Very Simple
```
riz = [];
```
or
```
riz.length = 0;
```
|
50,969,311 |
I'm trying to execute a step function that has a task that uses an activity resource.
and after running my code i would like to return a `SendTaskSuccess` or `SendTaskFailure`
back to the step function.
I'm getting the following error sporadically (after less then 10 seconds):
```
An error occurred (TaskTimedOut) when calling the SendTaskFailure operation: Task Timed Out: 'arn:aws:states:us-east-1:<....>'
```
where do i disable the TaskTimeOut? or how do i increase it?
**more info**
This is the step function code
```
{
"Comment": "orchestrator-state-machine",
"StartAt": "get_data_from_lambda",
"States": {
"get_data_from_lambda": {
"Type": "Pass",
"Next": "start_task"
},
"start_task": {
"Type": "Task",
"Resource": "arn:aws:states:us-east-1:<...>",
"End": true
}
}
}
```
Code for sending success
```
self._client = boto3.client('stepfunctions', self._region, config=Config(connect_timeout=65,read_timeout=70,region_name=self._region))
...
def task_success(self, token, result):
self.logger.info(str(token))
try:
self._client.send_task_success(taskToken=token, output=result)
self.logger.info("sending success back to step function")
except Exception as e:
self.logger.error("did not send success to step function: {0}".format(str(e)))
return True
```
request details
```
{
'Error': {
'Message': "Task Timed Out: 'arn:aws:states:us-east-1:<....>t'",
'Code': 'TaskTimedOut'
},
'ResponseMetadata': {
'RequestId': 'b******d-755a-****-9cef-ad*******a4c',
'HTTPStatusCode': 400,
'HTTPHeaders': {
'x-amzn-requestid': 'b******d-755a-****-9cef-ad*******a4c',
'content-type': 'application/x-amz-json-1.0',
'content-length': '154'
},
'RetryAttempts': 0
}
}
```
|
2018/06/21
|
[
"https://Stackoverflow.com/questions/50969311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4412317/"
] |
You need to first join the tuples in your list
```
>>> boundarylist = [('eː', 'n'), ('a', 'k'), ('a', 's')]
>>> ' '.join([''.join(w) for w in boundarylist])
'eːn ak as'
>>>
```
|
One way:
```
boundarylist = [('eː', 'n'), ('a', 'k'), ('a', 's')]
print(' '.join([x+y for x, y in boundarylist]))
# eːn ak as
```
|
50,969,311 |
I'm trying to execute a step function that has a task that uses an activity resource.
and after running my code i would like to return a `SendTaskSuccess` or `SendTaskFailure`
back to the step function.
I'm getting the following error sporadically (after less then 10 seconds):
```
An error occurred (TaskTimedOut) when calling the SendTaskFailure operation: Task Timed Out: 'arn:aws:states:us-east-1:<....>'
```
where do i disable the TaskTimeOut? or how do i increase it?
**more info**
This is the step function code
```
{
"Comment": "orchestrator-state-machine",
"StartAt": "get_data_from_lambda",
"States": {
"get_data_from_lambda": {
"Type": "Pass",
"Next": "start_task"
},
"start_task": {
"Type": "Task",
"Resource": "arn:aws:states:us-east-1:<...>",
"End": true
}
}
}
```
Code for sending success
```
self._client = boto3.client('stepfunctions', self._region, config=Config(connect_timeout=65,read_timeout=70,region_name=self._region))
...
def task_success(self, token, result):
self.logger.info(str(token))
try:
self._client.send_task_success(taskToken=token, output=result)
self.logger.info("sending success back to step function")
except Exception as e:
self.logger.error("did not send success to step function: {0}".format(str(e)))
return True
```
request details
```
{
'Error': {
'Message': "Task Timed Out: 'arn:aws:states:us-east-1:<....>t'",
'Code': 'TaskTimedOut'
},
'ResponseMetadata': {
'RequestId': 'b******d-755a-****-9cef-ad*******a4c',
'HTTPStatusCode': 400,
'HTTPHeaders': {
'x-amzn-requestid': 'b******d-755a-****-9cef-ad*******a4c',
'content-type': 'application/x-amz-json-1.0',
'content-length': '154'
},
'RetryAttempts': 0
}
}
```
|
2018/06/21
|
[
"https://Stackoverflow.com/questions/50969311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4412317/"
] |
You need to first join the tuples in your list
```
>>> boundarylist = [('eː', 'n'), ('a', 'k'), ('a', 's')]
>>> ' '.join([''.join(w) for w in boundarylist])
'eːn ak as'
>>>
```
|
here's what I tried, iterated through the list then through the tuple;
```
boundarylist = [('eː', 'n'), ('a', 'k'), ('a', 's')]
new_list = []
for tuple_ in boundarylist:
for i in tuple_:
new_list.append(i)
boundarylist = ' '.join(new_list)
print(boundarylist)
```
|
50,969,311 |
I'm trying to execute a step function that has a task that uses an activity resource.
and after running my code i would like to return a `SendTaskSuccess` or `SendTaskFailure`
back to the step function.
I'm getting the following error sporadically (after less then 10 seconds):
```
An error occurred (TaskTimedOut) when calling the SendTaskFailure operation: Task Timed Out: 'arn:aws:states:us-east-1:<....>'
```
where do i disable the TaskTimeOut? or how do i increase it?
**more info**
This is the step function code
```
{
"Comment": "orchestrator-state-machine",
"StartAt": "get_data_from_lambda",
"States": {
"get_data_from_lambda": {
"Type": "Pass",
"Next": "start_task"
},
"start_task": {
"Type": "Task",
"Resource": "arn:aws:states:us-east-1:<...>",
"End": true
}
}
}
```
Code for sending success
```
self._client = boto3.client('stepfunctions', self._region, config=Config(connect_timeout=65,read_timeout=70,region_name=self._region))
...
def task_success(self, token, result):
self.logger.info(str(token))
try:
self._client.send_task_success(taskToken=token, output=result)
self.logger.info("sending success back to step function")
except Exception as e:
self.logger.error("did not send success to step function: {0}".format(str(e)))
return True
```
request details
```
{
'Error': {
'Message': "Task Timed Out: 'arn:aws:states:us-east-1:<....>t'",
'Code': 'TaskTimedOut'
},
'ResponseMetadata': {
'RequestId': 'b******d-755a-****-9cef-ad*******a4c',
'HTTPStatusCode': 400,
'HTTPHeaders': {
'x-amzn-requestid': 'b******d-755a-****-9cef-ad*******a4c',
'content-type': 'application/x-amz-json-1.0',
'content-length': '154'
},
'RetryAttempts': 0
}
}
```
|
2018/06/21
|
[
"https://Stackoverflow.com/questions/50969311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4412317/"
] |
You need to first join the tuples in your list
```
>>> boundarylist = [('eː', 'n'), ('a', 'k'), ('a', 's')]
>>> ' '.join([''.join(w) for w in boundarylist])
'eːn ak as'
>>>
```
|
We can use reduce method for it.
```
boundarylist = [('eː', 'n'), ('a', 'k'), ('a', 's')]
print reduce(lambda x,y:"".join(x) + " " + "".join(y) , boundarylist)
```
Output
```
'eːn ak as'
```
How this works
--------------
Here we are actually joining the tuple that is inside the list using `.join()` method and then using `reduce()` function we are taking two arguments and concatenating them with " " space character that will satisfy your use case.
|
50,969,311 |
I'm trying to execute a step function that has a task that uses an activity resource.
and after running my code i would like to return a `SendTaskSuccess` or `SendTaskFailure`
back to the step function.
I'm getting the following error sporadically (after less then 10 seconds):
```
An error occurred (TaskTimedOut) when calling the SendTaskFailure operation: Task Timed Out: 'arn:aws:states:us-east-1:<....>'
```
where do i disable the TaskTimeOut? or how do i increase it?
**more info**
This is the step function code
```
{
"Comment": "orchestrator-state-machine",
"StartAt": "get_data_from_lambda",
"States": {
"get_data_from_lambda": {
"Type": "Pass",
"Next": "start_task"
},
"start_task": {
"Type": "Task",
"Resource": "arn:aws:states:us-east-1:<...>",
"End": true
}
}
}
```
Code for sending success
```
self._client = boto3.client('stepfunctions', self._region, config=Config(connect_timeout=65,read_timeout=70,region_name=self._region))
...
def task_success(self, token, result):
self.logger.info(str(token))
try:
self._client.send_task_success(taskToken=token, output=result)
self.logger.info("sending success back to step function")
except Exception as e:
self.logger.error("did not send success to step function: {0}".format(str(e)))
return True
```
request details
```
{
'Error': {
'Message': "Task Timed Out: 'arn:aws:states:us-east-1:<....>t'",
'Code': 'TaskTimedOut'
},
'ResponseMetadata': {
'RequestId': 'b******d-755a-****-9cef-ad*******a4c',
'HTTPStatusCode': 400,
'HTTPHeaders': {
'x-amzn-requestid': 'b******d-755a-****-9cef-ad*******a4c',
'content-type': 'application/x-amz-json-1.0',
'content-length': '154'
},
'RetryAttempts': 0
}
}
```
|
2018/06/21
|
[
"https://Stackoverflow.com/questions/50969311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4412317/"
] |
One way:
```
boundarylist = [('eː', 'n'), ('a', 'k'), ('a', 's')]
print(' '.join([x+y for x, y in boundarylist]))
# eːn ak as
```
|
here's what I tried, iterated through the list then through the tuple;
```
boundarylist = [('eː', 'n'), ('a', 'k'), ('a', 's')]
new_list = []
for tuple_ in boundarylist:
for i in tuple_:
new_list.append(i)
boundarylist = ' '.join(new_list)
print(boundarylist)
```
|
50,969,311 |
I'm trying to execute a step function that has a task that uses an activity resource.
and after running my code i would like to return a `SendTaskSuccess` or `SendTaskFailure`
back to the step function.
I'm getting the following error sporadically (after less then 10 seconds):
```
An error occurred (TaskTimedOut) when calling the SendTaskFailure operation: Task Timed Out: 'arn:aws:states:us-east-1:<....>'
```
where do i disable the TaskTimeOut? or how do i increase it?
**more info**
This is the step function code
```
{
"Comment": "orchestrator-state-machine",
"StartAt": "get_data_from_lambda",
"States": {
"get_data_from_lambda": {
"Type": "Pass",
"Next": "start_task"
},
"start_task": {
"Type": "Task",
"Resource": "arn:aws:states:us-east-1:<...>",
"End": true
}
}
}
```
Code for sending success
```
self._client = boto3.client('stepfunctions', self._region, config=Config(connect_timeout=65,read_timeout=70,region_name=self._region))
...
def task_success(self, token, result):
self.logger.info(str(token))
try:
self._client.send_task_success(taskToken=token, output=result)
self.logger.info("sending success back to step function")
except Exception as e:
self.logger.error("did not send success to step function: {0}".format(str(e)))
return True
```
request details
```
{
'Error': {
'Message': "Task Timed Out: 'arn:aws:states:us-east-1:<....>t'",
'Code': 'TaskTimedOut'
},
'ResponseMetadata': {
'RequestId': 'b******d-755a-****-9cef-ad*******a4c',
'HTTPStatusCode': 400,
'HTTPHeaders': {
'x-amzn-requestid': 'b******d-755a-****-9cef-ad*******a4c',
'content-type': 'application/x-amz-json-1.0',
'content-length': '154'
},
'RetryAttempts': 0
}
}
```
|
2018/06/21
|
[
"https://Stackoverflow.com/questions/50969311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4412317/"
] |
One way:
```
boundarylist = [('eː', 'n'), ('a', 'k'), ('a', 's')]
print(' '.join([x+y for x, y in boundarylist]))
# eːn ak as
```
|
We can use reduce method for it.
```
boundarylist = [('eː', 'n'), ('a', 'k'), ('a', 's')]
print reduce(lambda x,y:"".join(x) + " " + "".join(y) , boundarylist)
```
Output
```
'eːn ak as'
```
How this works
--------------
Here we are actually joining the tuple that is inside the list using `.join()` method and then using `reduce()` function we are taking two arguments and concatenating them with " " space character that will satisfy your use case.
|
49,505,446 |
I tried to archive my react native project using **Product** > **Archive** on XCode9.2. But Xcode produce this error:
```
File /Users/louis/Library/Developer/Xcode/DerivedData/Scavenger-evyvzocndqoghkclcbwewolywniz/Build/Products/Release-iphoneos/Scavenger.app/main.jsbundle does not exist. This must be a bug with
My Environment:
OS: macOS Sierra 10.12.6
Node: 9.3.0
npm: 5.5.1
Watchman: 4.7.0
Xcode: Xcode 9.2 Build version 9C40b
Android Studio: 3.0 AI-171.4443003
Packages: (wanted => installed)
react: ^16.0.0 => 16.2.0
react-native: ^0.50.3 => 0.50.4
```
I also tried to run on terminal
`react-native bundle --entry-file='index.ios.js' --bundle-output='./ios/Scavenger/main.jsbundle' --dev=false --platform='ios' --assets-dest='./ios'`but ended up with error Loading dependency graph...
Unexpected end of JSON input
XCode error.

|
2018/03/27
|
[
"https://Stackoverflow.com/questions/49505446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7252084/"
] |
For some people like me this is simply an indication of an error in the JavaScript code. I discovered this to be the case after entering the following command: `npx react-native bundle --entry-file index.js --bundle-output "bundle.bundle"`. Android users would need to specify the platform like so: `npx react-native bundle --entry-file --platform "ios" index.js --bundle-output "bundle.bundle"`.
The bundle failed and the syntax error was shown. Any attempt to open the offending code in a simulator would show the error too.
|
Simply cleaning the project in Xcode helped me
|
49,505,446 |
I tried to archive my react native project using **Product** > **Archive** on XCode9.2. But Xcode produce this error:
```
File /Users/louis/Library/Developer/Xcode/DerivedData/Scavenger-evyvzocndqoghkclcbwewolywniz/Build/Products/Release-iphoneos/Scavenger.app/main.jsbundle does not exist. This must be a bug with
My Environment:
OS: macOS Sierra 10.12.6
Node: 9.3.0
npm: 5.5.1
Watchman: 4.7.0
Xcode: Xcode 9.2 Build version 9C40b
Android Studio: 3.0 AI-171.4443003
Packages: (wanted => installed)
react: ^16.0.0 => 16.2.0
react-native: ^0.50.3 => 0.50.4
```
I also tried to run on terminal
`react-native bundle --entry-file='index.ios.js' --bundle-output='./ios/Scavenger/main.jsbundle' --dev=false --platform='ios' --assets-dest='./ios'`but ended up with error Loading dependency graph...
Unexpected end of JSON input
XCode error.

|
2018/03/27
|
[
"https://Stackoverflow.com/questions/49505446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7252084/"
] |
Comment this line in AppDelegate.m
```
jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
```
Use this line:-
```
jsCodeLocation = [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
```
After that run this to make jsbundle:-
```
react-native bundle --entry-file index.js --platform ios --dev false --bundle-output ios/main.jsbundle --assets-dest ios
```
Run after this command in xcode .
Hope it will make bundle and there is no such error after that ...
Thanx
|
For some people like me this is simply an indication of an error in the JavaScript code. I discovered this to be the case after entering the following command: `npx react-native bundle --entry-file index.js --bundle-output "bundle.bundle"`. Android users would need to specify the platform like so: `npx react-native bundle --entry-file --platform "ios" index.js --bundle-output "bundle.bundle"`.
The bundle failed and the syntax error was shown. Any attempt to open the offending code in a simulator would show the error too.
|
49,505,446 |
I tried to archive my react native project using **Product** > **Archive** on XCode9.2. But Xcode produce this error:
```
File /Users/louis/Library/Developer/Xcode/DerivedData/Scavenger-evyvzocndqoghkclcbwewolywniz/Build/Products/Release-iphoneos/Scavenger.app/main.jsbundle does not exist. This must be a bug with
My Environment:
OS: macOS Sierra 10.12.6
Node: 9.3.0
npm: 5.5.1
Watchman: 4.7.0
Xcode: Xcode 9.2 Build version 9C40b
Android Studio: 3.0 AI-171.4443003
Packages: (wanted => installed)
react: ^16.0.0 => 16.2.0
react-native: ^0.50.3 => 0.50.4
```
I also tried to run on terminal
`react-native bundle --entry-file='index.ios.js' --bundle-output='./ios/Scavenger/main.jsbundle' --dev=false --platform='ios' --assets-dest='./ios'`but ended up with error Loading dependency graph...
Unexpected end of JSON input
XCode error.

|
2018/03/27
|
[
"https://Stackoverflow.com/questions/49505446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7252084/"
] |
This happens when there is no offline bundle file in your project, I had the same problem and this worked for me.
I have added the below line to my package.json file, under `scripts` section, so I don't have to type it every time I want to generate an offline bundle.
```
"build:ios": "react-native bundle --entry-file='index.ios.js' --bundle-output='./ios/YourAppName/main.jsbundle' --dev=false --platform='ios' --assets-dest='./ios'"
```
And then run this command in your application projects folder:
>
> npm run build:ios
>
>
>
After running the above command, new `main.jsbundle` will be generated in your `ios/YourAppName` directory.
Next, open your project using XCode, right click on your project name then click Add Files to "`YourProjectName`", choose the `main.jsbundle` file that was generated, and then build again.
Now it might be working well.
I am using:
```
"react": "16.0.0-alpha.12",
"react-native": "^0.48.3",
```
|
PFB the command I ran, which resolves the issue.
1. npm i
2. cd ios
3. pod install
|
49,505,446 |
I tried to archive my react native project using **Product** > **Archive** on XCode9.2. But Xcode produce this error:
```
File /Users/louis/Library/Developer/Xcode/DerivedData/Scavenger-evyvzocndqoghkclcbwewolywniz/Build/Products/Release-iphoneos/Scavenger.app/main.jsbundle does not exist. This must be a bug with
My Environment:
OS: macOS Sierra 10.12.6
Node: 9.3.0
npm: 5.5.1
Watchman: 4.7.0
Xcode: Xcode 9.2 Build version 9C40b
Android Studio: 3.0 AI-171.4443003
Packages: (wanted => installed)
react: ^16.0.0 => 16.2.0
react-native: ^0.50.3 => 0.50.4
```
I also tried to run on terminal
`react-native bundle --entry-file='index.ios.js' --bundle-output='./ios/Scavenger/main.jsbundle' --dev=false --platform='ios' --assets-dest='./ios'`but ended up with error Loading dependency graph...
Unexpected end of JSON input
XCode error.

|
2018/03/27
|
[
"https://Stackoverflow.com/questions/49505446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7252084/"
] |
This issue take me some days to fixed. I got this issue when run the build on travis-ci.
Here is my fix:
Add this line to `scripts` in your package.json file.
```
"build:ios": "react-native bundle --entry-file='index.js' --bundle-output='./ios/main.jsbundle' --dev=false --platform='ios'"
```
Now your can run the command to generate `main.jsbundle`.
`yarn build:ios` or `npm run build:ios`
Open the Xcode > Select project target > add `main.jsbundle` to `Copy Bundle Resource` in Build Phases. (image below).
[](https://i.stack.imgur.com/eH0RA.png)
|
In my case I got this error at archive after updating from RN 0.53.3 to 0.55.4
```
/Users/<myuser>/Desktop/projects/<myProjectName>mobileapp/index.ios.js: Plugin 0 specified in "/Users/<myUserName>/Desktop/projects/<myProjectName>mobileapp/node_modules/babel-preset-react-native/index.js" provided an invalid property of "default" (While processing preset: "/Users/<myUserName>/Desktop/projects/<myProjectName>mobileapp/node_modules/babel-preset-react-native/index.js")
+ [[ false != true ]]
+ [[ ! -f /Users/<myUserName>/Library/Developer/Xcode/DerivedData/<myProjectName>Mobile-ghzbbftkebcwlvayfocqahvzifbe/Build/Intermediates.noindex/ArchiveIntermediates/<myProjectName>Mobile/BuildProductsPath/Release-iphoneos/<myProjectName>Mobile.app/main.jsbundle ]]
+ echo 'error: File /Users/<myUserName>/Library/Developer/Xcode/DerivedData/<myProjectName>Mobile-ghzbbftkebcwlvayfocqahvzifbe/Build/Intermediates.noindex/ArchiveIntermediates/<myProjectName>Mobile/BuildProductsPath/Release-iphoneos/<myProjectName>Mobile.app/main.jsbundle does not exist. This must be a bug with'
error: File /Users/<myUserName>/Library/Developer/Xcode/DerivedData/<myProjectName>Mobile-ghzbbftkebcwlvayfocqahvzifbe/Build/Intermediates.noindex/ArchiveIntermediates/<myProjectName>Mobile/BuildProductsPath/Release-iphoneos/<myProjectName>Mobile.app/main.jsbundle does not exist. This must be a bug with
+ echo 'React Native, please report it here: https://github.com/facebook/react-native/issues'
React Native, please report it here: https://github.com/facebook/react-native/issues
+ exit 2
```
A big importance to fix this had the line above the error related to **babel-preset-react-native**
After many hours of trying several workarounds I found a solution by downgrading `babel-preset-react-native` from `^5.0.2` to `^4.0.0` to make the archive process work.
|
49,505,446 |
I tried to archive my react native project using **Product** > **Archive** on XCode9.2. But Xcode produce this error:
```
File /Users/louis/Library/Developer/Xcode/DerivedData/Scavenger-evyvzocndqoghkclcbwewolywniz/Build/Products/Release-iphoneos/Scavenger.app/main.jsbundle does not exist. This must be a bug with
My Environment:
OS: macOS Sierra 10.12.6
Node: 9.3.0
npm: 5.5.1
Watchman: 4.7.0
Xcode: Xcode 9.2 Build version 9C40b
Android Studio: 3.0 AI-171.4443003
Packages: (wanted => installed)
react: ^16.0.0 => 16.2.0
react-native: ^0.50.3 => 0.50.4
```
I also tried to run on terminal
`react-native bundle --entry-file='index.ios.js' --bundle-output='./ios/Scavenger/main.jsbundle' --dev=false --platform='ios' --assets-dest='./ios'`but ended up with error Loading dependency graph...
Unexpected end of JSON input
XCode error.

|
2018/03/27
|
[
"https://Stackoverflow.com/questions/49505446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7252084/"
] |
I was facing this issue after I ejected from the expo to add in-app purchases.
I did the following to get it to work
```
cd <your repo>
npx react-native bundle --entry-file ./index.js --dev false --reset-cache --platform ios --bundle-output ios/main.jsbundle --assets-dest ./ios
```
**After the above commands are run you have to drag and drop the main.jsbundle and the assets into your Xcode and link it by reference and not group**
|
If properties of config file are changing at run time then make sure there is no error in that as well, if property is not set properly then main.bundlejs would not be generated.
For Example :
```
isSent:false,
isShow:false
```
this two properties were setting at run time and found that for a particular record isSent and isShow were not set which made it
```
isSent:,
isShow:
```
at run time and caused error.
|
49,505,446 |
I tried to archive my react native project using **Product** > **Archive** on XCode9.2. But Xcode produce this error:
```
File /Users/louis/Library/Developer/Xcode/DerivedData/Scavenger-evyvzocndqoghkclcbwewolywniz/Build/Products/Release-iphoneos/Scavenger.app/main.jsbundle does not exist. This must be a bug with
My Environment:
OS: macOS Sierra 10.12.6
Node: 9.3.0
npm: 5.5.1
Watchman: 4.7.0
Xcode: Xcode 9.2 Build version 9C40b
Android Studio: 3.0 AI-171.4443003
Packages: (wanted => installed)
react: ^16.0.0 => 16.2.0
react-native: ^0.50.3 => 0.50.4
```
I also tried to run on terminal
`react-native bundle --entry-file='index.ios.js' --bundle-output='./ios/Scavenger/main.jsbundle' --dev=false --platform='ios' --assets-dest='./ios'`but ended up with error Loading dependency graph...
Unexpected end of JSON input
XCode error.

|
2018/03/27
|
[
"https://Stackoverflow.com/questions/49505446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7252084/"
] |
**Recommend to use the latest Xcode and React Native versions.**
My React Native Version: 0.56 and Xcode 10
***Step 1:*** **Change AppDelegate.m** file
```
// jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
#ifdef DEBUG
jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
#else
jsCodeLocation = [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
#endif
```
***Step 2:*** **Change Xcode Build Configuration to "Release"**
Goto Products> Scheme> Edit Scheme> change Debug to release
if you are using Xcode 10+ please change Build system to Legacy Build System under File> ProjectWorkSpace Settings> Build System
***Step 3:*** Upgrade your "babel-preset-react-native" to 5.0.1, if it does not exist in your package.json file please add it.
Remove NodeModules and package.lock file and add it (npm install or yarn install).
***Step 4:*** **Change ".babelrc.js" file**
Add " `presets: ["module:metro-react-native-babel-preset"]`
***Step 5:*** **Open Terminal**
Open the terminal and navigate to your project directory run this command
```
"react-native bundle --entry-file index.js --platform ios --dev false --bundle-output ios/main.jsbundle --assets-dest ios/assets"
```
**this will generate a "main.jsbundle" file in iOS folder**
***Step 6:*** Add "main.jsbundle" file into Xcode.
Open Xcode and navigate to "Build Phase" under "Copy Bundle Resource" add "main.jsbundle" file.
Clean your project also clear your derived data in Xcode.
This will build your project in Release mode.
**For "Archive" error**
Add this dependency into your "*pod file"*
```
pod 'React', :path => '../node_modules/react-native', :subspecs => [
'CxxBridge'
]
pod 'yoga', :path => '../node_modules/react-native/ReactCommon/yoga'
pod 'DoubleConversion', :podspec => '../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec'
pod 'glog', :podspec => '../node_modules/react-native/third-party-podspecs/glog.podspec'
pod 'Folly', :podspec => '../node_modules/react-native/third-party-podspecs/Folly.podspec'
```
Remove pod and pod.lock and add again. (pod install)
***Happy Coding :)***
|
In my case, it was caused by the javascript code. The error showed at the Metro Bundler(Command Line). Check the Metro Bundler, Does it have an Error or not.
|
49,505,446 |
I tried to archive my react native project using **Product** > **Archive** on XCode9.2. But Xcode produce this error:
```
File /Users/louis/Library/Developer/Xcode/DerivedData/Scavenger-evyvzocndqoghkclcbwewolywniz/Build/Products/Release-iphoneos/Scavenger.app/main.jsbundle does not exist. This must be a bug with
My Environment:
OS: macOS Sierra 10.12.6
Node: 9.3.0
npm: 5.5.1
Watchman: 4.7.0
Xcode: Xcode 9.2 Build version 9C40b
Android Studio: 3.0 AI-171.4443003
Packages: (wanted => installed)
react: ^16.0.0 => 16.2.0
react-native: ^0.50.3 => 0.50.4
```
I also tried to run on terminal
`react-native bundle --entry-file='index.ios.js' --bundle-output='./ios/Scavenger/main.jsbundle' --dev=false --platform='ios' --assets-dest='./ios'`but ended up with error Loading dependency graph...
Unexpected end of JSON input
XCode error.

|
2018/03/27
|
[
"https://Stackoverflow.com/questions/49505446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7252084/"
] |
In my case I got this error at archive after updating from RN 0.53.3 to 0.55.4
```
/Users/<myuser>/Desktop/projects/<myProjectName>mobileapp/index.ios.js: Plugin 0 specified in "/Users/<myUserName>/Desktop/projects/<myProjectName>mobileapp/node_modules/babel-preset-react-native/index.js" provided an invalid property of "default" (While processing preset: "/Users/<myUserName>/Desktop/projects/<myProjectName>mobileapp/node_modules/babel-preset-react-native/index.js")
+ [[ false != true ]]
+ [[ ! -f /Users/<myUserName>/Library/Developer/Xcode/DerivedData/<myProjectName>Mobile-ghzbbftkebcwlvayfocqahvzifbe/Build/Intermediates.noindex/ArchiveIntermediates/<myProjectName>Mobile/BuildProductsPath/Release-iphoneos/<myProjectName>Mobile.app/main.jsbundle ]]
+ echo 'error: File /Users/<myUserName>/Library/Developer/Xcode/DerivedData/<myProjectName>Mobile-ghzbbftkebcwlvayfocqahvzifbe/Build/Intermediates.noindex/ArchiveIntermediates/<myProjectName>Mobile/BuildProductsPath/Release-iphoneos/<myProjectName>Mobile.app/main.jsbundle does not exist. This must be a bug with'
error: File /Users/<myUserName>/Library/Developer/Xcode/DerivedData/<myProjectName>Mobile-ghzbbftkebcwlvayfocqahvzifbe/Build/Intermediates.noindex/ArchiveIntermediates/<myProjectName>Mobile/BuildProductsPath/Release-iphoneos/<myProjectName>Mobile.app/main.jsbundle does not exist. This must be a bug with
+ echo 'React Native, please report it here: https://github.com/facebook/react-native/issues'
React Native, please report it here: https://github.com/facebook/react-native/issues
+ exit 2
```
A big importance to fix this had the line above the error related to **babel-preset-react-native**
After many hours of trying several workarounds I found a solution by downgrading `babel-preset-react-native` from `^5.0.2` to `^4.0.0` to make the archive process work.
|
In my case this was caused by a space character in my project path: `/users/USER/Projects/Project HousePlants/`
That space in `Project Houseplants` the bundle can not handle and therefore can not find your `main.jsbundle`
Make sure that you have no whitespace characters in your path and try again.
[See this answer](https://stackoverflow.com/a/48280992/1116508)
|
49,505,446 |
I tried to archive my react native project using **Product** > **Archive** on XCode9.2. But Xcode produce this error:
```
File /Users/louis/Library/Developer/Xcode/DerivedData/Scavenger-evyvzocndqoghkclcbwewolywniz/Build/Products/Release-iphoneos/Scavenger.app/main.jsbundle does not exist. This must be a bug with
My Environment:
OS: macOS Sierra 10.12.6
Node: 9.3.0
npm: 5.5.1
Watchman: 4.7.0
Xcode: Xcode 9.2 Build version 9C40b
Android Studio: 3.0 AI-171.4443003
Packages: (wanted => installed)
react: ^16.0.0 => 16.2.0
react-native: ^0.50.3 => 0.50.4
```
I also tried to run on terminal
`react-native bundle --entry-file='index.ios.js' --bundle-output='./ios/Scavenger/main.jsbundle' --dev=false --platform='ios' --assets-dest='./ios'`but ended up with error Loading dependency graph...
Unexpected end of JSON input
XCode error.

|
2018/03/27
|
[
"https://Stackoverflow.com/questions/49505446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7252084/"
] |
This issue take me some days to fixed. I got this issue when run the build on travis-ci.
Here is my fix:
Add this line to `scripts` in your package.json file.
```
"build:ios": "react-native bundle --entry-file='index.js' --bundle-output='./ios/main.jsbundle' --dev=false --platform='ios'"
```
Now your can run the command to generate `main.jsbundle`.
`yarn build:ios` or `npm run build:ios`
Open the Xcode > Select project target > add `main.jsbundle` to `Copy Bundle Resource` in Build Phases. (image below).
[](https://i.stack.imgur.com/eH0RA.png)
|
This happens when there is no offline bundle file in your project, I had the same problem and this worked for me.
I have added the below line to my package.json file, under `scripts` section, so I don't have to type it every time I want to generate an offline bundle.
```
"build:ios": "react-native bundle --entry-file='index.ios.js' --bundle-output='./ios/YourAppName/main.jsbundle' --dev=false --platform='ios' --assets-dest='./ios'"
```
And then run this command in your application projects folder:
>
> npm run build:ios
>
>
>
After running the above command, new `main.jsbundle` will be generated in your `ios/YourAppName` directory.
Next, open your project using XCode, right click on your project name then click Add Files to "`YourProjectName`", choose the `main.jsbundle` file that was generated, and then build again.
Now it might be working well.
I am using:
```
"react": "16.0.0-alpha.12",
"react-native": "^0.48.3",
```
|
49,505,446 |
I tried to archive my react native project using **Product** > **Archive** on XCode9.2. But Xcode produce this error:
```
File /Users/louis/Library/Developer/Xcode/DerivedData/Scavenger-evyvzocndqoghkclcbwewolywniz/Build/Products/Release-iphoneos/Scavenger.app/main.jsbundle does not exist. This must be a bug with
My Environment:
OS: macOS Sierra 10.12.6
Node: 9.3.0
npm: 5.5.1
Watchman: 4.7.0
Xcode: Xcode 9.2 Build version 9C40b
Android Studio: 3.0 AI-171.4443003
Packages: (wanted => installed)
react: ^16.0.0 => 16.2.0
react-native: ^0.50.3 => 0.50.4
```
I also tried to run on terminal
`react-native bundle --entry-file='index.ios.js' --bundle-output='./ios/Scavenger/main.jsbundle' --dev=false --platform='ios' --assets-dest='./ios'`but ended up with error Loading dependency graph...
Unexpected end of JSON input
XCode error.

|
2018/03/27
|
[
"https://Stackoverflow.com/questions/49505446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7252084/"
] |
This commnad works for me.
```
react-native bundle --entry-file ./index.ios.js --platform ios --bundle-output ios/main.jsbundle
```
|
In my case this was caused by a space character in my project path: `/users/USER/Projects/Project HousePlants/`
That space in `Project Houseplants` the bundle can not handle and therefore can not find your `main.jsbundle`
Make sure that you have no whitespace characters in your path and try again.
[See this answer](https://stackoverflow.com/a/48280992/1116508)
|
49,505,446 |
I tried to archive my react native project using **Product** > **Archive** on XCode9.2. But Xcode produce this error:
```
File /Users/louis/Library/Developer/Xcode/DerivedData/Scavenger-evyvzocndqoghkclcbwewolywniz/Build/Products/Release-iphoneos/Scavenger.app/main.jsbundle does not exist. This must be a bug with
My Environment:
OS: macOS Sierra 10.12.6
Node: 9.3.0
npm: 5.5.1
Watchman: 4.7.0
Xcode: Xcode 9.2 Build version 9C40b
Android Studio: 3.0 AI-171.4443003
Packages: (wanted => installed)
react: ^16.0.0 => 16.2.0
react-native: ^0.50.3 => 0.50.4
```
I also tried to run on terminal
`react-native bundle --entry-file='index.ios.js' --bundle-output='./ios/Scavenger/main.jsbundle' --dev=false --platform='ios' --assets-dest='./ios'`but ended up with error Loading dependency graph...
Unexpected end of JSON input
XCode error.

|
2018/03/27
|
[
"https://Stackoverflow.com/questions/49505446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7252084/"
] |
Comment this line in AppDelegate.m
```
jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
```
Use this line:-
```
jsCodeLocation = [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
```
After that run this to make jsbundle:-
```
react-native bundle --entry-file index.js --platform ios --dev false --bundle-output ios/main.jsbundle --assets-dest ios
```
Run after this command in xcode .
Hope it will make bundle and there is no such error after that ...
Thanx
|
**Recommend to use the latest Xcode and React Native versions.**
My React Native Version: 0.56 and Xcode 10
***Step 1:*** **Change AppDelegate.m** file
```
// jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
#ifdef DEBUG
jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
#else
jsCodeLocation = [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
#endif
```
***Step 2:*** **Change Xcode Build Configuration to "Release"**
Goto Products> Scheme> Edit Scheme> change Debug to release
if you are using Xcode 10+ please change Build system to Legacy Build System under File> ProjectWorkSpace Settings> Build System
***Step 3:*** Upgrade your "babel-preset-react-native" to 5.0.1, if it does not exist in your package.json file please add it.
Remove NodeModules and package.lock file and add it (npm install or yarn install).
***Step 4:*** **Change ".babelrc.js" file**
Add " `presets: ["module:metro-react-native-babel-preset"]`
***Step 5:*** **Open Terminal**
Open the terminal and navigate to your project directory run this command
```
"react-native bundle --entry-file index.js --platform ios --dev false --bundle-output ios/main.jsbundle --assets-dest ios/assets"
```
**this will generate a "main.jsbundle" file in iOS folder**
***Step 6:*** Add "main.jsbundle" file into Xcode.
Open Xcode and navigate to "Build Phase" under "Copy Bundle Resource" add "main.jsbundle" file.
Clean your project also clear your derived data in Xcode.
This will build your project in Release mode.
**For "Archive" error**
Add this dependency into your "*pod file"*
```
pod 'React', :path => '../node_modules/react-native', :subspecs => [
'CxxBridge'
]
pod 'yoga', :path => '../node_modules/react-native/ReactCommon/yoga'
pod 'DoubleConversion', :podspec => '../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec'
pod 'glog', :podspec => '../node_modules/react-native/third-party-podspecs/glog.podspec'
pod 'Folly', :podspec => '../node_modules/react-native/third-party-podspecs/Folly.podspec'
```
Remove pod and pod.lock and add again. (pod install)
***Happy Coding :)***
|
26,822,018 |
Is there a way to get the use ADB to simulate a Recent App key press? I do not see it in the list of [assigned keys](https://stackoverflow.com/questions/7789826/adb-shell-input-events) and I am not able to select it using `adb input shell tap` despite getting the coordinates from the debugging options.
I am trying to automate a task on my own personal phone (Nexus 5 with soft keys) so any hacky way is fine, assuming there is not a clean way to do this.
|
2014/11/08
|
[
"https://Stackoverflow.com/questions/26822018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1279884/"
] |
*See @SimonMarquis answer below*
```
adb shell input keyevent KEYCODE_APP_SWITCH
```
---
*(OBSOLETE)*
I don't think there is a keycode for it.
However, I **am** able to open the recent apps menu with `adb shell input tap` (testing on a Nexus 5 with Lollipop). For example:
```
adb shell input tap 800 1890
```
|
```
adb shell input keyevent KEYCODE_APP_SWITCH
```
Still works, you don't even have to put its numeric value (187) into the command.
|
26,822,018 |
Is there a way to get the use ADB to simulate a Recent App key press? I do not see it in the list of [assigned keys](https://stackoverflow.com/questions/7789826/adb-shell-input-events) and I am not able to select it using `adb input shell tap` despite getting the coordinates from the debugging options.
I am trying to automate a task on my own personal phone (Nexus 5 with soft keys) so any hacky way is fine, assuming there is not a clean way to do this.
|
2014/11/08
|
[
"https://Stackoverflow.com/questions/26822018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1279884/"
] |
The solution is to use the `KEYCODE_APP_SWITCH` KeyEvent:
```
adb shell input keyevent KEYCODE_APP_SWITCH
```
|
```
adb shell input keyevent KEYCODE_APP_SWITCH
```
Still works, you don't even have to put its numeric value (187) into the command.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.