Search is not available for this dataset
qid
int64 1
74.7M
| question
stringlengths 25
64.6k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 0
115k
| response_k
stringlengths 3
61.5k
|
---|---|---|---|---|---|
47,087 | Is it okay to use `app.mycoolname.local` for URLs that are private / internal?
We have several applications that are web based, but they are private apps and are not exposed to the public.
We have been using ".net" for some of these, which doesn't make sense since they could collied with a real URL on the internet. That hasn't been a problem yet.
But now I have a new group of applications and I want to name them using a "popular" name that will definatly collide with a URL on the internet.
Should I use `app.mycoolname.local`? I have it set up this way right now, and it seems to be working. I have read a few places where it was encouraged, but then I saw a few places where it wasn't working (some problem on Mac, but we don't have those, so NBD). | 2009/07/28 | [
"https://serverfault.com/questions/47087",
"https://serverfault.com",
"https://serverfault.com/users/-1/"
] | As pointed out by many; in general a bad idea to use an unregistered TLD for intranets.
However [0] states that there are some commonly used nanmes (although not approved for intranet use only). [0] still discourages to use the mentioned TLD for local nets, and local. should not be used in any other situation than a multicast DNS.
[0] RFC6762, appendix G : <https://www.rfc-editor.org/rfc/rfc6762#appendix-G> | I've always been a big fan of the internal .lan TLD, myself. |
47,087 | Is it okay to use `app.mycoolname.local` for URLs that are private / internal?
We have several applications that are web based, but they are private apps and are not exposed to the public.
We have been using ".net" for some of these, which doesn't make sense since they could collied with a real URL on the internet. That hasn't been a problem yet.
But now I have a new group of applications and I want to name them using a "popular" name that will definatly collide with a URL on the internet.
Should I use `app.mycoolname.local`? I have it set up this way right now, and it seems to be working. I have read a few places where it was encouraged, but then I saw a few places where it wasn't working (some problem on Mac, but we don't have those, so NBD). | 2009/07/28 | [
"https://serverfault.com/questions/47087",
"https://serverfault.com",
"https://serverfault.com/users/-1/"
] | If you were after some more information on [.local](http://en.wikipedia.org/wiki/.local) and why it may or may not be an issue for you to use it. There don't actually seem to be any [reserved zones](https://www.rfc-editor.org/rfc/rfc2606) for internal use | We use .local all the time with both macs and pcs. Enjoy |
47,087 | Is it okay to use `app.mycoolname.local` for URLs that are private / internal?
We have several applications that are web based, but they are private apps and are not exposed to the public.
We have been using ".net" for some of these, which doesn't make sense since they could collied with a real URL on the internet. That hasn't been a problem yet.
But now I have a new group of applications and I want to name them using a "popular" name that will definatly collide with a URL on the internet.
Should I use `app.mycoolname.local`? I have it set up this way right now, and it seems to be working. I have read a few places where it was encouraged, but then I saw a few places where it wasn't working (some problem on Mac, but we don't have those, so NBD). | 2009/07/28 | [
"https://serverfault.com/questions/47087",
"https://serverfault.com",
"https://serverfault.com/users/-1/"
] | Do not use .local. Do not use .anythingyoujustmadeup either. Don't even use the reserved TLDs. Use a real domain or sub domain and just don't allow it to be visible to the outside world. The main reason for this is when you work for company A that uses .local (or example.com) and they buy company B that also uses .local (or example.com). Not a lot of fun bringing the two namespaces together. | I've always been a big fan of the internal .lan TLD, myself. |
174,684 | It is from this [video](https://youtu.be/REVpwKKd8VA). It is at 14 second. Here it is:
>
> **Greetings programs**, Trace here for DNews.
>
>
>
I searched it on the internet, but could not find what it means. What is it from and what does it mean? | 2018/07/30 | [
"https://ell.stackexchange.com/questions/174684",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/60696/"
] | It might be a nod to the 1982 movie *Tron* the main protagonist uses it as a greeting fairly often.
**Kevin Flynn:** Greetings, programs. | This appears to be a joke, perhaps an "in joke" that would be understood by regular subscribers to the youtube channel.
Perhaps it's a parody of "Greetings, Earthlings", the greeting made by aliens from outer space in schlock films. Perhaps it is some joke along the lines of "Lots of the hits on my videos come from search engines." Or a nerd joke "Did you know that the brain could be simulated by a computer program?"
It's very common for YouTubers and others to stick some weird catch-phrase near the beginning, that they think is very clever. Sometimes it's just gibberish. Don't waste any brain cells trying to understand it. |
79,073 | I can not understand why a peroxide $\ce{R-O-O-R}$ is considered reactive and unstable.
Going down one row on the periodic table, a disulfide bridge ($\ce{R-S-S-R}$) is apparently super stable and super important to proteins 3d structure.
At the same time, a thioester is considered to be as unstable/reactive as ATP and the ester is the stable one?
***What am I conceptually missing here to explain this contradiction?*** | 2017/07/19 | [
"https://chemistry.stackexchange.com/questions/79073",
"https://chemistry.stackexchange.com",
"https://chemistry.stackexchange.com/users/46976/"
] | Some hard data: bond enthalpies (in $\pu{kJ mol-1}$)
$$\begin{array}{c|c|c|c} \text{Bond} & \text{Enthalpy} &
\text{Bond} & \text{Enthalpy} \\ \hline
\ce{C-C} & 350 & \ce{Si-Si} & 226\\
\ce{N-N} & 163 & \ce{P-P} & 201\\
\ce{O-O} & 146 & \ce{S-S} & 226\\
\ce{F-F} & 155 & \ce{Cl-Cl} & 240 \\
\end{array}$$
We observe a decrease in bond energy from carbon to nitrogen and from silicon to phosphorus. It is clear and probably have same reason: appearance of lone electron pair of the atom. There is a repulsion between lone pairs, that is in partially compensated by stronger bonds formed by smaller atoms (the atomic radii falls down to the end of the row). When moving from second to third row, this repulsion is reduced thanks to larger size of atoms of the elements of the third row.
The general decrease in energy from carbon to silicon is thanks to increased size of the orbitals of valence level, making them more diffuse with less efficient overlap and longer bond length.
The stability of esters vs thioesters is ruled by different reasons. Sulfur is not as electronegative as oxygen, but when you consider an anion, sulfur anions have larger radius and are less prone to grabbing first positive charge they find. So sulfur anions are more stable intermediates (kinetically), and thus polar dissociation of thioester bonds is easier. | It has to do with electronegativity (EN). Remember the concept of "formal charge"?
In a bond between molecule 1 and 2, if molecule 1 is more electronegative than molecule 2, then the electrons will be drawn closer to molecule one.
That is general, but to get to your specific question, Oxygen's EN is 3.5. Sulfur's EN is aprox 2.5. Carbon's EN is also 2.5.
So in a Carbon oxygen bond, the electrons will shift to oxygen.
In a carbon-sulfur bond, the electrons will be relatively in the middle, thus one can expect a carbon-sulfur, and sulfur-sulfur bonds to be relatively equal in strenght.
On the other hand, the peroxides (when bonded to carbons) will always pull the electrons towards them more than the carbons wil, and at some point, the bond will eventually snap. |
1,709,398 | Here is the exercise:
Let's consider the Banach space $l^{\infty}$ with the sup norm.
We consider the following subspace of $l^{\infty}$ :
$C = ${ $x \in l^{\infty} : \lim\_{n\to \infty} x\_n\quad exists $}.
We have to show that $C$ is a closed subspace of $l^{\infty}$ and is thus also a Banach space with respect to the sup norm.
Let $y$ denote $\lim\_{n\to \infty}$ $x\_n$.
The key there is to show that every convergent sequence in $C$, say every sequence in $C$ converges within $C$, hence we have to show that $y$ belongs to $C$.
I've successfully shown that $y$ is a Cauchy sequence in $l^{\infty}$, but I don't know what to do with that. When I'm looking at the correction, it says that { $y$ Cauchy } $\Rightarrow$ {$y$ convergent} $\Rightarrow$ {y $\in$ $C$}.
That's where I'm lost. I don't understand why we can deduce $y$ is convergent by having shown $y$ is Cauchy. Also, I don't understand why we have to show that $y$ is Cauchy.
I hope someone can explain me those two problems I have.
I do understand though that $C$ being closed implies that $C$ is a Banach space. | 2016/03/22 | [
"https://math.stackexchange.com/questions/1709398",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/325137/"
] | Let $(x\_n)\_n$ be a Cauchy sequence in $C$ converging to $y=(y\_j)\_j\in l\_{\infty}.$ Let $x\_n=(x\_{n,j})\_j.$ For each $j$ we have $\lim\_{n\to \infty}x\_{n,j}=y\_j . $
By contradiction: Suppose $y$ is not a convergent sequence. Then for some $r>0$, we have $\forall n\in N\;(\exists j,k\;(n\leq j<k\land |y\_j-y\_k|>r).$
But let $\|x\_{n}-y\|<r/4$ and let $j\_0$ satisfy $(j\geq j\_0\implies |x\_{n,j}-L(n)|<r/4),$ where $L(n)=\lim\_{j\to \infty}x\_{n,j}.$
Then there exists $j\geq j\_0$ and $k>j$ such that $|y\_j-y\_k|>r.$
This yields $$|y\_j-L(n)|\leq |y\_j-x\_{n,j}|+|x\_{n,j}-L(n)| <\|y-x\_n\|+r/4<r/2$$ and $$|y\_k-L(n)|\leq |y\_k-x\_{n.k}|+|x\_{n,k}-L(n)|< \|y-x\_n|+r/4<2.$$ But then we have $|y\_j-L(n)|<r/2$ and $|y\_k-L(n)|<r/2,$ which implies $|y\_j-y\_k|<r,$ a contradiction. | Consider $l^{\infty}\setminus C$
Let $y\_{n} \in l^{\infty}\setminus C\,,$ then $\forall y \in\mathbb{R}, \exists \varepsilon\_{y} > 0$ such that $\|y-y\_{n}\|\_{\infty} > 2\varepsilon\_{y}$
Now consider $\mathbb{B}(y\_{n},\varepsilon\_{y})$
Let $z\_{n} \in \mathbb{B}(y\_{n},\varepsilon\_{y})\Longrightarrow \|y\_{n}-z\_{n}\|\_{\infty}<\varepsilon\_{y}$
So $\forall y \in \mathbb{R}$;
$\|y-z\_{n}\|\_{\infty} = \|y-y\_{n}-(z\_{n}-y\_{n})\|\_{\infty} \geq \|y-y\_{n}\|\_{\infty} - \|z-y\_{n}\|\_{\infty} > 2\varepsilon\_{y} - \varepsilon\_{y} = \varepsilon\_{y} > 0$
$\Longrightarrow \mathbb{B}(y\_{n},\varepsilon\_{y}) \subseteq l^{\infty}\setminus C\Longrightarrow l^{\infty}\setminus C$ is open $\Longrightarrow C$ is closed. |
1,709,398 | Here is the exercise:
Let's consider the Banach space $l^{\infty}$ with the sup norm.
We consider the following subspace of $l^{\infty}$ :
$C = ${ $x \in l^{\infty} : \lim\_{n\to \infty} x\_n\quad exists $}.
We have to show that $C$ is a closed subspace of $l^{\infty}$ and is thus also a Banach space with respect to the sup norm.
Let $y$ denote $\lim\_{n\to \infty}$ $x\_n$.
The key there is to show that every convergent sequence in $C$, say every sequence in $C$ converges within $C$, hence we have to show that $y$ belongs to $C$.
I've successfully shown that $y$ is a Cauchy sequence in $l^{\infty}$, but I don't know what to do with that. When I'm looking at the correction, it says that { $y$ Cauchy } $\Rightarrow$ {$y$ convergent} $\Rightarrow$ {y $\in$ $C$}.
That's where I'm lost. I don't understand why we can deduce $y$ is convergent by having shown $y$ is Cauchy. Also, I don't understand why we have to show that $y$ is Cauchy.
I hope someone can explain me those two problems I have.
I do understand though that $C$ being closed implies that $C$ is a Banach space. | 2016/03/22 | [
"https://math.stackexchange.com/questions/1709398",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/325137/"
] | Let $(x\_n)\_n$ be a Cauchy sequence in $C$ converging to $y=(y\_j)\_j\in l\_{\infty}.$ Let $x\_n=(x\_{n,j})\_j.$ For each $j$ we have $\lim\_{n\to \infty}x\_{n,j}=y\_j . $
By contradiction: Suppose $y$ is not a convergent sequence. Then for some $r>0$, we have $\forall n\in N\;(\exists j,k\;(n\leq j<k\land |y\_j-y\_k|>r).$
But let $\|x\_{n}-y\|<r/4$ and let $j\_0$ satisfy $(j\geq j\_0\implies |x\_{n,j}-L(n)|<r/4),$ where $L(n)=\lim\_{j\to \infty}x\_{n,j}.$
Then there exists $j\geq j\_0$ and $k>j$ such that $|y\_j-y\_k|>r.$
This yields $$|y\_j-L(n)|\leq |y\_j-x\_{n,j}|+|x\_{n,j}-L(n)| <\|y-x\_n\|+r/4<r/2$$ and $$|y\_k-L(n)|\leq |y\_k-x\_{n.k}|+|x\_{n,k}-L(n)|< \|y-x\_n|+r/4<2.$$ But then we have $|y\_j-L(n)|<r/2$ and $|y\_k-L(n)|<r/2,$ which implies $|y\_j-y\_k|<r,$ a contradiction. | Let $X=\{1,2,3,\cdots\}\cup\{\infty\}$ and define a topology on $X$ that is discrete, but neighborhoods of $\infty$ include all large integers. Then $X$ is compact, and your sequences are the same as the continuous functions $C(X)$. This is the one-point compactification. $C(X)$ is a Banach space, and the elements of $C(X)$ are determined by their values on the integers, with a natural isometric inclusion in $\ell^{\infty}$. |
399,962 | We have a bunch of servers that our engineers remote desktop into, but each server has a two connection limit. We will often attempt to RDP into these boxes and we will see the "This machine has exceeded the maximum number of connections" message.
It's a big pain because we have sent out several email messages to these users, and they never get the point.
I know how to connect to the root console and boot people, but I'd prefer not to do that. I also know that there are ways of booting inactive sessions after a period of time, and I don't want to do that either.
I want to force users to *learn* that they need to log out. This doesn't happen if you log them out manually (plus logging them out manually is a pain). If you just log them out manually, these engineers won't think twice about staying connected in an RDP session because it is convenient for them.
I would prefer some notification system where the inconsiderate user is notified via email or NET SEND message that their account is being disconnected from machine. That way, they will realize that they are doing something wrong. Even better, if they are in violation several times, I would like their account to be locked until a system administrator unlocks it.
Is there a way to achieve the goal of having users log out manually? All suggestions are welcome. | 2012/03/12 | [
"https://superuser.com/questions/399962",
"https://superuser.com",
"https://superuser.com/users/107098/"
] | You can use the Remote Desktop Session Host Configuration tools, or (better) Group Policies to define rules around RDP disconnects.
If you use Group Policy and OUs, you will be able to allow some users to stay "disconnected" and force others to log-off after disconnect.
Specifically check out these policy branches:
* Computer Configuration\Policies\Administrative Templates\Windows Components\Remote Desktop Services\Remote Desktop Session Host\Session Time Limits
* User Configuration\Policies\Administrative Templates\Windows Components\Remote Desktop Services\Remote Desktop Session Host\Session Time Limits
And policies like these:
>
> *End a disconnected session*
>
>
> Specify the maximum amount of time that a disconnected user session is
> kept active on the RD Session Host server. If you specify "Never," the
> user's disconnected session is maintained for an unlimited time.
>
>
> When a session is in a disconnected state, running programs are kept
> active even though the user is no longer actively connected.
>
>
>
.
>
> *When a session limit is reached or connection is broken*
>
>
> Specify whether to disconnect or end the user's Remote Desktop
> Services session when an active session limit or an idle session limit
> is reached.
>
>
> If the user's session is disconnected, the programs that the user is
> running are kept active even though the user is no longer actively
> connected.
>
>
> If the user's session is ended, the user will need to establish a new
> Remote Desktop Services session with an RD Session Host server.
>
>
>
For more info, check out [this page from MS](http://technet.microsoft.com/en-us/library/cc754272.aspx) about RDP disconnection policies. | Not sure how much help this will be, but it's worth taking a look at [using VNC viewer instead](http://www.realvnc.com/products/free/4.1/winvnc.html). It can be set up to log off once the last viewer is disconnected.
You can then force users to use VNC by blocking the RDP port on the machine. |
399,962 | We have a bunch of servers that our engineers remote desktop into, but each server has a two connection limit. We will often attempt to RDP into these boxes and we will see the "This machine has exceeded the maximum number of connections" message.
It's a big pain because we have sent out several email messages to these users, and they never get the point.
I know how to connect to the root console and boot people, but I'd prefer not to do that. I also know that there are ways of booting inactive sessions after a period of time, and I don't want to do that either.
I want to force users to *learn* that they need to log out. This doesn't happen if you log them out manually (plus logging them out manually is a pain). If you just log them out manually, these engineers won't think twice about staying connected in an RDP session because it is convenient for them.
I would prefer some notification system where the inconsiderate user is notified via email or NET SEND message that their account is being disconnected from machine. That way, they will realize that they are doing something wrong. Even better, if they are in violation several times, I would like their account to be locked until a system administrator unlocks it.
Is there a way to achieve the goal of having users log out manually? All suggestions are welcome. | 2012/03/12 | [
"https://superuser.com/questions/399962",
"https://superuser.com",
"https://superuser.com/users/107098/"
] | For a notification system, I guess you would have to develop it, using APIs such as [WTSEnumerateSession](https://msdn.microsoft.com/en-us/library/aa383833%28v=vs.85%29.aspx).
This means developing something like a windows service which would query regularly your servers in order to hunt disconnected sessions, and do what you want with them.
This could take you a bunch of days of work to get it right.
Otherwise, I suggest another approach to this trouble:
* Setup two groups of rdp users on servers: say TrustedDisconnectors and UntrustedDisconnectors.
* Setup a policy for UntrustedDisconnectors, causing them to have their session logged out on a somewhat short disconnection timeout.
* Communicate about that change. States that engineers frequently failing to disconnect properly without valid reasons would no more be allowed to disconnect without being logged off. | Not sure how much help this will be, but it's worth taking a look at [using VNC viewer instead](http://www.realvnc.com/products/free/4.1/winvnc.html). It can be set up to log off once the last viewer is disconnected.
You can then force users to use VNC by blocking the RDP port on the machine. |
399,962 | We have a bunch of servers that our engineers remote desktop into, but each server has a two connection limit. We will often attempt to RDP into these boxes and we will see the "This machine has exceeded the maximum number of connections" message.
It's a big pain because we have sent out several email messages to these users, and they never get the point.
I know how to connect to the root console and boot people, but I'd prefer not to do that. I also know that there are ways of booting inactive sessions after a period of time, and I don't want to do that either.
I want to force users to *learn* that they need to log out. This doesn't happen if you log them out manually (plus logging them out manually is a pain). If you just log them out manually, these engineers won't think twice about staying connected in an RDP session because it is convenient for them.
I would prefer some notification system where the inconsiderate user is notified via email or NET SEND message that their account is being disconnected from machine. That way, they will realize that they are doing something wrong. Even better, if they are in violation several times, I would like their account to be locked until a system administrator unlocks it.
Is there a way to achieve the goal of having users log out manually? All suggestions are welcome. | 2012/03/12 | [
"https://superuser.com/questions/399962",
"https://superuser.com",
"https://superuser.com/users/107098/"
] | You can use the Remote Desktop Session Host Configuration tools, or (better) Group Policies to define rules around RDP disconnects.
If you use Group Policy and OUs, you will be able to allow some users to stay "disconnected" and force others to log-off after disconnect.
Specifically check out these policy branches:
* Computer Configuration\Policies\Administrative Templates\Windows Components\Remote Desktop Services\Remote Desktop Session Host\Session Time Limits
* User Configuration\Policies\Administrative Templates\Windows Components\Remote Desktop Services\Remote Desktop Session Host\Session Time Limits
And policies like these:
>
> *End a disconnected session*
>
>
> Specify the maximum amount of time that a disconnected user session is
> kept active on the RD Session Host server. If you specify "Never," the
> user's disconnected session is maintained for an unlimited time.
>
>
> When a session is in a disconnected state, running programs are kept
> active even though the user is no longer actively connected.
>
>
>
.
>
> *When a session limit is reached or connection is broken*
>
>
> Specify whether to disconnect or end the user's Remote Desktop
> Services session when an active session limit or an idle session limit
> is reached.
>
>
> If the user's session is disconnected, the programs that the user is
> running are kept active even though the user is no longer actively
> connected.
>
>
> If the user's session is ended, the user will need to establish a new
> Remote Desktop Services session with an RD Session Host server.
>
>
>
For more info, check out [this page from MS](http://technet.microsoft.com/en-us/library/cc754272.aspx) about RDP disconnection policies. | For a notification system, I guess you would have to develop it, using APIs such as [WTSEnumerateSession](https://msdn.microsoft.com/en-us/library/aa383833%28v=vs.85%29.aspx).
This means developing something like a windows service which would query regularly your servers in order to hunt disconnected sessions, and do what you want with them.
This could take you a bunch of days of work to get it right.
Otherwise, I suggest another approach to this trouble:
* Setup two groups of rdp users on servers: say TrustedDisconnectors and UntrustedDisconnectors.
* Setup a policy for UntrustedDisconnectors, causing them to have their session logged out on a somewhat short disconnection timeout.
* Communicate about that change. States that engineers frequently failing to disconnect properly without valid reasons would no more be allowed to disconnect without being logged off. |
243,523 | **SCENARIO:**
web application which I think is affected by:
* a **self-xss** in the profile section of a user.
* **logout CSRF**
* **login CSRF**
Below I described the test I did to check for the last 2 vulnerabilities, I'd appreciate an opinion about their correctness.
**TEST:**
**Logout CSRF:**
1. in one tab I'm an authenticated user
2. on another tab where in the same browser where the user is authenticated I browse to this page.
```
<html>
<body>
<!-- logout the victim -->
<a href="https://vuln/logout.aspx" target="_self">click</a>
</body>
</html>
```
3. If I go back to the first tab my session is ended --> here I'm quite sure this test is enough to proof logout csrf.
**login CSRF:**
The web server is IIS and then it uses `__VIEWSTATE` and `__EVENTVALIDATION`. The test is the following:
1. I create and host a page like this. NOTE: I substituted the real value with XXX but in my test I used current value retrieved from the application
```
<!-- login the victim into the attacker profile -->
<form name=myform action="https://vuln/Login.aspx" method="POST">
<input type="hidden" name="user" value="hacker" />
<input type="hidden" name="passw" value="hacker" />
<input type="hidden" name="LoginBtn" value="..." />
<input type="hidden" name="__VIEWSTATEGENERATOR" id="__VIEWSTATEGENERATOR" value="XXX" />
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/XXX"/>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/XXX/" />
</form>
```
2. I simulate a user that browses to that page.
3. The user is logged as the attacker.
Does this mean that **login CSRF** is happening? Should `__VIEWSTATE` and `__EVENTVALIDATION` prevent this?
**EDIT (01-20-2021)**
Reading the comments I decided to edit this post to add some notes to understand the final attack I wanted to deliver. I already know that *taken alone*: self-xss, logout csrf, login csrf are not considered to be vulnerabilities most of the times, although [owasp](https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#login-csrf) suggests how to mitigate login csrf for example.
Anyway my goal was to escalate from self-xss to xss as illustrated elsewhere: [brutelogic](https://brutelogic.com.br/blog/leveraging-self-xss/) or by [Ch3ckM4te](https://medium.com/@Ch3ckM4te/self-xss-to-account-takeover-72c89775cf8f) which reflects mine scenario but exploiting Oauth.
The steps were the following:
1- Send a link to the victim and wait for him to open it
2- Logout the victim (if he was authenticated)
3- Login the victim with the attacker's account credentials
4- Redirect the victim (now authenticated with the attacker's account) to the page where self-xss is stored.
5- Now the **arbitrary javascript** chosen by the attacker is executed in the victim's browser
Somebody pointed out in the comment that because I can't steal the session token or perform some action in the name of the victim then this chain of vulnerabilites is not dangerous.
The fact that I can **execute arbitrary javascript in the context of the victim's browser** in my opinion should be enough to consider this a proper attack. Just to do an example you could run:
* BeeF hook.js and then have a lot of options.
>
> What is BeEF? BeEF which stands for Browser Exploitation Framework is
> a tool that can hook one or more browsers and can use them as a
> beachhead of launching various direct commands and further attacks
> against the system from within the browser context
>
>
>
To have an idea, when you hook a browser this is the Beef's commands panel
[![enter image description here](https://i.stack.imgur.com/7zpAE.png)](https://i.stack.imgur.com/7zpAE.png)
**POC**
```
<html>
<body>
<!-- logout the victim from he web application -->
<a href="https://vuln.com/logout.aspx" target="_self" onclick=xss_login()>click</a>
<!-- login the victim into the attacker profile -->
<form name=myform action="https://vuln.com/Login.aspx" method="POST">
<input type="hidden" name="user" value="hacker" />
<input type="hidden" name="passw" value="hacker" />
<input type="hidden" name="LoginBtn" value="Loadin" />
<input type="hidden" name="__VIEWSTATEGENERATOR" id="__VIEWSTATEGENERATOR" value="XXX" />
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="XXX"/>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="XXX" />
</form>
<script>
//redirect the victim to the page where Self-XSS is stored and execute the payload in the user's browser context
function xss_redirect()
{
setTimeout(function(){
location.href="https://vuln.com/atk/item=xss";
} , 400);
}
function xss_login()
{
setTimeout(function(){
document.myform.submit();
xss_redirect();
}, 200);
}
</script>
</body>
</html>
```
**EXAMPLE OF 300$ BOUNTY**
<https://hackerone.com/reports/632017> | 2021/01/19 | [
"https://security.stackexchange.com/questions/243523",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/188823/"
] | Yep, indeed the scenario is enough to say that the web app is vulnerable to Login/Logout CSRF.
ViewState and EventValidation are not meant to protect against CSRF (I guess it's a .net/asp(x) application).
[In fact](http://aspalliance.com/articleViewer.aspx?aId=135&pId=)
>
> ViewState is used to track and restore the state values of controls
> that would otherwise be lost, either because those values do not post
> with the form or because they are not in the page HTML. This means
> that a control totally defined in your page HTML, with no changes made
> in the code, will have no ViewState at all, as is often the case when
> using drag-n-drop with static content. Instead, ViewState only holds
> the values of properties that are dynamically changed somehow, usually
> in code, data-binding, or user interactions, so that they can be
> restored on each request.
>
>
>
And EventValidation prevents unauthorized requests sent by potentially malicious users from the client. To ensure that each and every postback and callback event originates from the expected user interface elements, the page adds an extra layer of validation on events. (<https://docs.microsoft.com/en-us/archive/msdn-magazine/2006/december/cutting-edge-the-client-side-of-asp-net-pages>)
And in your scenario, the "hacker" user becomes the legitimate user.
To prevent CSRF in asp/x applications, Microsoft offers an AntiForgery Class within its .net [Framework](https://docs.microsoft.com/en-us/dotnet/api/system.web.helpers.antiforgery?view=aspnet-webpages-3.2) | Your vulnerability doesn't do anything in practice.
===================================================
Conor already explained [in his answer](https://security.stackexchange.com/a/243535/163495) that Login CSRF doesn't really exist, but I think that's not the full story.
You mentioned a self-XSS vulnerability in the profile, which leads me to believe that your attack vector looks as follows:
1. Lure the victim to your site
2. Abuse a CSRF vulnerability to log the victim in with your account
3. Have the victim visit the vulnerable site
4. The self-XSS payload now executes in the victim's browser.
However, XSS vulnerabilities are usually done for two reasons:
1. Steal the victim's session
2. Perform actions in the victim's name
Neither of these apply to you in this scenario, since the victim is logged in via an account you already control. As such, stealing the session of an account who's credentials you already have is pointless. Further, having the victim perform actions on an account you already own is pointless as well - you could just perform these actions yourself.
That limits you to actions that you could already perform in step 1, luring the victim to your site. That isn't a vulnerability either. |
3,532 | When programming in R, I've used the [multicore](http://www.rforge.net/doc/packages/multicore/multicore.html) package a few times. However, I've never seen a statement about how it handles it's random numbers. When I use openMP with C, I'm careful to use a proper parallel RNG, but with R I've assume that something sensible happens. Can anyone confirm that something sensible does happen?
**Example**
From the documentation, we have
```
x <- foreach(icount(1000), .combine = "+") %do% rnorm(4)
```
How are the `rnorm``s generated? | 2010/10/12 | [
"https://stats.stackexchange.com/questions/3532",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/8/"
] | I'm not sure how the `foreach` works (from the doMC package, I guess), but in multicore if you did something like `mclapply` the `mc.set.seed` parameter defaults to `TRUE` which gives each process a different seed (e.g. `mclapply(1:1000, rnorm)`). I assume your code is translated into something similar, i.e. it boils down to calls to `parallel` which has the same convention.
But also see page 16 of the [slides](http://www.stat.umn.edu/~charlie/parallel/) by Charlie Geyer, which recommends the [rlecuyer](http://cran.r-project.org/web/packages/rlecuyer/index.html) package for parallel independent streams with theoretical guarantees. Geyer's page also has sample code in R for the different setups. | You might want to look at page 5 of this [document](http://cran.r-project.org/web/packages/multicore/multicore.pdf) and of this [document](http://cran.r-project.org/web/packages/doMC/vignettes/gettingstartedMC.pdf). By default, under R, each core sets is own seed (i seem to recall using high precision time).
NB: if you use foreach() from Revolution-computing under windows then i suspect something sensible will **not** happen. Windows is not POSIX compliant, and this should pose problems when each core needs a different high prec. starting time to set it's seed (unfortunately i don't have windows handy so i can't check this empirically). |
8,267,254 | I want to rewrite a URL through htaccess, but I am not getting the solution to do the specific rewriting. For e.g., I have a URL:
**http://www.yourdomain.com/page/about-us.html**
Now I want to remove **page** from above URL, so it should look like;
**http://www.yourdomain.com/about-us.html**
Can anybody help me with this.
Thanks in advance. | 2011/11/25 | [
"https://Stackoverflow.com/questions/8267254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/928715/"
] | Something like this should work:
```
RewriteEngine on
RewriteRule ^about-us.html$ /page/about-us.html
```
If you need it done on any URL put into the site, then something like this:
```
RewriteEngine on
RewriteRule ^([_\&\'\,\+A-Za-z0-9-]+).html$ /page/$1.html
``` | Assuming you want a 301:
```
RewriteEngine on
RewriteRule ^page/about-us.html$ /about.html [R=301,L]
``` |
562 | I have briefly used the new Photosynth app and noticed that the output has a fairly low resolution.
I suppose a compromise has been made for the processing power and bandwidth available on a mobile phone, but it makes the end result less than impressive.
Is there any way to use the app only to make full resolution photographs, which can then be processed on a desktop computer using the [Image Composite Editor](http://research.microsoft.com/en-us/um/redmond/groups/ivm/ice/) for Photosynth?
Or is there a third-party app which has a similar camera interface for taking photos to make 'synths'?
Here is a QR code to get the Photosynth app:
![Photosynth](https://i.stack.imgur.com/w85i2.png) | 2012/05/30 | [
"https://windowsphone.stackexchange.com/questions/562",
"https://windowsphone.stackexchange.com",
"https://windowsphone.stackexchange.com/users/157/"
] | Gyroscope can improve the same data you already have. Some apps like compass apps would work better with this sensor.
I think gyroscope can precisely feel when you hang your phone with your arm straight and starts to turn yourself. I think compass fell when you turn only the phone in its own axis.
Edit:[Testing Photosynth with and without gyro](http://www.wpcentral.com/does-having-gyroscope-affect-photosynth). | In theory using the gyroscope will be more accurate and wont lag/jump-around like using the compass+accelerometer found on the Lumia 800.
In [real-world usage](http://www.wpcentral.com/does-having-gyroscope-affect-photosynth) the gyroscope doesn't make a noticeable difference when compared to using the compass+accelerometer. |
50,785,432 | I am new to the bootstrap. I have following bootstrap code:
```html
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div style="padding-top: 25px; ">
<div class="col-md-10 col-md-offset-1" style="background-color: #F0F8FF;">
<div class="col-md-3">
<img src="{{URL::asset('/images/car.png')}}" alt="profile Pic" height="50" width="50">Car
</div>
</div>
</div>
```
Now, I need the first image and then under the image 'car' word in the center to the div and under word some discription about the car. like image of this. how can I do this?
See image here:
![see image here](https://i.stack.imgur.com/2iwR6.png) | 2018/06/10 | [
"https://Stackoverflow.com/questions/50785432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9868104/"
] | I had this error just try this it will work,
instead of using user-key just use apikey.
developers.zomato.com/api/v2.1/categories?**apikey**=your API key
Good luck. | You're passing the api key as a query param in RestAssured. It should be passed as a header param. Like this:
```
.header("user-key", <api_key>)
``` |
50,785,432 | I am new to the bootstrap. I have following bootstrap code:
```html
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div style="padding-top: 25px; ">
<div class="col-md-10 col-md-offset-1" style="background-color: #F0F8FF;">
<div class="col-md-3">
<img src="{{URL::asset('/images/car.png')}}" alt="profile Pic" height="50" width="50">Car
</div>
</div>
</div>
```
Now, I need the first image and then under the image 'car' word in the center to the div and under word some discription about the car. like image of this. how can I do this?
See image here:
![see image here](https://i.stack.imgur.com/2iwR6.png) | 2018/06/10 | [
"https://Stackoverflow.com/questions/50785432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9868104/"
] | I had this error just try this it will work,
instead of using user-key just use apikey.
developers.zomato.com/api/v2.1/categories?**apikey**=your API key
Good luck. | For me, it worked with by using headers instead of header function call.
```
RequestSpecification requestSpec=RestAssured.given().headers("Content-Type","application/json","user-key",<api-key>);
``` |
12,026,668 | I initially wrote this (brute force and inefficient) method of calculating primes with the intent of making sure that there was no difference in speed between using "if-then-else" versus guards in Haskell (and there is no difference!). But then I decided to write a C program to compare and I got the following (Haskell slower by just over 25%) :
(Note I got the ideas of using rem instead of mod and also the O3 option in the compiler invocation from the following post : [On improving Haskell's performance compared to C in fibonacci micro-benchmark](https://stackoverflow.com/questions/6716315/on-improving-haskells-performance-compared-to-c-in-fibonacci-micro-benchmark))
***Haskell : Forum.hs***
```
divisibleRec :: Int -> Int -> Bool
divisibleRec i j
| j == 1 = False
| i `rem` j == 0 = True
| otherwise = divisibleRec i (j-1)
divisible::Int -> Bool
divisible i = divisibleRec i (i-1)
r = [ x | x <- [2..200000], divisible x == False]
main :: IO()
main = print(length(r))
```
***C : main.cpp***
```
#include <stdio.h>
bool divisibleRec(int i, int j){
if(j==1){ return false; }
else if(i%j==0){ return true; }
else{ return divisibleRec(i,j-1); }
}
bool divisible(int i){ return divisibleRec(i, i-1); }
int main(void){
int i, count =0;
for(i=2; i<200000; ++i){
if(divisible(i)==false){
count = count+1;
}
}
printf("number of primes = %d\n",count);
return 0;
}
```
The results I got were as follows :
***Compilation times***
```
time (ghc -O3 -o runProg Forum.hs)
real 0m0.355s
user 0m0.252s
sys 0m0.040s
time (gcc -O3 -o runProg main.cpp)
real 0m0.070s
user 0m0.036s
sys 0m0.008s
```
and the following running times :
***Running times on Ubuntu 32 bit***
```
Haskell
17984
real 0m54.498s
user 0m51.363s
sys 0m0.140s
C++
number of primes = 17984
real 0m41.739s
user 0m39.642s
sys 0m0.080s
```
I was quite impressed with the running times of Haskell. However my question is this : can I do anything to speed up the haskell program without :
1. Changing the underlying algorithm (it is clear that massive speedups can be gained by changing the algorithm; but I just want to understand what I can do on the language/compiler side to improve performance)
2. Invoking the llvm compiler (because I dont have this installed)
***[EDIT : Memory usage]***
After a comment by Alan I noticed that the C program uses a constant amount of memory where as the Haskell program slowly grows in memory size. At first I thought this had something to do with recursion, but gspr explains below why this is happening and provides a solution. Will Ness provides an alternative solution which (like gspr's solution) also ensures that the memory remains static.
***[EDIT : Summary of bigger runs]***
max number tested : 200,000:
(54.498s/41.739s) = ***Haskell 30.5% slower***
max number tested : 400,000:
3m31.372s/2m45.076s = 211.37s/165s = ***Haskell 28.1% slower***
max number tested : 800,000:
14m3.266s/11m6.024s = 843.27s/666.02s = ***Haskell 26.6% slower***
***[EDIT : Code for Alan]***
This was the code that I had written earlier which does not have recursion and which I had tested on 200,000 :
```
#include <stdio.h>
bool divisibleRec(int i, int j){
while(j>0){
if(j==1){ return false; }
else if(i%j==0){ return true; }
else{ j -= 1;}
}
}
bool divisible(int i){ return divisibleRec(i, i-1); }
int main(void){
int i, count =0;
for(i=2; i<8000000; ++i){
if(divisible(i)==false){
count = count+1;
}
}
printf("number of primes = %d\n",count);
return 0;
}
```
The results for the C code with and without recursion are as follows (for 800,000) :
With recursion : 11m6.024s
Without recursion : 11m5.328s
Note that the executable seems to take up 60kb (as seen in System monitor) irrespective of the maximum number, and therefore I suspect that the compiler is detecting this recursion. | 2012/08/19 | [
"https://Stackoverflow.com/questions/12026668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/917635/"
] | Another way to write down your algorithm is
```
main = print $ length [()|x<-[2..200000], and [rem x d>0|d<-[x-1,x-2..2]]]
```
Unfortunately, it runs slower. Using `all ((>0).rem x) [x-1,x-2..2]` as a test, it runs slower still. But maybe you'd test it on your setup nevertheless.
Replacing your code with explicit loop with bang patterns made no difference whatsoever:
```
{-# OPTIONS_GHC -XBangPatterns #-}
r4::Int->Int
r4 n = go 0 2 where
go !c i | i>n = c
| True = go (if not(divisible i) then (c+1) else c) (i+1)
divisibleRec::Int->Int->Bool
divisibleRec i !j | j == 1 = False
| i `rem` j == 0 = True
| otherwise = divisibleRec i (j-1)
``` | When I started programming in Haskell I was also impressed about its speed. You may be interested in reading point 5 "The speed of Haskell" of this [article](http://www.haskell.org/haskellwiki/Why_Haskell_matters#The_speed_of_Haskell). |
12,026,668 | I initially wrote this (brute force and inefficient) method of calculating primes with the intent of making sure that there was no difference in speed between using "if-then-else" versus guards in Haskell (and there is no difference!). But then I decided to write a C program to compare and I got the following (Haskell slower by just over 25%) :
(Note I got the ideas of using rem instead of mod and also the O3 option in the compiler invocation from the following post : [On improving Haskell's performance compared to C in fibonacci micro-benchmark](https://stackoverflow.com/questions/6716315/on-improving-haskells-performance-compared-to-c-in-fibonacci-micro-benchmark))
***Haskell : Forum.hs***
```
divisibleRec :: Int -> Int -> Bool
divisibleRec i j
| j == 1 = False
| i `rem` j == 0 = True
| otherwise = divisibleRec i (j-1)
divisible::Int -> Bool
divisible i = divisibleRec i (i-1)
r = [ x | x <- [2..200000], divisible x == False]
main :: IO()
main = print(length(r))
```
***C : main.cpp***
```
#include <stdio.h>
bool divisibleRec(int i, int j){
if(j==1){ return false; }
else if(i%j==0){ return true; }
else{ return divisibleRec(i,j-1); }
}
bool divisible(int i){ return divisibleRec(i, i-1); }
int main(void){
int i, count =0;
for(i=2; i<200000; ++i){
if(divisible(i)==false){
count = count+1;
}
}
printf("number of primes = %d\n",count);
return 0;
}
```
The results I got were as follows :
***Compilation times***
```
time (ghc -O3 -o runProg Forum.hs)
real 0m0.355s
user 0m0.252s
sys 0m0.040s
time (gcc -O3 -o runProg main.cpp)
real 0m0.070s
user 0m0.036s
sys 0m0.008s
```
and the following running times :
***Running times on Ubuntu 32 bit***
```
Haskell
17984
real 0m54.498s
user 0m51.363s
sys 0m0.140s
C++
number of primes = 17984
real 0m41.739s
user 0m39.642s
sys 0m0.080s
```
I was quite impressed with the running times of Haskell. However my question is this : can I do anything to speed up the haskell program without :
1. Changing the underlying algorithm (it is clear that massive speedups can be gained by changing the algorithm; but I just want to understand what I can do on the language/compiler side to improve performance)
2. Invoking the llvm compiler (because I dont have this installed)
***[EDIT : Memory usage]***
After a comment by Alan I noticed that the C program uses a constant amount of memory where as the Haskell program slowly grows in memory size. At first I thought this had something to do with recursion, but gspr explains below why this is happening and provides a solution. Will Ness provides an alternative solution which (like gspr's solution) also ensures that the memory remains static.
***[EDIT : Summary of bigger runs]***
max number tested : 200,000:
(54.498s/41.739s) = ***Haskell 30.5% slower***
max number tested : 400,000:
3m31.372s/2m45.076s = 211.37s/165s = ***Haskell 28.1% slower***
max number tested : 800,000:
14m3.266s/11m6.024s = 843.27s/666.02s = ***Haskell 26.6% slower***
***[EDIT : Code for Alan]***
This was the code that I had written earlier which does not have recursion and which I had tested on 200,000 :
```
#include <stdio.h>
bool divisibleRec(int i, int j){
while(j>0){
if(j==1){ return false; }
else if(i%j==0){ return true; }
else{ j -= 1;}
}
}
bool divisible(int i){ return divisibleRec(i, i-1); }
int main(void){
int i, count =0;
for(i=2; i<8000000; ++i){
if(divisible(i)==false){
count = count+1;
}
}
printf("number of primes = %d\n",count);
return 0;
}
```
The results for the C code with and without recursion are as follows (for 800,000) :
With recursion : 11m6.024s
Without recursion : 11m5.328s
Note that the executable seems to take up 60kb (as seen in System monitor) irrespective of the maximum number, and therefore I suspect that the compiler is detecting this recursion. | 2012/08/19 | [
"https://Stackoverflow.com/questions/12026668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/917635/"
] | Well bang patters give you a very small win (as does llvm, but you seem to have expected that):
```
{-# LANUGAGE BangPatterns #-}
divisibleRec !i !j | j == 1 = False
```
And on my x86-64 I get a very big win by switching to smaller representations, such as Word32:
```
divisibleRec :: Word32 -> Word32 -> Bool
...
divisible :: Word32 -> Bool
```
My timings:
```
$ time ./so -- Int
2262
real 0m2.332s
$ time ./so -- Word32
2262
real 0m1.424s
```
This is a closer match to your C program, which is only using `int`. It still doesn't match performance wise, I suspect we'd have to look at core to figure out why.
EDIT: and the memory use, as was already noted I see, is about the named list `r`. I just inlined `r`, made it output a `1` for each non-divisble value and took the sum:
```
main = print $ sum $ [ 1 | x <- [2..800000], not (divisible x) ]
``` | Another way to write down your algorithm is
```
main = print $ length [()|x<-[2..200000], and [rem x d>0|d<-[x-1,x-2..2]]]
```
Unfortunately, it runs slower. Using `all ((>0).rem x) [x-1,x-2..2]` as a test, it runs slower still. But maybe you'd test it on your setup nevertheless.
Replacing your code with explicit loop with bang patterns made no difference whatsoever:
```
{-# OPTIONS_GHC -XBangPatterns #-}
r4::Int->Int
r4 n = go 0 2 where
go !c i | i>n = c
| True = go (if not(divisible i) then (c+1) else c) (i+1)
divisibleRec::Int->Int->Bool
divisibleRec i !j | j == 1 = False
| i `rem` j == 0 = True
| otherwise = divisibleRec i (j-1)
``` |
12,026,668 | I initially wrote this (brute force and inefficient) method of calculating primes with the intent of making sure that there was no difference in speed between using "if-then-else" versus guards in Haskell (and there is no difference!). But then I decided to write a C program to compare and I got the following (Haskell slower by just over 25%) :
(Note I got the ideas of using rem instead of mod and also the O3 option in the compiler invocation from the following post : [On improving Haskell's performance compared to C in fibonacci micro-benchmark](https://stackoverflow.com/questions/6716315/on-improving-haskells-performance-compared-to-c-in-fibonacci-micro-benchmark))
***Haskell : Forum.hs***
```
divisibleRec :: Int -> Int -> Bool
divisibleRec i j
| j == 1 = False
| i `rem` j == 0 = True
| otherwise = divisibleRec i (j-1)
divisible::Int -> Bool
divisible i = divisibleRec i (i-1)
r = [ x | x <- [2..200000], divisible x == False]
main :: IO()
main = print(length(r))
```
***C : main.cpp***
```
#include <stdio.h>
bool divisibleRec(int i, int j){
if(j==1){ return false; }
else if(i%j==0){ return true; }
else{ return divisibleRec(i,j-1); }
}
bool divisible(int i){ return divisibleRec(i, i-1); }
int main(void){
int i, count =0;
for(i=2; i<200000; ++i){
if(divisible(i)==false){
count = count+1;
}
}
printf("number of primes = %d\n",count);
return 0;
}
```
The results I got were as follows :
***Compilation times***
```
time (ghc -O3 -o runProg Forum.hs)
real 0m0.355s
user 0m0.252s
sys 0m0.040s
time (gcc -O3 -o runProg main.cpp)
real 0m0.070s
user 0m0.036s
sys 0m0.008s
```
and the following running times :
***Running times on Ubuntu 32 bit***
```
Haskell
17984
real 0m54.498s
user 0m51.363s
sys 0m0.140s
C++
number of primes = 17984
real 0m41.739s
user 0m39.642s
sys 0m0.080s
```
I was quite impressed with the running times of Haskell. However my question is this : can I do anything to speed up the haskell program without :
1. Changing the underlying algorithm (it is clear that massive speedups can be gained by changing the algorithm; but I just want to understand what I can do on the language/compiler side to improve performance)
2. Invoking the llvm compiler (because I dont have this installed)
***[EDIT : Memory usage]***
After a comment by Alan I noticed that the C program uses a constant amount of memory where as the Haskell program slowly grows in memory size. At first I thought this had something to do with recursion, but gspr explains below why this is happening and provides a solution. Will Ness provides an alternative solution which (like gspr's solution) also ensures that the memory remains static.
***[EDIT : Summary of bigger runs]***
max number tested : 200,000:
(54.498s/41.739s) = ***Haskell 30.5% slower***
max number tested : 400,000:
3m31.372s/2m45.076s = 211.37s/165s = ***Haskell 28.1% slower***
max number tested : 800,000:
14m3.266s/11m6.024s = 843.27s/666.02s = ***Haskell 26.6% slower***
***[EDIT : Code for Alan]***
This was the code that I had written earlier which does not have recursion and which I had tested on 200,000 :
```
#include <stdio.h>
bool divisibleRec(int i, int j){
while(j>0){
if(j==1){ return false; }
else if(i%j==0){ return true; }
else{ j -= 1;}
}
}
bool divisible(int i){ return divisibleRec(i, i-1); }
int main(void){
int i, count =0;
for(i=2; i<8000000; ++i){
if(divisible(i)==false){
count = count+1;
}
}
printf("number of primes = %d\n",count);
return 0;
}
```
The results for the C code with and without recursion are as follows (for 800,000) :
With recursion : 11m6.024s
Without recursion : 11m5.328s
Note that the executable seems to take up 60kb (as seen in System monitor) irrespective of the maximum number, and therefore I suspect that the compiler is detecting this recursion. | 2012/08/19 | [
"https://Stackoverflow.com/questions/12026668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/917635/"
] | This isn't really answering your question, but rather what you asked in a comment regarding growing memory usage when the number 200000 grows.
When that number grows, so does the list `r`. Your code needs all of `r` at the very end, to compute its length. The C code, on the other hand, just increments a counter. You'll have to do something similar in Haskell too if you want constant memory usage. The code will still be very Haskelly, and in general it's a sensible proposition: you don't really need the list of numbers for which `divisible` is `False`, you just need to know how many there are.
You can try with
```
main :: IO ()
main = print $ foldl' (\s x -> if divisible x then s else s+1) 0 [2..200000]
```
(`foldl'` is a stricter `foldl` from `Data.List` that avoids thunks being built up). | Another way to write down your algorithm is
```
main = print $ length [()|x<-[2..200000], and [rem x d>0|d<-[x-1,x-2..2]]]
```
Unfortunately, it runs slower. Using `all ((>0).rem x) [x-1,x-2..2]` as a test, it runs slower still. But maybe you'd test it on your setup nevertheless.
Replacing your code with explicit loop with bang patterns made no difference whatsoever:
```
{-# OPTIONS_GHC -XBangPatterns #-}
r4::Int->Int
r4 n = go 0 2 where
go !c i | i>n = c
| True = go (if not(divisible i) then (c+1) else c) (i+1)
divisibleRec::Int->Int->Bool
divisibleRec i !j | j == 1 = False
| i `rem` j == 0 = True
| otherwise = divisibleRec i (j-1)
``` |
12,026,668 | I initially wrote this (brute force and inefficient) method of calculating primes with the intent of making sure that there was no difference in speed between using "if-then-else" versus guards in Haskell (and there is no difference!). But then I decided to write a C program to compare and I got the following (Haskell slower by just over 25%) :
(Note I got the ideas of using rem instead of mod and also the O3 option in the compiler invocation from the following post : [On improving Haskell's performance compared to C in fibonacci micro-benchmark](https://stackoverflow.com/questions/6716315/on-improving-haskells-performance-compared-to-c-in-fibonacci-micro-benchmark))
***Haskell : Forum.hs***
```
divisibleRec :: Int -> Int -> Bool
divisibleRec i j
| j == 1 = False
| i `rem` j == 0 = True
| otherwise = divisibleRec i (j-1)
divisible::Int -> Bool
divisible i = divisibleRec i (i-1)
r = [ x | x <- [2..200000], divisible x == False]
main :: IO()
main = print(length(r))
```
***C : main.cpp***
```
#include <stdio.h>
bool divisibleRec(int i, int j){
if(j==1){ return false; }
else if(i%j==0){ return true; }
else{ return divisibleRec(i,j-1); }
}
bool divisible(int i){ return divisibleRec(i, i-1); }
int main(void){
int i, count =0;
for(i=2; i<200000; ++i){
if(divisible(i)==false){
count = count+1;
}
}
printf("number of primes = %d\n",count);
return 0;
}
```
The results I got were as follows :
***Compilation times***
```
time (ghc -O3 -o runProg Forum.hs)
real 0m0.355s
user 0m0.252s
sys 0m0.040s
time (gcc -O3 -o runProg main.cpp)
real 0m0.070s
user 0m0.036s
sys 0m0.008s
```
and the following running times :
***Running times on Ubuntu 32 bit***
```
Haskell
17984
real 0m54.498s
user 0m51.363s
sys 0m0.140s
C++
number of primes = 17984
real 0m41.739s
user 0m39.642s
sys 0m0.080s
```
I was quite impressed with the running times of Haskell. However my question is this : can I do anything to speed up the haskell program without :
1. Changing the underlying algorithm (it is clear that massive speedups can be gained by changing the algorithm; but I just want to understand what I can do on the language/compiler side to improve performance)
2. Invoking the llvm compiler (because I dont have this installed)
***[EDIT : Memory usage]***
After a comment by Alan I noticed that the C program uses a constant amount of memory where as the Haskell program slowly grows in memory size. At first I thought this had something to do with recursion, but gspr explains below why this is happening and provides a solution. Will Ness provides an alternative solution which (like gspr's solution) also ensures that the memory remains static.
***[EDIT : Summary of bigger runs]***
max number tested : 200,000:
(54.498s/41.739s) = ***Haskell 30.5% slower***
max number tested : 400,000:
3m31.372s/2m45.076s = 211.37s/165s = ***Haskell 28.1% slower***
max number tested : 800,000:
14m3.266s/11m6.024s = 843.27s/666.02s = ***Haskell 26.6% slower***
***[EDIT : Code for Alan]***
This was the code that I had written earlier which does not have recursion and which I had tested on 200,000 :
```
#include <stdio.h>
bool divisibleRec(int i, int j){
while(j>0){
if(j==1){ return false; }
else if(i%j==0){ return true; }
else{ j -= 1;}
}
}
bool divisible(int i){ return divisibleRec(i, i-1); }
int main(void){
int i, count =0;
for(i=2; i<8000000; ++i){
if(divisible(i)==false){
count = count+1;
}
}
printf("number of primes = %d\n",count);
return 0;
}
```
The results for the C code with and without recursion are as follows (for 800,000) :
With recursion : 11m6.024s
Without recursion : 11m5.328s
Note that the executable seems to take up 60kb (as seen in System monitor) irrespective of the maximum number, and therefore I suspect that the compiler is detecting this recursion. | 2012/08/19 | [
"https://Stackoverflow.com/questions/12026668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/917635/"
] | Well bang patters give you a very small win (as does llvm, but you seem to have expected that):
```
{-# LANUGAGE BangPatterns #-}
divisibleRec !i !j | j == 1 = False
```
And on my x86-64 I get a very big win by switching to smaller representations, such as Word32:
```
divisibleRec :: Word32 -> Word32 -> Bool
...
divisible :: Word32 -> Bool
```
My timings:
```
$ time ./so -- Int
2262
real 0m2.332s
$ time ./so -- Word32
2262
real 0m1.424s
```
This is a closer match to your C program, which is only using `int`. It still doesn't match performance wise, I suspect we'd have to look at core to figure out why.
EDIT: and the memory use, as was already noted I see, is about the named list `r`. I just inlined `r`, made it output a `1` for each non-divisble value and took the sum:
```
main = print $ sum $ [ 1 | x <- [2..800000], not (divisible x) ]
``` | When I started programming in Haskell I was also impressed about its speed. You may be interested in reading point 5 "The speed of Haskell" of this [article](http://www.haskell.org/haskellwiki/Why_Haskell_matters#The_speed_of_Haskell). |
12,026,668 | I initially wrote this (brute force and inefficient) method of calculating primes with the intent of making sure that there was no difference in speed between using "if-then-else" versus guards in Haskell (and there is no difference!). But then I decided to write a C program to compare and I got the following (Haskell slower by just over 25%) :
(Note I got the ideas of using rem instead of mod and also the O3 option in the compiler invocation from the following post : [On improving Haskell's performance compared to C in fibonacci micro-benchmark](https://stackoverflow.com/questions/6716315/on-improving-haskells-performance-compared-to-c-in-fibonacci-micro-benchmark))
***Haskell : Forum.hs***
```
divisibleRec :: Int -> Int -> Bool
divisibleRec i j
| j == 1 = False
| i `rem` j == 0 = True
| otherwise = divisibleRec i (j-1)
divisible::Int -> Bool
divisible i = divisibleRec i (i-1)
r = [ x | x <- [2..200000], divisible x == False]
main :: IO()
main = print(length(r))
```
***C : main.cpp***
```
#include <stdio.h>
bool divisibleRec(int i, int j){
if(j==1){ return false; }
else if(i%j==0){ return true; }
else{ return divisibleRec(i,j-1); }
}
bool divisible(int i){ return divisibleRec(i, i-1); }
int main(void){
int i, count =0;
for(i=2; i<200000; ++i){
if(divisible(i)==false){
count = count+1;
}
}
printf("number of primes = %d\n",count);
return 0;
}
```
The results I got were as follows :
***Compilation times***
```
time (ghc -O3 -o runProg Forum.hs)
real 0m0.355s
user 0m0.252s
sys 0m0.040s
time (gcc -O3 -o runProg main.cpp)
real 0m0.070s
user 0m0.036s
sys 0m0.008s
```
and the following running times :
***Running times on Ubuntu 32 bit***
```
Haskell
17984
real 0m54.498s
user 0m51.363s
sys 0m0.140s
C++
number of primes = 17984
real 0m41.739s
user 0m39.642s
sys 0m0.080s
```
I was quite impressed with the running times of Haskell. However my question is this : can I do anything to speed up the haskell program without :
1. Changing the underlying algorithm (it is clear that massive speedups can be gained by changing the algorithm; but I just want to understand what I can do on the language/compiler side to improve performance)
2. Invoking the llvm compiler (because I dont have this installed)
***[EDIT : Memory usage]***
After a comment by Alan I noticed that the C program uses a constant amount of memory where as the Haskell program slowly grows in memory size. At first I thought this had something to do with recursion, but gspr explains below why this is happening and provides a solution. Will Ness provides an alternative solution which (like gspr's solution) also ensures that the memory remains static.
***[EDIT : Summary of bigger runs]***
max number tested : 200,000:
(54.498s/41.739s) = ***Haskell 30.5% slower***
max number tested : 400,000:
3m31.372s/2m45.076s = 211.37s/165s = ***Haskell 28.1% slower***
max number tested : 800,000:
14m3.266s/11m6.024s = 843.27s/666.02s = ***Haskell 26.6% slower***
***[EDIT : Code for Alan]***
This was the code that I had written earlier which does not have recursion and which I had tested on 200,000 :
```
#include <stdio.h>
bool divisibleRec(int i, int j){
while(j>0){
if(j==1){ return false; }
else if(i%j==0){ return true; }
else{ j -= 1;}
}
}
bool divisible(int i){ return divisibleRec(i, i-1); }
int main(void){
int i, count =0;
for(i=2; i<8000000; ++i){
if(divisible(i)==false){
count = count+1;
}
}
printf("number of primes = %d\n",count);
return 0;
}
```
The results for the C code with and without recursion are as follows (for 800,000) :
With recursion : 11m6.024s
Without recursion : 11m5.328s
Note that the executable seems to take up 60kb (as seen in System monitor) irrespective of the maximum number, and therefore I suspect that the compiler is detecting this recursion. | 2012/08/19 | [
"https://Stackoverflow.com/questions/12026668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/917635/"
] | This isn't really answering your question, but rather what you asked in a comment regarding growing memory usage when the number 200000 grows.
When that number grows, so does the list `r`. Your code needs all of `r` at the very end, to compute its length. The C code, on the other hand, just increments a counter. You'll have to do something similar in Haskell too if you want constant memory usage. The code will still be very Haskelly, and in general it's a sensible proposition: you don't really need the list of numbers for which `divisible` is `False`, you just need to know how many there are.
You can try with
```
main :: IO ()
main = print $ foldl' (\s x -> if divisible x then s else s+1) 0 [2..200000]
```
(`foldl'` is a stricter `foldl` from `Data.List` that avoids thunks being built up). | When I started programming in Haskell I was also impressed about its speed. You may be interested in reading point 5 "The speed of Haskell" of this [article](http://www.haskell.org/haskellwiki/Why_Haskell_matters#The_speed_of_Haskell). |
12,026,668 | I initially wrote this (brute force and inefficient) method of calculating primes with the intent of making sure that there was no difference in speed between using "if-then-else" versus guards in Haskell (and there is no difference!). But then I decided to write a C program to compare and I got the following (Haskell slower by just over 25%) :
(Note I got the ideas of using rem instead of mod and also the O3 option in the compiler invocation from the following post : [On improving Haskell's performance compared to C in fibonacci micro-benchmark](https://stackoverflow.com/questions/6716315/on-improving-haskells-performance-compared-to-c-in-fibonacci-micro-benchmark))
***Haskell : Forum.hs***
```
divisibleRec :: Int -> Int -> Bool
divisibleRec i j
| j == 1 = False
| i `rem` j == 0 = True
| otherwise = divisibleRec i (j-1)
divisible::Int -> Bool
divisible i = divisibleRec i (i-1)
r = [ x | x <- [2..200000], divisible x == False]
main :: IO()
main = print(length(r))
```
***C : main.cpp***
```
#include <stdio.h>
bool divisibleRec(int i, int j){
if(j==1){ return false; }
else if(i%j==0){ return true; }
else{ return divisibleRec(i,j-1); }
}
bool divisible(int i){ return divisibleRec(i, i-1); }
int main(void){
int i, count =0;
for(i=2; i<200000; ++i){
if(divisible(i)==false){
count = count+1;
}
}
printf("number of primes = %d\n",count);
return 0;
}
```
The results I got were as follows :
***Compilation times***
```
time (ghc -O3 -o runProg Forum.hs)
real 0m0.355s
user 0m0.252s
sys 0m0.040s
time (gcc -O3 -o runProg main.cpp)
real 0m0.070s
user 0m0.036s
sys 0m0.008s
```
and the following running times :
***Running times on Ubuntu 32 bit***
```
Haskell
17984
real 0m54.498s
user 0m51.363s
sys 0m0.140s
C++
number of primes = 17984
real 0m41.739s
user 0m39.642s
sys 0m0.080s
```
I was quite impressed with the running times of Haskell. However my question is this : can I do anything to speed up the haskell program without :
1. Changing the underlying algorithm (it is clear that massive speedups can be gained by changing the algorithm; but I just want to understand what I can do on the language/compiler side to improve performance)
2. Invoking the llvm compiler (because I dont have this installed)
***[EDIT : Memory usage]***
After a comment by Alan I noticed that the C program uses a constant amount of memory where as the Haskell program slowly grows in memory size. At first I thought this had something to do with recursion, but gspr explains below why this is happening and provides a solution. Will Ness provides an alternative solution which (like gspr's solution) also ensures that the memory remains static.
***[EDIT : Summary of bigger runs]***
max number tested : 200,000:
(54.498s/41.739s) = ***Haskell 30.5% slower***
max number tested : 400,000:
3m31.372s/2m45.076s = 211.37s/165s = ***Haskell 28.1% slower***
max number tested : 800,000:
14m3.266s/11m6.024s = 843.27s/666.02s = ***Haskell 26.6% slower***
***[EDIT : Code for Alan]***
This was the code that I had written earlier which does not have recursion and which I had tested on 200,000 :
```
#include <stdio.h>
bool divisibleRec(int i, int j){
while(j>0){
if(j==1){ return false; }
else if(i%j==0){ return true; }
else{ j -= 1;}
}
}
bool divisible(int i){ return divisibleRec(i, i-1); }
int main(void){
int i, count =0;
for(i=2; i<8000000; ++i){
if(divisible(i)==false){
count = count+1;
}
}
printf("number of primes = %d\n",count);
return 0;
}
```
The results for the C code with and without recursion are as follows (for 800,000) :
With recursion : 11m6.024s
Without recursion : 11m5.328s
Note that the executable seems to take up 60kb (as seen in System monitor) irrespective of the maximum number, and therefore I suspect that the compiler is detecting this recursion. | 2012/08/19 | [
"https://Stackoverflow.com/questions/12026668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/917635/"
] | This isn't really answering your question, but rather what you asked in a comment regarding growing memory usage when the number 200000 grows.
When that number grows, so does the list `r`. Your code needs all of `r` at the very end, to compute its length. The C code, on the other hand, just increments a counter. You'll have to do something similar in Haskell too if you want constant memory usage. The code will still be very Haskelly, and in general it's a sensible proposition: you don't really need the list of numbers for which `divisible` is `False`, you just need to know how many there are.
You can try with
```
main :: IO ()
main = print $ foldl' (\s x -> if divisible x then s else s+1) 0 [2..200000]
```
(`foldl'` is a stricter `foldl` from `Data.List` that avoids thunks being built up). | Well bang patters give you a very small win (as does llvm, but you seem to have expected that):
```
{-# LANUGAGE BangPatterns #-}
divisibleRec !i !j | j == 1 = False
```
And on my x86-64 I get a very big win by switching to smaller representations, such as Word32:
```
divisibleRec :: Word32 -> Word32 -> Bool
...
divisible :: Word32 -> Bool
```
My timings:
```
$ time ./so -- Int
2262
real 0m2.332s
$ time ./so -- Word32
2262
real 0m1.424s
```
This is a closer match to your C program, which is only using `int`. It still doesn't match performance wise, I suspect we'd have to look at core to figure out why.
EDIT: and the memory use, as was already noted I see, is about the named list `r`. I just inlined `r`, made it output a `1` for each non-divisble value and took the sum:
```
main = print $ sum $ [ 1 | x <- [2..800000], not (divisible x) ]
``` |
2,005,649 | I am struggling to find a parameterization for the following set :
$$F=\left\{(x,y,z)\in\mathbb R^3\middle| \left(\sqrt{x^2+y^2}-R\right)^2 + z^2 = r^2\right\}
\quad\text{with }R>r$$
I also have to calculate the area.
I know its a circle so we express it in terms of the angle but my problem is with the $x$ and $y$ . They are not defined uniquely by the angle.
Please explain with details because it is more important for me to understand than the answer itself | 2016/11/08 | [
"https://math.stackexchange.com/questions/2005649",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/301826/"
] | I think it is a bit easier than what you did if you handle $D$ more freely.
1. Take all combinations: $(A+B+C+D)^8$
2. Exclude combinations that do not have (at least) one of $A, B, C$ = $ (B+C+D)^8 + (A+C+D)^8 + (A+B+D)^8$
3. Include combinations that do not have (at least) two of $A, B, C$ = $ (C+D)^8 + (B+D)^8 + (A+D)^8$
4. Exclude combinations that do not have three of $A, B, C$ = $ D^8$
The inclusion/exclusion principle lies in the fact that if you exclude and item because it does not have an $A$, but it also does not have a $B$, you have to include it again. | Here's a somewhat simpler approach. We need to use 1 uppercase, 1 digit and 1 special character. There are $26\cdot 10\cdot 16$ ways to choose which 3 symbols we want to use. Then we have to choose a spot for them in the password. There are 8 possible spots for the uppercase, 7 for the digit and 6 for the special character. So far we have
$$26\cdot 10\cdot 16\cdot (8\cdot 7\cdot 6)$$
different ways of choosing these things. Now the other 5 symbols are completely free, they can be anything. There is a total of $26+26+10+16=78$ symbols, so we can choose these 5 symbols in $78^5$ ways. The answer is then
$$26\cdot 10\cdot 16\cdot (8\cdot 7\cdot 6)\cdot 78^5\simeq 4,03\cdot 10^{15}$$ |
2,005,649 | I am struggling to find a parameterization for the following set :
$$F=\left\{(x,y,z)\in\mathbb R^3\middle| \left(\sqrt{x^2+y^2}-R\right)^2 + z^2 = r^2\right\}
\quad\text{with }R>r$$
I also have to calculate the area.
I know its a circle so we express it in terms of the angle but my problem is with the $x$ and $y$ . They are not defined uniquely by the angle.
Please explain with details because it is more important for me to understand than the answer itself | 2016/11/08 | [
"https://math.stackexchange.com/questions/2005649",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/301826/"
] | Starting from a similar point as you, but with slightly different logic from there, I got...
$$78^8-68^8-52^8-62^8+42^8+52^8+36^8-26^8 = 706905960284160 \approx 7.07E14$$
I started with the total number of possibilities.
$$78^8$$
Then, I subtracted all possibilities without a digit, without an upper case, and without a special, respectively.
$$-68^8-52^8-62^8$$
Then, using inclusion-exclusion, I added back in all the possibilities having no digits or upper cases, no digits or specials, and no upper cases or specials.
$$+42^8+52^8+36^8$$
Finally, once again because of inclusion-exclusion, I subtracted the number of possibilities that have no digits no upper cases and no specials.
$$-26^8$$ | Here's a somewhat simpler approach. We need to use 1 uppercase, 1 digit and 1 special character. There are $26\cdot 10\cdot 16$ ways to choose which 3 symbols we want to use. Then we have to choose a spot for them in the password. There are 8 possible spots for the uppercase, 7 for the digit and 6 for the special character. So far we have
$$26\cdot 10\cdot 16\cdot (8\cdot 7\cdot 6)$$
different ways of choosing these things. Now the other 5 symbols are completely free, they can be anything. There is a total of $26+26+10+16=78$ symbols, so we can choose these 5 symbols in $78^5$ ways. The answer is then
$$26\cdot 10\cdot 16\cdot (8\cdot 7\cdot 6)\cdot 78^5\simeq 4,03\cdot 10^{15}$$ |
2,005,649 | I am struggling to find a parameterization for the following set :
$$F=\left\{(x,y,z)\in\mathbb R^3\middle| \left(\sqrt{x^2+y^2}-R\right)^2 + z^2 = r^2\right\}
\quad\text{with }R>r$$
I also have to calculate the area.
I know its a circle so we express it in terms of the angle but my problem is with the $x$ and $y$ . They are not defined uniquely by the angle.
Please explain with details because it is more important for me to understand than the answer itself | 2016/11/08 | [
"https://math.stackexchange.com/questions/2005649",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/301826/"
] | Starting from a similar point as you, but with slightly different logic from there, I got...
$$78^8-68^8-52^8-62^8+42^8+52^8+36^8-26^8 = 706905960284160 \approx 7.07E14$$
I started with the total number of possibilities.
$$78^8$$
Then, I subtracted all possibilities without a digit, without an upper case, and without a special, respectively.
$$-68^8-52^8-62^8$$
Then, using inclusion-exclusion, I added back in all the possibilities having no digits or upper cases, no digits or specials, and no upper cases or specials.
$$+42^8+52^8+36^8$$
Finally, once again because of inclusion-exclusion, I subtracted the number of possibilities that have no digits no upper cases and no specials.
$$-26^8$$ | I think it is a bit easier than what you did if you handle $D$ more freely.
1. Take all combinations: $(A+B+C+D)^8$
2. Exclude combinations that do not have (at least) one of $A, B, C$ = $ (B+C+D)^8 + (A+C+D)^8 + (A+B+D)^8$
3. Include combinations that do not have (at least) two of $A, B, C$ = $ (C+D)^8 + (B+D)^8 + (A+D)^8$
4. Exclude combinations that do not have three of $A, B, C$ = $ D^8$
The inclusion/exclusion principle lies in the fact that if you exclude and item because it does not have an $A$, but it also does not have a $B$, you have to include it again. |
5,213,105 | I know that there are hundreds of pages written on Django v Rails, but I've been searching for a few days trying to get opinions on a few more subtle points in the debate with no luck, so I thought I'd ask here. I have almost no experience with either framework, but am currently leaning towards Django because of its documentation, speed, and my love for python.
* Which one is better for quick and maintainable development of complex webapps? I'm not talking about a 'plane-jane' website, but a complicated desktop application-esque webapp. I hear that Python is more performant than Ruby and I also hear that the learning curve in Rails is such that I'll spend a lot of later hours refactoring out newbie mistakes after the webapp progresses beyond simple CRUD. This could be combatted by hiring experienced Rails developers, however.
* Is there a perception that Rails apps are often more beautiful than Django apps? I know that whether an application is beautiful is not dependent on the framework behind it (case in point mint.com), but this is just a feeling I get and I was wondering if there was any validity to it.
* Is one easier to deploy than the other? I've deployed a few Rails apps on Apache with some trouble, but never tried to deploy a Django app. I've been thinking about providing potential users with a downloadable executable that would set up a small webserver and deploy the app locally so that they could test it on their own machine before deploying it on their servers - are there tools that make that easier with either framework?
* Which has better database libraries/ORM? I know that things are pretty simple if I go the NoSQL route, but if I decide to use a relational database, is one framework better than the other? | 2011/03/06 | [
"https://Stackoverflow.com/questions/5213105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/291736/"
] | I'm going to warn you up-front that I'm a Django developer that keeps modest tabs on Rails' development and I've never had to develop or maintain a complex Rails application, so I'm going to focus on the strengths of Django and what I know about Rails' design philosophy, so I welcome experienced Rails users to challenge and correct any wrong assumptions I'm about to make.
### Which one is better for quick and maintainable development of complex webapps?
Django has a fantastic layer of modularization that is implemented through Django apps. Your project is nothing more than a Django instance composed of a root URL configuration and a settings file, that serve the main purpose of hooking Django apps into your instance.
Django apps themselves are Python packages, that are by Django's design, meant to be packaged for distribution completely independent of a Django instance and that was initially why I picked up Django. They encapsulate all of the discrete components (models, templates, URL patterns, views, forms, etc.) necessary for providing a certain feature (this app supports user registration; that app provides user authentication; this one is for managing user profiles; this one servers static pages dynamically from the database; this app can take any image, convert it to an RGB JPEG, resize it and upload it to a local path, S3 or to some FTP server) and your encouraged to have a lot of different Django applications to simplify your application structure.
To put it bluntly, in Rails it would be as if your application is solely composed of separate Rails plugins. The Rails architecture encourages people to have a huge `app/` structure, where all of the components for a feature are kept separate and collocated together with similar components from other features, and distribute 3rd party code together with their Rails application in `vendors/`, whereas Django enforces Django apps to be shoulder-to-shoulder top-level packages, be they your instance specific apps or 3rd party apps, that can be independently redistributed and reused across several Django instances in the same environment, wholly encapsulating data fixtures, their own templates, static media, translations, test code, models, views and controllers and their intermediary components.
For instance, take a look at the repository of these two big projects, [Zamboni](https://github.com/mozilla/zamboni/tree/master/apps) and [Redmine](https://github.com/edavis10/redmine). All of Zamboni's [application code](https://github.com/mozilla/zamboni/tree/master/apps) resides within several dozen Django apps and just by reading the package (folder) names of each, you can see it's obvious that they document where certain parts (features) of the Web application are located and all the code pertaining to that feature is encapsulated within the app. Compare that with [Redmine](https://github.com/edavis10/redmine/tree/master/app), where a feature's components are kept separate and mixed with other components in predefined directories. You have to do a lot of navigation within and across different directories when your exploring or developing Redmine's Wiki feature and that makes it harder to get a holistic view on everything the Wiki feature provides.
This is just my personal opinion that Django has a better architectural premise for developing and maintaining large code bases.
### Is there a perception that Rails apps are more beautiful than Django apps?
As far as I can tell, personal preferences aside, both have a clean architectural design. If you follow the conventions and employ the same patterns as your framework does for solving similar problems, your apps should both look and feel beautiful to other framework developers.
So this in part also answers the point people said about the difficult learning curve of Rails, which I believe holds true for Django just as well. Both have a difficult learning curve in that it takes time to understand the basic philosophy and designs of your framework to design and develop beautiful applications that go with, not against the framework. By beautiful I mean that it becomes very natural to discover where a certain feature is implemented, or more discretely, it's data, presentation and behavior and that it's very obvious where new features should be added and how they interact with existing components.
But until you don't have a well founded understanding of your framework to fully appreciate it, you'll most likely take up on novel approaches that extensively configure and customize the framework experience for other developers. I think the only newbie mistake you can make in Rails and Django is to do something that works, but has a very fragile and unintuitive design, something that either goes against documented and proven approaches in an unfashionable manner or otherwise ignores basic framework principles.
### Is one easier to deploy than the other?
No, both provide tools for easy packaging and deployment. There are a lot of Ruby and Python Web servers out there in the wild that make deployment a breeze, although I can see most people still deploy their apps for Apache, which is a whole lot of bang for something that's likely to be used solely for instancing and interfacing with your Rails or Django app, so I understand where some of the pain is coming from.
### Which has better database libraries/ORM?
Rails and Django diverge on their perception of the database schema. Rails takes your existing schema and maps it to application logic, while Django takes your existing application logic and maps it to a schema. Both have never prevented anyone from building complex applications.
In Rails, your models bubble up from the schema, while in Django your schema bubbles up from the models. I haven't found this mentioned anywhere, but it's very reminiscent of the naked objects pattern, i.e. domain object attributes are not just dumb data holders. The models API facilitates a complete understanding of your data, because each model field is an instance of a complex, reusable and customizable field class that provides the business logic and the presentation for the data. Effectively, Django models can provide complex inheritance scenarios, their schema, manage impedance mismatch and provide the presentation for populating model data through HTML forms and an administrative backend.
The scaffolding in Rails is pretty much a throwaway, it's there to provide the basic CRUD until your provide your own complex presentation and behavior. Django has the admin that introspects your model and dynamically provides an elaborate interface for managing your model data that can be extensively customized through `ModelAdmin` objects. Even though you'll never provide non-staff users with access to the admin backend and will always have to design CRUD access within your Web site front presentation for other community users, you'll always use it to provide access to your data for users with elevated permissions. Basically, you can describe a model with a few lines and have a full-fledged, production ready interface for managing your domain objects.
The models are the focal point for any data, presentation and behavior triad and make it very easy to develop complex applications. Truth be told, since Django's models are more explicit, it makes it that much harder to customize the assumptions an application has about it's model data. This is never a problem until you start working with 3rd party Django apps, because once they ship a model that says a city's name can only be 72 characters long, your stuck with that. Django is shipping class based generic controllers in the current preview release that's due for a public release shortly, which should provide a much cleaner interface for customizing model interaction at the level of the controller. This should quickly streamline how people can extend and override the logic of 3rd party apps to abstract the assumptions about model data.
### Conclusion
Frankly, I just can't see how you can go wrong with either. Rails is indisputably the more popular choice in the wider developer community right now, but I'd believe it should be a purely personal choice which of the two you take, based on the amount of joy you get as a developer from one over the other. At this point, their design and feature set is mature enough to make it possible to do anything you need with both, regardless of how you accomplish it.
That would perhaps only leave you with having to judge the human resource and 3rd party solution pool. Though you can find more Python developers than Ruby developers, you'll surely find more Rails developers than Django developers. Django has picked up enough interest by now that you can find a Django application for anything you need, something Rails has been more established with; as far as languages go, you'll also find a native solution for anything you need in Ruby, something Python is more established with. I think you safely exclude native and framework 3rd party solutions out of the equation when making your choice. | Given your criteria, neither is better suited. If you're comfortable with Django and you feel Python is a language you can support in the future, go with that. Go with Rails otherwise.
Better question is, how will you design your app to take advantage of your language's features? How will you be storing your data. Etc. |
35,244,270 | I recently attempted to upgrade my leiningen install on a Windows XP (sp3) machine using both lein upgrade and lein self-install. Unfortunately, both attempts were unsuccessful as one can clearly see below:
```
C:\>lein upgrade
The script at C:\lein.bat will be upgraded to the latest stable version.
Do you want to continue (Y/N)?Y
Downloading latest Leiningen batch script...
--2016-02-06 10:36:08-- https://github.com/technomancy/leiningen/raw/stable/bin/lein.bat
Resolving github.com (github.com)... 192.30.252.131
Connecting to github.com (github.com)|192.30.252.131|:443... connected.
ERROR: cannot verify github.com's certificate, issued by 'CN=DigiCert SHA2 Extended Validation Serve
r CA,OU=www.digicert.com,O=DigiCert Inc,C=US':
Unable to locally verify the issuer's authority.
To connect to github.com insecurely, use `--no-check-certificate'.
Failed to download https://github.com/technomancy/leiningen/raw/stable/bin/lein.bat
C:\>lein self-install
Downloading Leiningen now...
--2016-02-06 10:39:39-- https://github.com/technomancy/leiningen/releases/download/2.6.0/leiningen-
2.6.0-standalone.zip
Resolving github.com (github.com)... 192.30.252.131
Connecting to github.com (github.com)|192.30.252.131|:443... connected.
ERROR: cannot verify github.com's certificate, issued by 'CN=DigiCert SHA2 Extended Validation Serve
r CA,OU=www.digicert.com,O=DigiCert Inc,C=US':
Unable to locally verify the issuer's authority.
To connect to github.com insecurely, use `--no-check-certificate'.
Failed to download https://github.com/technomancy/leiningen/releases/download/2.6.0/leiningen-2.6.0-
standalone.zip
It is possible that the download failed due to "powershell",
"curl" or "wget"'s inability to retreive GitHub's security certificate.
The suggestions below do not check certificates, so use this only if
you understand the security implications of not doing so.
Curl failed to download the latest Leiningen version.
Try to use "wget" to download Leiningen by setting up
the HTTP_CLIENT environment variable with one of the following
values:
" a) set HTTP_CLIENT=curl -f -L -k -o"
NOTE: make sure *not* to add double quotes to set the value of
HTTP_CLIENT
If neither curl nor wget can download Leiningen, please seek
for help on Leiningen's GitHub project issues page.
```
Using the --no-check-certificate option also failed to resolve the issue.
In a attempt to satiate my intellectual curiosity, I manually downloaded leiningen-2.6.0-standalone.zip, but I am unsure of how to proceed with the install so I can use leiningen in the customary manner. Would I sinmply upzip the file to a folder, e.g., C:\lein, and add it to my path? Any help would be appreciated.
Thanks. | 2016/02/06 | [
"https://Stackoverflow.com/questions/35244270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1136670/"
] | I think you are getting error on this line
`**String result = response.getProperty(0).toString();**`
If that's the case please check whether you are getting any response at all. If you are getting no response at all, then that could be the reason.
**check if you are providing the arguments to the webservice correctly.**
When using SOAP you have to provide arguments in a particular structure, like a SOAP object inside another SOAP object. Check the SOAP object you are creating and the one required are the same.
(Just print the request.toString() for checking)
PS: I meant to put this in the comment section. But i dont have enough reputation. | i faced this issue recently, the problem was about internet permission, and i fixed it by adding this line of code into manifest file.
```
<uses-permission android:name="android.permission.INTERNET" />
``` |
2,480,377 | What are some of the things you've observed in ColdFusion 9 with CF-ORM (Hibernate) that one should watch out for? | 2010/03/19 | [
"https://Stackoverflow.com/questions/2480377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35634/"
] | * entity `init()` method must not have required argument(s), otherwise `EntityNew()` and other CF-ORM actions will break. You may want to use a Factory to create the entity, and enforce the required arguments there.
[A bug regarding this limitation has been filed in the Adobe Bugbase.](https://bugbase.adobe.com/index.cfm?event=bug&id=4012852)
* `ORMReload()` with `ormsettings.dbcreate = "drop create"` might not drop all tables for you. [CF9 Cumulative Hot Fix 1](http://kb2.adobe.com/cps/825/cpsid_82536.html) improves this a little bit, but you might want to drop the tables in DB yourself.
* `type="date"` (default to use `ormtype="date"`), will only store date but not time. If you want to persisted time as well, use `ormtype="timestamp"`
* `type="string"` will default to `varchar(255)`
* `type="numeric"` will default to `float`, not `int`. Use ormtype="int" if needed.
* if `fieldtype="id"` and generator is set to some generator, ormtype will default to `int`.
* `type="string" length="10"` will use `varchar(10)`, not `char(10)`
* `ormtype="char" length="10"` will use `char(1)` still. Use `sqltype="char(10)"` if you really need to.
* `type="boolean"` use `tinyint` by default, use `sqltype="bit"` if you need to.
* should use `inverse=true` in a bi-directional relationship, usually in "one-to-many" side.
* do **NOT** use `inverse="true"` in uni-directional relationship! The relationship might not be persisted at all!
* If you use MS-SQL, you cannot have more than 1 entity with one-to-one property set to Null, because Null is considered as an unique value in an index. Good idea to make column not null. (or use linktable)
* `EntityLoad("entity", 1, true)` works, but `EntityLoadByPK("entity", 1)` is cleaner!
* `EntityLoad()`, `EntityLoadByPK()`, and `ORMExecuteQuery` with `unique=true`, will return `null` if entity is not found. Use `isNull()` to check before you use the returned value.
* `ORMExecuteQuery` will return empty array if no entity is found by default.
* don't forget to use `singularname` property in "one-to-many" / "many-to-many" for nicer looking generated functions (e.g. `addDog(Dog dog)` vs `addDogs(Dog dogs)` .)
* `<cfdump>` will load all the lazy-load properties. Alternatively you may try `<cfdump var="#entityToQuery([entity])#">` or set top=1 to dump efficiently.
* entity stored in Session scope will be disconnected with its Hibernate session scope, and lazy load property will not be loaded. To restore the hibernate session scope, use `entityLoadByExample()` or `entitySave(entity)`.
* `cascade="all-delete-orphan"` usually make more sense for "one-to-many" or "many-to-many" relationship. Hibernate sets null then delete, so make sure the column is nullable. Test and see if that's your desire behaviour.
* set `required="true"` whenever `notnull="true"`, more readable for others browsing the CFC with CFCExplorer
* `EntityNew('Y')` is slightly more efficient than `new com.X.Y` if the entity is to be persisted later according to some Adobe engineer.
* relationship with an inherited entity may break sometimes due to an unfixed Hibernate bug, use `linktable` as a workaround.
* `structKeyColumn` cannot be the PK of the target entity.
* bi-directional many-to-many cannot use struct
* When adding new entity to struct, `structKeyColumn` is ignored when CF persists the parent entity.
* If you access the one-to-many / many-to-many array or struct directly, make sure the corresponding array/struct exists before use. Generated addX()/hasX()/removeX() are safe to use anytime.
* at `postInsert()`, the entity hibernate session is no longer available, so setting property at postInsert() will be silently ignore, or Session is Closed exception will be thrown.
* after entity is loaded by `entityLoad()` or HQL from DB, the changes will be automatically persisted even if `EntitySave()` is not called.
* transaction with CF-ORM is implemented in a way that it starts a new session and close when it's done.
* inside the event (i.e. preLoad() / postInsert()), assigning to variables might throw Java exception about types. Use JavaCast() to work around the bug.
**UPDATE**
* CF9.0.1+: use `<cfquery dbtype="hql">`, easier to do `cfqueryparam`, and debug output actually shows you the binded values. | EntityReload appears to ignore lazy loading like CFDUMP.
I use it after an EntitySave to grab any defaulted columns in the db. I see in SQL Profiler ( a tracing tool for SQL Server ) lots of queries coming thru.
If change it to a EntityLoadByPK, etc it will load up the object and will not see all the excess relationship queries which for me can cause major problems. |
2,480,377 | What are some of the things you've observed in ColdFusion 9 with CF-ORM (Hibernate) that one should watch out for? | 2010/03/19 | [
"https://Stackoverflow.com/questions/2480377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35634/"
] | * entity `init()` method must not have required argument(s), otherwise `EntityNew()` and other CF-ORM actions will break. You may want to use a Factory to create the entity, and enforce the required arguments there.
[A bug regarding this limitation has been filed in the Adobe Bugbase.](https://bugbase.adobe.com/index.cfm?event=bug&id=4012852)
* `ORMReload()` with `ormsettings.dbcreate = "drop create"` might not drop all tables for you. [CF9 Cumulative Hot Fix 1](http://kb2.adobe.com/cps/825/cpsid_82536.html) improves this a little bit, but you might want to drop the tables in DB yourself.
* `type="date"` (default to use `ormtype="date"`), will only store date but not time. If you want to persisted time as well, use `ormtype="timestamp"`
* `type="string"` will default to `varchar(255)`
* `type="numeric"` will default to `float`, not `int`. Use ormtype="int" if needed.
* if `fieldtype="id"` and generator is set to some generator, ormtype will default to `int`.
* `type="string" length="10"` will use `varchar(10)`, not `char(10)`
* `ormtype="char" length="10"` will use `char(1)` still. Use `sqltype="char(10)"` if you really need to.
* `type="boolean"` use `tinyint` by default, use `sqltype="bit"` if you need to.
* should use `inverse=true` in a bi-directional relationship, usually in "one-to-many" side.
* do **NOT** use `inverse="true"` in uni-directional relationship! The relationship might not be persisted at all!
* If you use MS-SQL, you cannot have more than 1 entity with one-to-one property set to Null, because Null is considered as an unique value in an index. Good idea to make column not null. (or use linktable)
* `EntityLoad("entity", 1, true)` works, but `EntityLoadByPK("entity", 1)` is cleaner!
* `EntityLoad()`, `EntityLoadByPK()`, and `ORMExecuteQuery` with `unique=true`, will return `null` if entity is not found. Use `isNull()` to check before you use the returned value.
* `ORMExecuteQuery` will return empty array if no entity is found by default.
* don't forget to use `singularname` property in "one-to-many" / "many-to-many" for nicer looking generated functions (e.g. `addDog(Dog dog)` vs `addDogs(Dog dogs)` .)
* `<cfdump>` will load all the lazy-load properties. Alternatively you may try `<cfdump var="#entityToQuery([entity])#">` or set top=1 to dump efficiently.
* entity stored in Session scope will be disconnected with its Hibernate session scope, and lazy load property will not be loaded. To restore the hibernate session scope, use `entityLoadByExample()` or `entitySave(entity)`.
* `cascade="all-delete-orphan"` usually make more sense for "one-to-many" or "many-to-many" relationship. Hibernate sets null then delete, so make sure the column is nullable. Test and see if that's your desire behaviour.
* set `required="true"` whenever `notnull="true"`, more readable for others browsing the CFC with CFCExplorer
* `EntityNew('Y')` is slightly more efficient than `new com.X.Y` if the entity is to be persisted later according to some Adobe engineer.
* relationship with an inherited entity may break sometimes due to an unfixed Hibernate bug, use `linktable` as a workaround.
* `structKeyColumn` cannot be the PK of the target entity.
* bi-directional many-to-many cannot use struct
* When adding new entity to struct, `structKeyColumn` is ignored when CF persists the parent entity.
* If you access the one-to-many / many-to-many array or struct directly, make sure the corresponding array/struct exists before use. Generated addX()/hasX()/removeX() are safe to use anytime.
* at `postInsert()`, the entity hibernate session is no longer available, so setting property at postInsert() will be silently ignore, or Session is Closed exception will be thrown.
* after entity is loaded by `entityLoad()` or HQL from DB, the changes will be automatically persisted even if `EntitySave()` is not called.
* transaction with CF-ORM is implemented in a way that it starts a new session and close when it's done.
* inside the event (i.e. preLoad() / postInsert()), assigning to variables might throw Java exception about types. Use JavaCast() to work around the bug.
**UPDATE**
* CF9.0.1+: use `<cfquery dbtype="hql">`, easier to do `cfqueryparam`, and debug output actually shows you the binded values. | Add'l recommendations:
* Turn off ormsettings.flushAtRequestEnd = false to not have auto-flush at the end of the request. Instead use transactions (as of CF9.01, cftransaction flushes session for you transaction completion) around all write transactions (entitySave() or when you edit a persisted entity).
* Prevent SQL injection by using binded parameters in HQL - unnamed '?' or named ':' notations, to assure type binding by ORM against the field in question (like CFQUERYPARAM does). Prevent SQL injection!
* CF9.0.1 allows CFQUERY dbtype="hql" to write & output HQL inline. Use CFQUERYPARAM to bind params inline (equivalent to unnamed ? notation in HQL).
* Use LEFT OUTER JOIN FETCH in HQL to eager fetch relationships.
* Override add/remove functions on CFCs with bi-directional relationships to assure both sides are set when either is.
* Turn ormsettings.logsql=true to view derived SQL in the console. Adjust log4j Hibernate settings to further tweak log settings from Hibernate.
* Join Google Group cf-orm-dev. Bright people there. |
2,480,377 | What are some of the things you've observed in ColdFusion 9 with CF-ORM (Hibernate) that one should watch out for? | 2010/03/19 | [
"https://Stackoverflow.com/questions/2480377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35634/"
] | * entity `init()` method must not have required argument(s), otherwise `EntityNew()` and other CF-ORM actions will break. You may want to use a Factory to create the entity, and enforce the required arguments there.
[A bug regarding this limitation has been filed in the Adobe Bugbase.](https://bugbase.adobe.com/index.cfm?event=bug&id=4012852)
* `ORMReload()` with `ormsettings.dbcreate = "drop create"` might not drop all tables for you. [CF9 Cumulative Hot Fix 1](http://kb2.adobe.com/cps/825/cpsid_82536.html) improves this a little bit, but you might want to drop the tables in DB yourself.
* `type="date"` (default to use `ormtype="date"`), will only store date but not time. If you want to persisted time as well, use `ormtype="timestamp"`
* `type="string"` will default to `varchar(255)`
* `type="numeric"` will default to `float`, not `int`. Use ormtype="int" if needed.
* if `fieldtype="id"` and generator is set to some generator, ormtype will default to `int`.
* `type="string" length="10"` will use `varchar(10)`, not `char(10)`
* `ormtype="char" length="10"` will use `char(1)` still. Use `sqltype="char(10)"` if you really need to.
* `type="boolean"` use `tinyint` by default, use `sqltype="bit"` if you need to.
* should use `inverse=true` in a bi-directional relationship, usually in "one-to-many" side.
* do **NOT** use `inverse="true"` in uni-directional relationship! The relationship might not be persisted at all!
* If you use MS-SQL, you cannot have more than 1 entity with one-to-one property set to Null, because Null is considered as an unique value in an index. Good idea to make column not null. (or use linktable)
* `EntityLoad("entity", 1, true)` works, but `EntityLoadByPK("entity", 1)` is cleaner!
* `EntityLoad()`, `EntityLoadByPK()`, and `ORMExecuteQuery` with `unique=true`, will return `null` if entity is not found. Use `isNull()` to check before you use the returned value.
* `ORMExecuteQuery` will return empty array if no entity is found by default.
* don't forget to use `singularname` property in "one-to-many" / "many-to-many" for nicer looking generated functions (e.g. `addDog(Dog dog)` vs `addDogs(Dog dogs)` .)
* `<cfdump>` will load all the lazy-load properties. Alternatively you may try `<cfdump var="#entityToQuery([entity])#">` or set top=1 to dump efficiently.
* entity stored in Session scope will be disconnected with its Hibernate session scope, and lazy load property will not be loaded. To restore the hibernate session scope, use `entityLoadByExample()` or `entitySave(entity)`.
* `cascade="all-delete-orphan"` usually make more sense for "one-to-many" or "many-to-many" relationship. Hibernate sets null then delete, so make sure the column is nullable. Test and see if that's your desire behaviour.
* set `required="true"` whenever `notnull="true"`, more readable for others browsing the CFC with CFCExplorer
* `EntityNew('Y')` is slightly more efficient than `new com.X.Y` if the entity is to be persisted later according to some Adobe engineer.
* relationship with an inherited entity may break sometimes due to an unfixed Hibernate bug, use `linktable` as a workaround.
* `structKeyColumn` cannot be the PK of the target entity.
* bi-directional many-to-many cannot use struct
* When adding new entity to struct, `structKeyColumn` is ignored when CF persists the parent entity.
* If you access the one-to-many / many-to-many array or struct directly, make sure the corresponding array/struct exists before use. Generated addX()/hasX()/removeX() are safe to use anytime.
* at `postInsert()`, the entity hibernate session is no longer available, so setting property at postInsert() will be silently ignore, or Session is Closed exception will be thrown.
* after entity is loaded by `entityLoad()` or HQL from DB, the changes will be automatically persisted even if `EntitySave()` is not called.
* transaction with CF-ORM is implemented in a way that it starts a new session and close when it's done.
* inside the event (i.e. preLoad() / postInsert()), assigning to variables might throw Java exception about types. Use JavaCast() to work around the bug.
**UPDATE**
* CF9.0.1+: use `<cfquery dbtype="hql">`, easier to do `cfqueryparam`, and debug output actually shows you the binded values. | In conjunction with fiddling with the Hibernate logging you can also turn "maintain connections" off for your datasource.
With SQL Server 2005 you can then launch profiler and watch the queries coming thru.
Since maintain connections is off Hibernate will be forced to create new prepared statements each time.
Reading prepared statements can be tough, but at least you can see the raw queries that are being generated.
If you maintain connections these prepared statements are created once and you just see something like
sp\_execute 15, 'someparam'
Before this was ran sp\_prepexec was ran which is where the 15 comes from. |
2,480,377 | What are some of the things you've observed in ColdFusion 9 with CF-ORM (Hibernate) that one should watch out for? | 2010/03/19 | [
"https://Stackoverflow.com/questions/2480377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35634/"
] | Add'l recommendations:
* Turn off ormsettings.flushAtRequestEnd = false to not have auto-flush at the end of the request. Instead use transactions (as of CF9.01, cftransaction flushes session for you transaction completion) around all write transactions (entitySave() or when you edit a persisted entity).
* Prevent SQL injection by using binded parameters in HQL - unnamed '?' or named ':' notations, to assure type binding by ORM against the field in question (like CFQUERYPARAM does). Prevent SQL injection!
* CF9.0.1 allows CFQUERY dbtype="hql" to write & output HQL inline. Use CFQUERYPARAM to bind params inline (equivalent to unnamed ? notation in HQL).
* Use LEFT OUTER JOIN FETCH in HQL to eager fetch relationships.
* Override add/remove functions on CFCs with bi-directional relationships to assure both sides are set when either is.
* Turn ormsettings.logsql=true to view derived SQL in the console. Adjust log4j Hibernate settings to further tweak log settings from Hibernate.
* Join Google Group cf-orm-dev. Bright people there. | EntityReload appears to ignore lazy loading like CFDUMP.
I use it after an EntitySave to grab any defaulted columns in the db. I see in SQL Profiler ( a tracing tool for SQL Server ) lots of queries coming thru.
If change it to a EntityLoadByPK, etc it will load up the object and will not see all the excess relationship queries which for me can cause major problems. |
2,480,377 | What are some of the things you've observed in ColdFusion 9 with CF-ORM (Hibernate) that one should watch out for? | 2010/03/19 | [
"https://Stackoverflow.com/questions/2480377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35634/"
] | In conjunction with fiddling with the Hibernate logging you can also turn "maintain connections" off for your datasource.
With SQL Server 2005 you can then launch profiler and watch the queries coming thru.
Since maintain connections is off Hibernate will be forced to create new prepared statements each time.
Reading prepared statements can be tough, but at least you can see the raw queries that are being generated.
If you maintain connections these prepared statements are created once and you just see something like
sp\_execute 15, 'someparam'
Before this was ran sp\_prepexec was ran which is where the 15 comes from. | EntityReload appears to ignore lazy loading like CFDUMP.
I use it after an EntitySave to grab any defaulted columns in the db. I see in SQL Profiler ( a tracing tool for SQL Server ) lots of queries coming thru.
If change it to a EntityLoadByPK, etc it will load up the object and will not see all the excess relationship queries which for me can cause major problems. |
2,480,377 | What are some of the things you've observed in ColdFusion 9 with CF-ORM (Hibernate) that one should watch out for? | 2010/03/19 | [
"https://Stackoverflow.com/questions/2480377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35634/"
] | Add'l recommendations:
* Turn off ormsettings.flushAtRequestEnd = false to not have auto-flush at the end of the request. Instead use transactions (as of CF9.01, cftransaction flushes session for you transaction completion) around all write transactions (entitySave() or when you edit a persisted entity).
* Prevent SQL injection by using binded parameters in HQL - unnamed '?' or named ':' notations, to assure type binding by ORM against the field in question (like CFQUERYPARAM does). Prevent SQL injection!
* CF9.0.1 allows CFQUERY dbtype="hql" to write & output HQL inline. Use CFQUERYPARAM to bind params inline (equivalent to unnamed ? notation in HQL).
* Use LEFT OUTER JOIN FETCH in HQL to eager fetch relationships.
* Override add/remove functions on CFCs with bi-directional relationships to assure both sides are set when either is.
* Turn ormsettings.logsql=true to view derived SQL in the console. Adjust log4j Hibernate settings to further tweak log settings from Hibernate.
* Join Google Group cf-orm-dev. Bright people there. | In conjunction with fiddling with the Hibernate logging you can also turn "maintain connections" off for your datasource.
With SQL Server 2005 you can then launch profiler and watch the queries coming thru.
Since maintain connections is off Hibernate will be forced to create new prepared statements each time.
Reading prepared statements can be tough, but at least you can see the raw queries that are being generated.
If you maintain connections these prepared statements are created once and you just see something like
sp\_execute 15, 'someparam'
Before this was ran sp\_prepexec was ran which is where the 15 comes from. |
15,909,604 | So I am writing a code for a binary search tree and I am far(I think) and there is a point where when I try and compile it I get an error that says
"File: D:\ReservationQueue.java [line: 15]
Error: left cannot be resolved or is not a field
File: D:\ReservationQueue.java [line: 17]
Error: right cannot be resolved or is not a field
File: D:\ReservationQueue.java [line: 4]
Warning: The field ReservationQueue.right is never read locally...
this is the code for the errors,
```
public class ReservationQueue{
private Reservation root;
private Reservation left;
private Reservation right;
public boolean empty() {return root == null;}
public String findRoot() {return root.getName();}
public void deleteRoot(){root = left; }
public void insert(Reservation node) {
if(this.empty()) {
root = node;
} else if (node.getPriority() < root.getPriority()){
insert(node.left);
} else if (node.getPriority() > root.getPriority()){
insert(node.right);
}
}
}
```
This is the Reservation class if it helps
public class Reservation{
private int priority;
private String name;
```
public Reservation(String name, int priority){
if (priority < 1) {
this.priority = 1;
} else if (priority > 10) {
this.priority = 10;
} else {
this.priority = priority;
}
}
public String getName(){return name;}
public int getPriority(){return priority;}
}
```
I really need help I have no idea what I am doing wrong, thank you in advance | 2013/04/09 | [
"https://Stackoverflow.com/questions/15909604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2224803/"
] | `node` is type `Reservation`, and `left` and `right` are fields of `ReservationQueue`. Therefore the following two lines won't compile:
```
insert(node.left);
insert(node.right);
```
If `ReservationQueue` is meant to be a tree with nodes of type `Reservation`, then `left` and `right` should probably be members of `Reservation` and not of `ReservationQueue`. | It is not totally clear what you are doing.
1. You don't have left and right variables in Reservetion classs, and what are they anyways.
2. May be you mean to
```
else if (node.getPriority() < root.getPriority()){
insert(left);
} else if (node.getPriority() > root.getPriority()){
insert(right);
``` |
12,954,331 | Using `HttpClient` 4.1.3, I've written the following code:
```
HttpClient httpClient = HttpClientFactory.newHttpClient();
HttpGet httpGet = new HttpGet("some/url/to/hit");
HttpResponse httpResp = httpClient.execute(httpGet);
int statusCode = httpResp.getStatusLine().getStatusCode();
if(statusCode != HttpStatus.SC_OK)
throw new Exception(/* ... */);
```
That's getting HTTP 500 responses (as found in the `httpResp.getStatusLine().getStatusCode()`) from a particular URL and throwing the exception.
The thing is, when I go to the "failing" URL in a browser, its running perfectly fine.
So I ask:
* Could `HttpClient` be timing out, short-circuiting the request-response cycle, and just giving me an HTTP 500?
* What else could be going on here? How is it possible for `HttpClient` to be giving me 500s when the browser is displaying the page perfectly fine for the same exact URL?
Thanks in advance! | 2012/10/18 | [
"https://Stackoverflow.com/questions/12954331",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/892029/"
] | The following works just fine for me:
```
image.Source = new BitmapImage(new Uri("pack://application:,,,/YourAssemblyName;component/Resources/someimage.png", UriKind.Absolute));
```
Also you should change the `Build Action` of your image from `None` to `Resource`. | You can open the Resource Editor (Solution Explorer, click on Resources.resx) and add the image there. Then you can simply access it as `Bitmap` with `Properties.Resources.ImageId`
<http://msdn.microsoft.com/en-us/library/3bka19x4(v=vs.100).aspx> |
12,954,331 | Using `HttpClient` 4.1.3, I've written the following code:
```
HttpClient httpClient = HttpClientFactory.newHttpClient();
HttpGet httpGet = new HttpGet("some/url/to/hit");
HttpResponse httpResp = httpClient.execute(httpGet);
int statusCode = httpResp.getStatusLine().getStatusCode();
if(statusCode != HttpStatus.SC_OK)
throw new Exception(/* ... */);
```
That's getting HTTP 500 responses (as found in the `httpResp.getStatusLine().getStatusCode()`) from a particular URL and throwing the exception.
The thing is, when I go to the "failing" URL in a browser, its running perfectly fine.
So I ask:
* Could `HttpClient` be timing out, short-circuiting the request-response cycle, and just giving me an HTTP 500?
* What else could be going on here? How is it possible for `HttpClient` to be giving me 500s when the browser is displaying the page perfectly fine for the same exact URL?
Thanks in advance! | 2012/10/18 | [
"https://Stackoverflow.com/questions/12954331",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/892029/"
] | The following works just fine for me:
```
image.Source = new BitmapImage(new Uri("pack://application:,,,/YourAssemblyName;component/Resources/someimage.png", UriKind.Absolute));
```
Also you should change the `Build Action` of your image from `None` to `Resource`. | I had some problems to find the exact syntax for the URI, so see below more details :
If your image (`myImage.png`) is located in a subfolder "images" (from the root directory) , the exact syntax is :
```
image.Source = new BitmapImage(new Uri(@"pack://application:,,,/images/myImage.png", UriKind.Absolute));
```
If your image is in the subfolder `images/icon/` (from the root directory) , the syntax is :
```
image.Source = new BitmapImage(new Uri(@"pack://application:,,,/images/icon/myImage.png", UriKind.Absolute));
```
* Note that the part `"pack://application:,,,` does not change.
* Be sure to set the "Build action" to "Resources"
For more information: [see here](https://learn.microsoft.com/en-us/dotnet/framework/wpf/app-development/pack-uris-in-wpf#Resource_File_Pack_URIs___Local_Assembly). |
53,551,705 | Basic Info :
```
Puppet Version: 2.8.1
OS Name/Version: RedHat 7
```
We are trying to run the below puppet resource but we are getting whitespace error, Please find the same.
```
mount { "/SERVER/New York_share":
atboot => true,
ensure => mounted,
device => "//MOUNTSERVER/New York_share",
fstype => "cifs",
options => "credentials=/tmp/id,uid=oracle,gid=oinstall,iocharset=utf8,file_mode=0644,dir_mode=0775,_netdev,soft", }
```
**Error:**
>
> Failed to apply catalog: Parameter name failed on Mount[/SERVER/New
> York\_share]: name must not contain whitespace: /SERVER/New York\_share
> at
> /etc/puppetlabs/code/environments/master/site/profile/manifests/ob.pp:132
>
>
>
Anybody could suggest us. Please respond. | 2018/11/30 | [
"https://Stackoverflow.com/questions/53551705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6694591/"
] | You need provide more details about your codes which doesn't work. But basically you can refer to below steps:
1. Add ASP.NET Core 2.0 web api application .
2. Install Microsoft.AspNetCore.Session NuGet package .
3. Modify your Startup.cs, call `AddDistributedMemoryCache` and `AddSessio`n methods in ConfigureServices function , and add `UseSession` method in Configure function :
```
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddDistributedMemoryCache();
services.AddSession();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseSession();
app.UseMvc();
}
```
4. Get/Set session in controller(using Microsoft.AspNetCore.Http;) :
```
[HttpGet("setSession/{name}")]
public IActionResult setsession(string name)
{
HttpContext.Session.SetString("Name", name);
return Ok("session data set");
}
[HttpGet("getSession")]
public IActionResult getsessiondata()
{
var sessionData = HttpContext.Session.GetString("Name");
return Ok(sessionData);
}
```
5. Then you could make api call to `http://localhost:xxxxx/api/ControllerName/setSession/derek` to set session , and call to `http://localhost:xxxxx/api/ControllerName/getSession` to get session data . | Following tutorial will help to set up Session values in server-side in ASP .Net Core Web API application.
[Tutorial for Session in API Core](https://andrewlock.net/an-introduction-to-session-storage-in-asp-net-core/) |
51,472,393 | I have a method called `SendWithReplyAsync`, it uses `TaskCompletionSource` to signal when it is complete and return a reply from the server.
I am trying to get 2 replies from the server in a method that also needs to change scenes, change transforms, etc so it needs to be on the main thread, as I understand it.
This method is bound to the `OnClick()` of a ui button in unity:
```
public async void RequestLogin()
{
var username = usernameField.text;
var password = passwordField.text;
var message = new LoginRequest() { Username = username, Password = password };
var reply = await client.SendWithReplyAsync<LoginResponse>(message);
if (reply.Result)
{
Debug.Log($"Login success!");
await worldManager.RequestSpawn();
}
else Debug.Log($"Login failed! {reply.Error}");
}
```
as you can see, there is a call to `await WorldManager.RequestSpawn();`
That method looks like this:
```
public async Task RequestSpawn()
{
//Get the initial spawn zone and transform
var spawnReply = await client.SendWithReplyAsync<PlayerSpawnResponse>(new PlayerSpawnRequest());
//Load the correct zone
SceneManager.LoadScene("TestingGround");
//Move the player to the correct location
var state = spawnReply.initialState;
player.transform.position = state.Position.Value.ToVector3();
player.transform.rotation = Quaternion.Euler(0, state.Rotation.Value, 0);
//The last step is to get the visible entities at our position and create them before closing the loading screen
var statesReply = await client.SendWithReplyAsync<InitialEntityStatesReply>(new InitialEntityStatesRequest());
SpawnNewEntities(statesReply);
}
```
So when I click the button, I can see (server side) that all of the messages (the login request, the spawn request and the initial entity state request) are all making it. However, nothing happens in unity. No scene change and (obviously) no position or rotation update.
I have a feeling i am not understanding something about async/await when it comes to unity and my `RequestSpawn` method is not running on the main thread.
I tried using `client.SendWithReplyAsync(...).Result` and removing the `async` keyword on all the methods, but that just caused a deadlock. I read more about deadlocks on Stephen Cleary's blog [here](https://blog.stephencleary.com/2012/07/dont-block-on-async-code.html) ( it seems his site consumes 100% cpu.. am I the only one?)
I am really not sure how to get this working.
In case you need them, here are the methods that send/receive messages:
```
public async Task<TReply> SendWithReplyAsync<TReply>(Message message) where TReply : Message
{
var task = msgService.RegisterReplyHandler(message);
Send(message);
return (TReply)await task;
}
public Task<Message> RegisterReplyHandler(Message message, int timeout = MAX_REPLY_WAIT_MS)
{
var replyToken = Guid.NewGuid();
var completionSource = new TaskCompletionSource<Message>();
var tokenSource = new CancellationTokenSource();
tokenSource.CancelAfter(timeout);
//TODO Make sure there is no leakage with the call to Token.Register()
tokenSource.Token.Register(() =>
{
completionSource.TrySetCanceled();
if (replyTasks.ContainsKey(replyToken))
replyTasks.Remove(replyToken);
},
false);
replyTasks.Add(replyToken, completionSource);
message.ReplyToken = replyToken;
return completionSource.Task;
}
```
And here is where/how the tasks are completed:
```
private void HandleMessage<TMessage>(TMessage message, object sender = null) where TMessage : Message
{
//Check if the message is in reply to a previously sent one.
//If it is, we can complete the reply task with the result
if (message.ReplyToken.HasValue &&
replyTasks.TryGetValue(message.ReplyToken.Value, out TaskCompletionSource<Message> tcs) &&
!tcs.Task.IsCanceled)
{
tcs.SetResult(message);
return;
}
//The message is not a reply, so we can invoke the associated handlers as usual
var messageType = message.GetType();
if (messageHandlers.TryGetValue(messageType, out List<Delegate> handlers))
{
foreach (var handler in handlers)
{
//If we have don't have a specific message type, we have to invoke the handler dynamically
//If we do have a specific type, we can invoke the handler much faster with .Invoke()
if (typeof(TMessage) == typeof(Message))
handler.DynamicInvoke(sender, message);
else
((Action<object, TMessage>)handler).Invoke(sender, message);
}
}
else
{
Debug.LogError(string.Format("No handler found for message of type {0}", messageType.FullName));
throw new NoHandlersException();
}
}
```
*fingers crossed the legendary Stephen Cleary sees this* | 2018/07/23 | [
"https://Stackoverflow.com/questions/51472393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/693943/"
] | Assuming you're using async/await via a recent version of Unity with '.NET 4.x Equivalent' set as the Scripting Runtime Version, then your `RequestSpawn()` method as written should be running on Unity's main thread. You can verify by calling:
```
Debug.Log(System.Threading.Thread.CurrentThread.ManagedThreadId);
```
The following simple test loads the new scene correctly for me, using Unity 2018.2 (output below):
```
public async void HandleAsync()
{
Debug.Log($"Foreground: {System.Threading.Thread.CurrentThread.ManagedThreadId}");
await WorkerAsync();
Debug.Log($"Foreground: {System.Threading.Thread.CurrentThread.ManagedThreadId}");
}
private async Task WorkerAsync()
{
await Task.Delay(500);
Debug.Log($"Worker: {Thread.CurrentThread.ManagedThreadId}");
await Task.Run((System.Action)BackgroundWork);
await Task.Delay(500);
SceneManager.LoadScene("Scene2");
}
private void BackgroundWork()
{
Debug.Log($"Background: {Thread.CurrentThread.ManagedThreadId}");
}
```
Output:
>
> Foreground: 1
>
>
> Worker: 1
>
>
> Background: 48
>
>
> Foreground: 1
>
>
> | try to do the async request with Coroutines and Callbacks,...
first, start a Coroutine....
in the routine u prepare and fire the request....
after this, u break the routine with this:
```
while(!request.isDone) {
yield return null;
}
```
after u get a response, use a callback function to change your scene |
45,687,792 | I am new to realm and I am trying to use Realm in my project. Here I am trying to parse JSON and save it using realm. When I am trying to loop through the result array error occurs
>
> 'Attempting to modify object outside of a write transaction - call beginwritetransaction on an RLMRealm instance first'
>
>
>
This is the JSON result:
```
{"data":[{"id":1,"parent_id":0,"name":"JenniferMaenle","title":"Ms","phone":"","address":"Toled, ohio","email":"jlmaenle@aol.com","image":"44381525_2017.jpg","relation_id":5,"created_at":null,"updated_at":"2017-08-10 02:30:05"},{"id":2, "parent_id":1,"name":"Khadeeja","title":"","phone":"","address":"","email":"","image":"Khadeeja_2017-07-17.jpg","relation_id":2,"created_at":null,"updated_at":"2017-07-17 08:3:12"}]}
```
I am trying to parse JSON and save it in the Realm database. Here is my try:
```
class Person: Object {
dynamic var name = ""
dynamic var title = ""
dynamic var address = ""
}
override func viewDidLoad() {
super.viewDidLoad()
self.add()
}
func add(){
guard let data = dataFromFile("ServerData") else { return }
let persons = Person()
do {
if let json = try JSONSerialization.jsonObject(with: data) as? [String: AnyObject] {
if let data = json["data"] as? [[String:AnyObject]]{
for eachItem in data{
persons.name = eachItem["name"] as! String
persons.title = eachItem["title"] as! String
persons.address = eachItem["address"] as! String
try! realm.write {
realm.add(persons)
}
}
}
}
} catch {
print("Error deserializing JSON: \(error)")
}
}
``` | 2017/08/15 | [
"https://Stackoverflow.com/questions/45687792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8465491/"
] | ```
var countElements = $('[name^="detailList["]').filter('[name$="].category"]').length;
```
this will give you all elements with names starting with "detailList[" and ending with "].category"
so it will not match name="detailList[2].foo" for example | ```
document.querySelectorAll('[property=value]'); // All with "property" set to "value" exactly.
``` |
45,687,792 | I am new to realm and I am trying to use Realm in my project. Here I am trying to parse JSON and save it using realm. When I am trying to loop through the result array error occurs
>
> 'Attempting to modify object outside of a write transaction - call beginwritetransaction on an RLMRealm instance first'
>
>
>
This is the JSON result:
```
{"data":[{"id":1,"parent_id":0,"name":"JenniferMaenle","title":"Ms","phone":"","address":"Toled, ohio","email":"jlmaenle@aol.com","image":"44381525_2017.jpg","relation_id":5,"created_at":null,"updated_at":"2017-08-10 02:30:05"},{"id":2, "parent_id":1,"name":"Khadeeja","title":"","phone":"","address":"","email":"","image":"Khadeeja_2017-07-17.jpg","relation_id":2,"created_at":null,"updated_at":"2017-07-17 08:3:12"}]}
```
I am trying to parse JSON and save it in the Realm database. Here is my try:
```
class Person: Object {
dynamic var name = ""
dynamic var title = ""
dynamic var address = ""
}
override func viewDidLoad() {
super.viewDidLoad()
self.add()
}
func add(){
guard let data = dataFromFile("ServerData") else { return }
let persons = Person()
do {
if let json = try JSONSerialization.jsonObject(with: data) as? [String: AnyObject] {
if let data = json["data"] as? [[String:AnyObject]]{
for eachItem in data{
persons.name = eachItem["name"] as! String
persons.title = eachItem["title"] as! String
persons.address = eachItem["address"] as! String
try! realm.write {
realm.add(persons)
}
}
}
}
} catch {
print("Error deserializing JSON: \(error)")
}
}
``` | 2017/08/15 | [
"https://Stackoverflow.com/questions/45687792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8465491/"
] | If you mean `detailList[x].category` matches all three, i.e. x is any number
```js
var result = [].filter.call(document.querySelectorAll('[name^="detailList["]'), function(item) {
return item.name.match(/^detailList\[\d+\].category$/);
}).length;
console.log(result, 'matches');
```
```html
<input name="detailList[0].category"/>
<input name="detailList[1].category"/>
<input name="detailList[2].category"/>
<input name="detailList[DoesntMatchThePattern"/>
``` | ```
document.querySelectorAll('[property=value]'); // All with "property" set to "value" exactly.
``` |
13,566,751 | I have Python GUI, and in one for-loop I call function from some dll which returns values for populating tableWidget row by row. All this works fine, except I can't scroll table while it's still populating (while dll function calculating things - 7-8secs for each row) so I tried work with threads like this:
```
q = Queue.Queue()
for i in (0, numberOfRows):
threading.Thread(target=self.callFunctionFromDLL, args=(arg1,arg2, q)).start()
result = q.get()
... do something with "result" and populate table row....
def callFunctionFromDLL(self, arg1, arg2, q):
result = self.dll.functionFromDLL(arg1, arg2)
q.put(result)
```
but still GUI is not responding until result is passed from q.get (functionFromDLL works 7-8 secs, and than for a moment while GUI populating row I can scroll table). I didn't really worked with threads before, so any suggestion or example how to do this would be appreciated.
I've also tried this way, same thing, gui still not responding while functionFromDLL works:
```
for i in (0, numberOfRows):
t = threading.Thread(target=self.callFunctionFromDLL, args=(arg1,arg2))
t.start()
t.join()
result = self.result
... do something with "result" and populate table row....
def callFunctionFromDLL(self, arg1, arg2):
self.result = self.dll.functionFromDLL(arg1, arg2)
``` | 2012/11/26 | [
"https://Stackoverflow.com/questions/13566751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1155106/"
] | If you are using the `tkinter` module, you might be able to get some help from how [Directory Pruner 4](http://code.activestate.com/recipes/578154/) is implemented. To get around the fact that most GUI libraries do not play well with threads, the recipe utilizes some custom modules listed below the code. The modules `affinity`, `threadbox`, and `safetkinter` provide a thread-safe wrapping of the GUI library the program uses. | CPython (what you probably have) has a Global Interpreter Lock in it that defeats a lot of multithreading. This is a known problem that has proven difficult to solve. (Look up "Python GIL" for more info.) Some other implementations, such as Jython, don't have this problem. |
33,548,744 | I need to load the content of a file on different computers at the same time. Because a StreamReader will occupy the file, I want to copy it to a temporary folder before opening it. (The title is more general as there should be no difference between two threads running on one computer and two computers running one thread each.)
Question: will two threads copying a file at the same time affect each other even when the copy destinations are separated? | 2015/11/05 | [
"https://Stackoverflow.com/questions/33548744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4792869/"
] | Don't - it's much easier to just use the correct arguments when creating your file stream.
The key is the `FileShare` setting - it says what kinds of operations are allowed on the file you have opened. Specify `FileShare.Read`, and any number of concurrent read operations (that also have a `FileShare.Read`) on the same file will work just fine.
It's as simple as
```
File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read)
``` | It's safe to read a file from multiple threads/processes/machines, as long as there is no one writing to the file at the same time. |
33,548,744 | I need to load the content of a file on different computers at the same time. Because a StreamReader will occupy the file, I want to copy it to a temporary folder before opening it. (The title is more general as there should be no difference between two threads running on one computer and two computers running one thread each.)
Question: will two threads copying a file at the same time affect each other even when the copy destinations are separated? | 2015/11/05 | [
"https://Stackoverflow.com/questions/33548744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4792869/"
] | It's safe to read a file from multiple threads/processes/machines, as long as there is no one writing to the file at the same time. | Your operation is reading. It is like reading a book by 2 person simultaneously. So it is thread safe.
However, if you write some note to the file by two threads - it is not thread safe. It is like two person writing some notes in one copybook. They will just disturb each other and letters will be not correct and the meaning will be incorrect. |
33,548,744 | I need to load the content of a file on different computers at the same time. Because a StreamReader will occupy the file, I want to copy it to a temporary folder before opening it. (The title is more general as there should be no difference between two threads running on one computer and two computers running one thread each.)
Question: will two threads copying a file at the same time affect each other even when the copy destinations are separated? | 2015/11/05 | [
"https://Stackoverflow.com/questions/33548744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4792869/"
] | Don't - it's much easier to just use the correct arguments when creating your file stream.
The key is the `FileShare` setting - it says what kinds of operations are allowed on the file you have opened. Specify `FileShare.Read`, and any number of concurrent read operations (that also have a `FileShare.Read`) on the same file will work just fine.
It's as simple as
```
File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read)
``` | Your operation is reading. It is like reading a book by 2 person simultaneously. So it is thread safe.
However, if you write some note to the file by two threads - it is not thread safe. It is like two person writing some notes in one copybook. They will just disturb each other and letters will be not correct and the meaning will be incorrect. |
6,155,625 | I have researched everywhere but still can't seem to fix a simple error:
Running Microsoft SQL server:
```
UPDATE copyprogmaster
SET active =
CASE
WHEN active = 1 THEN active = 0
WHEN active = 0 THEN active = 1
ELSE active
END
WHERE source = 'Mass_Mail'
```
my error is :
>
> Line 4: Incorrect syntax near '='.
>
>
> | 2011/05/27 | [
"https://Stackoverflow.com/questions/6155625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/735319/"
] | Remove the `=` after the `THEN`, so:
```
UPDATE copyprogmaster
SET active =
CASE
WHEN active = 1 THEN 0
WHEN active = 0 THEN 1
ELSE active
END
WHERE source = 'Mass_Mail'
```
You already have `active =` after the `SET` on the second line. | You do not need to repeat "active =" after THEN
```
UPDATE copyprogmaster
SET active =
CASE
WHEN active = 1 THEN 0
WHEN active = 0 THEN 1
ELSE active
END
WHERE source = 'Mass_Mail'
```
Here's an example from the documentation at <http://msdn.microsoft.com/en-us/library/ms181765.aspx>
```
USE AdventureWorks2008R2;
GO
SELECT ProductNumber, Category =
CASE ProductLine
WHEN 'R' THEN 'Road'
WHEN 'M' THEN 'Mountain'
WHEN 'T' THEN 'Touring'
WHEN 'S' THEN 'Other sale items'
ELSE 'Not for sale'
END,
Name
FROM Production.Product
ORDER BY ProductNumber;
GO
``` |
6,155,625 | I have researched everywhere but still can't seem to fix a simple error:
Running Microsoft SQL server:
```
UPDATE copyprogmaster
SET active =
CASE
WHEN active = 1 THEN active = 0
WHEN active = 0 THEN active = 1
ELSE active
END
WHERE source = 'Mass_Mail'
```
my error is :
>
> Line 4: Incorrect syntax near '='.
>
>
> | 2011/05/27 | [
"https://Stackoverflow.com/questions/6155625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/735319/"
] | Remove the `=` after the `THEN`, so:
```
UPDATE copyprogmaster
SET active =
CASE
WHEN active = 1 THEN 0
WHEN active = 0 THEN 1
ELSE active
END
WHERE source = 'Mass_Mail'
```
You already have `active =` after the `SET` on the second line. | Based on your query, I assume the `active` field is `bit` or `int` (assuming that `int` field has only values **0**, **1**, or **NULL**). In that case, I believe that you can write the query as following:
```
UPDATE dbo.copyprogmaster
SET active = active ^ 1
WHERE source = 'Mass_Mail'
```
Notice that the query can handle `NULL` values and also the rows #**1**, #**4** and #**6** in the screenshot are unchanged. Screenshot #**1** shows table structure and screenshot #**2** displays sample execution of the above query.
Hope that helps.
**Screenshot #1:**
![Table](https://i.stack.imgur.com/LLvGO.png)
**Screenshot #2:**
![Output](https://i.stack.imgur.com/5k5n4.png) |
6,155,625 | I have researched everywhere but still can't seem to fix a simple error:
Running Microsoft SQL server:
```
UPDATE copyprogmaster
SET active =
CASE
WHEN active = 1 THEN active = 0
WHEN active = 0 THEN active = 1
ELSE active
END
WHERE source = 'Mass_Mail'
```
my error is :
>
> Line 4: Incorrect syntax near '='.
>
>
> | 2011/05/27 | [
"https://Stackoverflow.com/questions/6155625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/735319/"
] | You do not need to repeat "active =" after THEN
```
UPDATE copyprogmaster
SET active =
CASE
WHEN active = 1 THEN 0
WHEN active = 0 THEN 1
ELSE active
END
WHERE source = 'Mass_Mail'
```
Here's an example from the documentation at <http://msdn.microsoft.com/en-us/library/ms181765.aspx>
```
USE AdventureWorks2008R2;
GO
SELECT ProductNumber, Category =
CASE ProductLine
WHEN 'R' THEN 'Road'
WHEN 'M' THEN 'Mountain'
WHEN 'T' THEN 'Touring'
WHEN 'S' THEN 'Other sale items'
ELSE 'Not for sale'
END,
Name
FROM Production.Product
ORDER BY ProductNumber;
GO
``` | Based on your query, I assume the `active` field is `bit` or `int` (assuming that `int` field has only values **0**, **1**, or **NULL**). In that case, I believe that you can write the query as following:
```
UPDATE dbo.copyprogmaster
SET active = active ^ 1
WHERE source = 'Mass_Mail'
```
Notice that the query can handle `NULL` values and also the rows #**1**, #**4** and #**6** in the screenshot are unchanged. Screenshot #**1** shows table structure and screenshot #**2** displays sample execution of the above query.
Hope that helps.
**Screenshot #1:**
![Table](https://i.stack.imgur.com/LLvGO.png)
**Screenshot #2:**
![Output](https://i.stack.imgur.com/5k5n4.png) |
8,591,053 | I have a situation where my table is loading before getting the data from my webservice.
When I debug it, I can see that my `NSMutableArray` has 123 objects, but it's not being reflected in the table.
This is my `connectionDidFinishLoading` method:
```
-(void)connectionDidFinishLoading:(NSURLConnection *)conn{
myData = [[NSString alloc] initWithData:xData encoding:NSUTF8StringEncoding];
SBJsonParser *jParser = [SBJsonParser new];
NSError *error = nil;
NSArray *jsonObjects = [jParser objectWithString:myData error:&error];
NSMutableArray *books = [[NSMutableArray alloc] init];
for(NSDictionary *dict in jsonObjects)
{
Book *b = [Book new];
b.bookName =[dict objectForKey:@"name"];
b.published = [dict objectForKey:@"published"];
[books addObject:b];
}
self.bookArray = books;
[self.tableView reloadData];
NSLog(@"myData = %@",myData);
}
```
If I debug this I'm getting my `jsonObjects` and populating my collection. But I notice my table is still empty.
Just to clarify this is my `tableView` method:
```
(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
...
Book *b = (Book *)[self.bookArray objectAtIndex:[indexPath row]];
cell.textLabel.text = b.bookName;
....
```
Can anyone help me with what I'm missing? | 2011/12/21 | [
"https://Stackoverflow.com/questions/8591053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1086420/"
] | It seems you can't, according to [this post in the Android googlegroup](http://groups.google.com/group/android-developers/browse_thread/thread/d692479c86e6eb8c?pli=1).
I guess that the most you can do is **launching** the radio app via an appropriate intent; I think, however, that these intents belong to a single vendor's SDK (check this [presentation from Archos, for instance](http://www.archos.com/support/download/software/ArchosAPIdemo.pdf) ).
So, I think that your best bet is to search for similar, **vendor-provided** api by Samsung | There is no API in the AOSP for FM radio. Thus, you cannot build your application with radio support. At the same time, SE proposed their solution for radio support but it is still not included in the main branch. You can read about it
[here](https://groups.google.com/forum/#!topic/android-platform/eFhxfsxqIMc "Google groups discussion").
At the same time, in some custom roms you already can find examples how to play with radio. For instance, [here](https://github.com/CyanogenMod/android_packages_apps_FM "FM app") is the code of application that is included in the Cyanogenmod. You can build and install this application on your phone and see if it works. If it is then you can build your application basing on this approach.
Also check the answer from the previous message. |
24,006,325 | I am very close to completing an AJAX delete method but I am confused about an error message that I receive when the AJAX method is completed. Here is the output generated from my terminal when I click on the AJAX method:
```
started DELETE "/tasks/71" for 127.0.0.1 at 2014-06-02 22:38:03 -0400
Processing by TasksController#destroy as JS
Parameters: {"id"=>"71"}
Task Load (0.5ms) SELECT "tasks".* FROM "tasks" WHERE "tasks"."id" = $1 LIMIT 1
[["id", 71]]
(0.2ms) BEGIN
SQL (0.3ms) DELETE FROM "tasks" WHERE "tasks"."id" = $1 [["id", 71]]
(75.5ms) COMMIT
Redirected to http://localhost:3000/
Completed 302 Found in 82ms (ActiveRecord: 76.5ms)
Started DELETE "/" for 127.0.0.1 at 2014-06-02 22:38:03 -0400
ActionController::RoutingError (No route matches [DELETE] "/"):
actionpack (4.1.0) lib/action_dispatch/middleware/debug_exceptions.rb:21:in `call'
```
Notice the Started DELETE '/' for 127.0 etc. part. What exactly is that telling me? From the output, I see that the AJAX function was completed succesfully. I'm confused as to what the Routing Error is referring to. Can someone explain to me what this is so I may be able to fix it?
Also, this is my controller code for the destroy function.
```
def destroy
@task = Task.find(params[:id])
@task.destroy
respond_to do |format|
format.html { redirect_to root_path, notice: "Task Successfully Removed, Good job!"}
format.json { render root_path, notice: "Task Successfully Removed, Good job!" }
end
```
end
As you can see, the code should be correct. I've tried changing render to redirect\_to but I still get the same problem. Thse are my routes:
```
Rails.application.routes.draw do
root 'tasks#index'
resources :tasks, except: [:show]
```
Finally, this is my ajax.js.erb file:
```
$(document).ready(function() {
$(this).on('delete', function(event) {
event.preventDefault();
var id = $(this).attr("data-id");
var data_info = $(this);
$.ajax({
type: 'DELETE',
url: Routes.task_path(id),
dataType: 'json',
data: data_info,
success: function(response) {
$(response).remove();
},
});
});
});
```
Where could the problem be? I don't think its in my ajax.js.erb file because the action completes. If not there then where? Thanks for the help in advance.
-----------EDIT-----------
I just realized that my output used the JS format not JSON to delete an item. Now I have a follow up question as to why that is? I'm even more confused because in the ajax call I specifically specify it as a JSON call not JS. Did I do something wrong?
-----------EDIT-------------
I tried inserting this line of code as recommended by Rick Peck.
```
format.js { render root_path, notice: "Task Successfully Removed, Good job!", layout: !request.xhr? }
```
but now I am receiving a 500 internal server error:
```
started DELETE "/tasks/108" for 127.0.0.1 at 2014-06-03 14:47:36 -0400
Processing by TasksController#destroy as JS
Parameters: {"id"=>"108"}
Task Load (0.2ms) SELECT "tasks".* FROM "tasks" WHERE "tasks"."id" = $1 LIMIT 1 [["id", 108]]
(0.1ms) BEGIN
SQL (0.2ms) DELETE FROM "tasks" WHERE "tasks"."id" = $1 [["id", 108]]
(1.8ms) COMMIT
Completed 500 Internal Server Error in 5ms
NoMethodError - undefined method `empty?' for nil:NilClass:
actionview (4.1.0) lib/action_view/lookup_context.rb:178:in `normalize_name'
actionview (4.1.0) lib/action_view/lookup_context.rb:153:in `args_for_lookup'
```
What makes this extremely annoying is that I'm unable to use debugger to checkout out what's happening. I've deduced that something is happening in my ajax code. Right here:
```
$.ajax({
type: 'DELETE',
url: Routes.task_path(id),
dataType: 'json',
data: data_info,
success: function(response) {
$(response).remove();
// Something is wrong here with the remove function undefined method 'empty'.
// Why is the call being sent as JS not JSON
// Where is the 500 error coming from?
},
});
});
```
I suspect that my response does not contain the information that I want. All I want to do is remove that HTML element that contained my task entry. I can't see what it is though because I can't use debugger. I can't tell if its my ajax logic in the controller or the ajax.js.erb file. Any thoughts? | 2014/06/03 | [
"https://Stackoverflow.com/questions/24006325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2325598/"
] | To make it work please set **enforceDefine** to **false**.
According to official [docs](http://requirejs.org/docs/api.html)
>
> enforceDefine: If set to true, an error will be thrown if a script
> loads that does not call define() or have a shim exports string value
> that can be checked.
>
>
> | as for jquery plugin, I prefer to convert to UMD module which is much cleaner way to avoid contamination of global variable |
20,666,361 | This is a Win32 program, and I Write a CaptureMousePosition function to capture the mouse's position.![This is CaptureMousePosition function.](https://i.stack.imgur.com/YGWNe.jpg)
and I call the function in WM\_MOUSEMOVE message.![This is where I call the function.](https://i.stack.imgur.com/qqLWs.jpg)
Then I run the program.when my mouse moves on the red point, it is (126,112).There is no problem here.![run the program.](https://i.stack.imgur.com/IJRIU.jpg)
But when my mouse moves on the blue point,it becomes (960,940).How can it happen,I don't understand, why the red point is (126,112),but the blue point is (960,940).the blue point should be ( < 126, < 112).how to fix it.![enter image description here](https://i.stack.imgur.com/GVwQD.jpg) | 2013/12/18 | [
"https://Stackoverflow.com/questions/20666361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3116182/"
] | The [documentation for `WM_MOUSEMOVE`](http://msdn.microsoft.com/en-us/library/windows/desktop/ms645616%28v=vs.85%29.aspx) clearly states:
>
> Use the following code to obtain the horizontal and vertical position:
>
>
>
> ```
> xPos = GET_X_LPARAM(lParam);
> yPos = GET_Y_LPARAM(lParam);
>
> ```
>
> As noted above, the x-coordinate is in the low-order short of the return value; the y-coordinate is in the high-order short (both represent signed values because they can take negative values on systems with multiple monitors). If the return value is assigned to a variable, you can use the MAKEPOINTS macro to obtain a POINTS structure from the return value. You can also use the GET\_X\_LPARAM or GET\_Y\_LPARAM macro to extract the x- or y-coordinate.
>
>
> **Important** Do not use the LOWORD or HIWORD macros to extract the x- and y- coordinates of the cursor position because these macros return incorrect results on systems with multiple monitors. Systems with multiple monitors can have negative x- and y- coordinates, and LOWORD and HIWORD treat the coordinates as unsigned quantities.
>
>
>
Change this:
```
short nX;
nX = (short)LOWORD(lParam);
short nY;
nY = (short)HIWORD(lParam);
```
To this:
```
short nX;
nX = GET_X_LPARAM(lParam);
short nY;
nY = GET_Y_LPARAM(lParam);
```
Or this:
```
POINTS pt;
pt = MAKEPOINTS(lParam);
short nX;
nX = pt.x;
short nY;
nY = pt.y;
```
**Update:** something else to note from the [documentation](http://msdn.microsoft.com/en-us/library/windows/desktop/ms645616%28v=vs.85%29.aspx):
>
> Posted to a window when the cursor moves. If the mouse is not captured, the message is posted to the window that contains the cursor. Otherwise, the message is posted to the window that has captured the mouse.
>
>
>
That means if the mouse has been captured via `SetCapture()`, the reported coordinates will be relative to the window that is doing the capturing, not the window that the mouse is actually moving over. | Without showing your code, is hard to answer, but I guess, that problem is in Screen vs. Client coordinates. |
20,666,361 | This is a Win32 program, and I Write a CaptureMousePosition function to capture the mouse's position.![This is CaptureMousePosition function.](https://i.stack.imgur.com/YGWNe.jpg)
and I call the function in WM\_MOUSEMOVE message.![This is where I call the function.](https://i.stack.imgur.com/qqLWs.jpg)
Then I run the program.when my mouse moves on the red point, it is (126,112).There is no problem here.![run the program.](https://i.stack.imgur.com/IJRIU.jpg)
But when my mouse moves on the blue point,it becomes (960,940).How can it happen,I don't understand, why the red point is (126,112),but the blue point is (960,940).the blue point should be ( < 126, < 112).how to fix it.![enter image description here](https://i.stack.imgur.com/GVwQD.jpg) | 2013/12/18 | [
"https://Stackoverflow.com/questions/20666361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3116182/"
] | Everything is just fine. The coordinates of the blue dot are `X = 96` and `Y = 94`. You are seeing `X = 960` because you are not erasing the 0 left over from `X = 100`. You would have noticed that the values are just fine if you had used a debugger to step through the code. | Without showing your code, is hard to answer, but I guess, that problem is in Screen vs. Client coordinates. |
20,653,476 | How to pass javascript variable that came from select option to a PHP variable?
I want to set PHP variable depending on user selection.
I tried that code:
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(function(){
$("select[name='sex']").change(function () {
var submitSearchData = jQuery('#extended-search').serialize();
var selectedValue=$('#sex').val();
jQuery.ajax({
type: "POST",
data: 'selected=' + selectedValue
url: "ajax.php",
success: function () {
// alert(submitSearchData);
alert(selectedValue);
}
});
});
});
</script>
<form id="extended-search" >
<div class="input-container">
<select class="select" name="sex" id="sex">
<option value="0">All</option>
<option value="1">M</option>
<option value="2">F</option>
</select>
</div>
</form>
<?php
var_dump ($_REQUEST['selected']); //that print NULL don't know why!
?>
``` | 2013/12/18 | [
"https://Stackoverflow.com/questions/20653476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3114378/"
] | You are passing data in wrong format. Data is passed as an object. Please refer below.
```
$("select[name='sex']").change(function () {
var submitSearchData = jQuery('#extended-search').serialize();
var selectedValue=$('#sex').val();
jQuery.ajax({
type: "POST",
data: {'selected': selectedValue},
url: "ajax.php",
success: function (response) {
// alert(submitSearchData);
alert(response);
}
});
});
``` | Is not possible in the same instance of time:
yourfile -> ajax -> yourfile (here is the value, but you can't see this in your current webpage except that instead of ajax, send post form) |
20,653,476 | How to pass javascript variable that came from select option to a PHP variable?
I want to set PHP variable depending on user selection.
I tried that code:
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(function(){
$("select[name='sex']").change(function () {
var submitSearchData = jQuery('#extended-search').serialize();
var selectedValue=$('#sex').val();
jQuery.ajax({
type: "POST",
data: 'selected=' + selectedValue
url: "ajax.php",
success: function () {
// alert(submitSearchData);
alert(selectedValue);
}
});
});
});
</script>
<form id="extended-search" >
<div class="input-container">
<select class="select" name="sex" id="sex">
<option value="0">All</option>
<option value="1">M</option>
<option value="2">F</option>
</select>
</div>
</form>
<?php
var_dump ($_REQUEST['selected']); //that print NULL don't know why!
?>
``` | 2013/12/18 | [
"https://Stackoverflow.com/questions/20653476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3114378/"
] | You are passing data in wrong format. Data is passed as an object. Please refer below.
```
$("select[name='sex']").change(function () {
var submitSearchData = jQuery('#extended-search').serialize();
var selectedValue=$('#sex').val();
jQuery.ajax({
type: "POST",
data: {'selected': selectedValue},
url: "ajax.php",
success: function (response) {
// alert(submitSearchData);
alert(response);
}
});
});
``` | I hope this will help you...
```
dataType: "html",
data: {'selected': selectedValue},
```
and then u can get it via $\_POST/$\_REQUEST array since you have set your type to post. |
20,653,476 | How to pass javascript variable that came from select option to a PHP variable?
I want to set PHP variable depending on user selection.
I tried that code:
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(function(){
$("select[name='sex']").change(function () {
var submitSearchData = jQuery('#extended-search').serialize();
var selectedValue=$('#sex').val();
jQuery.ajax({
type: "POST",
data: 'selected=' + selectedValue
url: "ajax.php",
success: function () {
// alert(submitSearchData);
alert(selectedValue);
}
});
});
});
</script>
<form id="extended-search" >
<div class="input-container">
<select class="select" name="sex" id="sex">
<option value="0">All</option>
<option value="1">M</option>
<option value="2">F</option>
</select>
</div>
</form>
<?php
var_dump ($_REQUEST['selected']); //that print NULL don't know why!
?>
``` | 2013/12/18 | [
"https://Stackoverflow.com/questions/20653476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3114378/"
] | You are passing data in wrong format. Data is passed as an object. Please refer below.
```
$("select[name='sex']").change(function () {
var submitSearchData = jQuery('#extended-search').serialize();
var selectedValue=$('#sex').val();
jQuery.ajax({
type: "POST",
data: {'selected': selectedValue},
url: "ajax.php",
success: function (response) {
// alert(submitSearchData);
alert(response);
}
});
});
``` | $\_REQUEST is null because it is not related to the ajax request you send. Try this for example:
```
<?php
if (isset($_POST["selected"])) {
echo $_POST["selected"];
} else {
?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<form id="extended-search">
<div class="input-container">
<select class="select" name="sex" id="sex">
<option value="0">All</option>
<option value="1">M</option>
<option value="2">F</option>
</select>
</div>
</form>
<script>
$(function() {
$("select[name='sex']").change(function () {
var selected = $(this).val();
$.ajax({
type: "POST",
data: {
selected: selected
},
url: "ajax.php",
success: function (data) {
alert(data);
}
});
});
});
</script>
</body>
</html>
<?php } ?>
```
EDIT:
I updated the script and tested it. You had some errors in your code. Hope this works for you. |
44,844,488 | I want to return BadRequest status code from Initialize method. I understand, how can I do it from any Action ( return new HttpStatusCodeResult(HttpStatusCode.BadRequest) ), but how to do it from Initialize? I try the following:
```
requestContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
```
but I get
>
> Exception Details: System.NullReferenceException: Object reference not
> set to an instance of an object.
>
>
>
if I don't call
```
base.Initialize(requestContext);
``` | 2017/06/30 | [
"https://Stackoverflow.com/questions/44844488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/285336/"
] | No, it is not possible. Values of `p1` and `p2` are run-time properties, not compile time properties, hence the compiler does not "know" their values at compile-time.
You can make them known at compile-time by using `constexpr`, and pass them as template arguments instead, e.g.:
```
#include <iostream>
#include <type_traits>
enum class props {
left, right
};
template <props v>
typename std::enable_if<v == props::left, void>::type allowLeftOnly()
{ std::cout << "Wow!\n"; }
int main() {
constexpr auto p1 = props::left;
constexpr auto p2 = props::right;
allowLeftOnly<p1>();
allowLeftOnly<p2>(); // Fails to compile
}
``` | You can change `p` in to a template parameter and then use `std::enable_if`, like this:
```
template <props p> // p is now a template parameter
std::enable_if_t<p == props::left> // We only allow p == props::left, return type is implicitly void
allowLeftOnly() // No 'normal' parameters anymore
{
std::cout << "Wow!";
}
int main()
{
constexpr props p1 = props::left;
constexpr props p2 = props::right;
allowLeftOnly<p1>();
// allowLeftOnly<p2>(); // Fails to compile
}
```
For `p1` and `p2` the `constexpr` keyword ensures we can use the variables as template parameters.
If you later want another return type, e.g., `int` then use:
```
std::enable_if_t<p == props::left, int>
``` |
44,844,488 | I want to return BadRequest status code from Initialize method. I understand, how can I do it from any Action ( return new HttpStatusCodeResult(HttpStatusCode.BadRequest) ), but how to do it from Initialize? I try the following:
```
requestContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
```
but I get
>
> Exception Details: System.NullReferenceException: Object reference not
> set to an instance of an object.
>
>
>
if I don't call
```
base.Initialize(requestContext);
``` | 2017/06/30 | [
"https://Stackoverflow.com/questions/44844488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/285336/"
] | No, it is not possible. Values of `p1` and `p2` are run-time properties, not compile time properties, hence the compiler does not "know" their values at compile-time.
You can make them known at compile-time by using `constexpr`, and pass them as template arguments instead, e.g.:
```
#include <iostream>
#include <type_traits>
enum class props {
left, right
};
template <props v>
typename std::enable_if<v == props::left, void>::type allowLeftOnly()
{ std::cout << "Wow!\n"; }
int main() {
constexpr auto p1 = props::left;
constexpr auto p2 = props::right;
allowLeftOnly<p1>();
allowLeftOnly<p2>(); // Fails to compile
}
``` | As the other answers suggest to use a template parameter, I'll also add an answer that show how this can be implemented using tag-dispatching ([description from boost.org](http://www.boost.org/community/generic_programming.html#tag_dispatching)):
```
#include <iostream>
using namespace std;
struct props
{
struct left {};
struct right {};
};
void allowLeftOnly(props::left p)
{
cout << "Wow!";
}
int main()
{
allowLeftOnly(props::left{});
// allowLeftOnly(props::right{}); // Fails to compile
}
``` |
44,844,488 | I want to return BadRequest status code from Initialize method. I understand, how can I do it from any Action ( return new HttpStatusCodeResult(HttpStatusCode.BadRequest) ), but how to do it from Initialize? I try the following:
```
requestContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
```
but I get
>
> Exception Details: System.NullReferenceException: Object reference not
> set to an instance of an object.
>
>
>
if I don't call
```
base.Initialize(requestContext);
``` | 2017/06/30 | [
"https://Stackoverflow.com/questions/44844488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/285336/"
] | You can change `p` in to a template parameter and then use `std::enable_if`, like this:
```
template <props p> // p is now a template parameter
std::enable_if_t<p == props::left> // We only allow p == props::left, return type is implicitly void
allowLeftOnly() // No 'normal' parameters anymore
{
std::cout << "Wow!";
}
int main()
{
constexpr props p1 = props::left;
constexpr props p2 = props::right;
allowLeftOnly<p1>();
// allowLeftOnly<p2>(); // Fails to compile
}
```
For `p1` and `p2` the `constexpr` keyword ensures we can use the variables as template parameters.
If you later want another return type, e.g., `int` then use:
```
std::enable_if_t<p == props::left, int>
``` | As the other answers suggest to use a template parameter, I'll also add an answer that show how this can be implemented using tag-dispatching ([description from boost.org](http://www.boost.org/community/generic_programming.html#tag_dispatching)):
```
#include <iostream>
using namespace std;
struct props
{
struct left {};
struct right {};
};
void allowLeftOnly(props::left p)
{
cout << "Wow!";
}
int main()
{
allowLeftOnly(props::left{});
// allowLeftOnly(props::right{}); // Fails to compile
}
``` |
194,914 | I am planning on carrying out a design using the CP2102 Interface IC. The cheapest price I can source (for bulk purchase of 1500 parts) is from Digikey at 2.34$/piece. A price of 2.34$ is approximately 151 Indian rupees.
However, CP2102 modules (with usb connectors etc.) are available on ebay India for prices as low as 162 Indian Rupees. How do they do get such ridculously low prices? I can't even imagine competing against such prices. So any ideas on how prices can be reduced? Any experiences? | 2015/10/12 | [
"https://electronics.stackexchange.com/questions/194914",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/57437/"
] | So you want to make an Interface Module, using an Interface IC, but you find that buying the IC from Distributors Inc costs the same as an entire module (including connectors) from Shenzen Inc via well known auction site, FortyThieves.com.
Assuming the question is not *"Where should I buy to get the best prices?"* but *"How is it possible to make money selling entire modules at the same price as the raw IC?"*
Also assuming that all parties are honest and legitimate parties to the deal ... as other answers note, this may not always be the case.
(Names and actual prices are of course fictitious)
---
The first thing to note is the economy of scale.
Buying your Interface IC may net you a better deal in 1500s than buying 1 or 10, but the IC fab probably cannot afford to set up a production run for less than a million. So Distributors Inc and Shenzen Inc both negotiate with the fab to buy a million pieces, at probably a quarter of the best price you can see. (Maybe a tenth : actual figures are rarely made public. Maybe Shenzen Inc name a better price on the back of another deal, or during a recession when the fab want to keep the plant running. But let's assume the same price)
Now both buyers have a million parts - a significant investment, with inventory costs to boot. Distributors Inc reclaim that investment by passing on high prices to you. In return you have a simple buying process, essentially no risk of counterfeit parts, friendly application engineers, usually no lead times on common items, and all that is easily worth the quadrupling in price.
Shenzen Inc didn't start negotiations until they were about to land a firm order for a million smartphones at a price that covers their costs nicely. If they buy an entire run designed to produce a million good parts, and the yield is higher than (cautious) predictions, they are left with maybe a hundred thousand parts surplus inventory.
---
The second thing to note is the importance of marginal costs.
The true price of these surplus parts is not 1/4 or 1/10 of the price you pay : it is reduced by the cost of managing inventory. Unlike the distributor, to whom it is adding value to the part (so it's available as a service to customers) it is an excess cost to the manufacturer. Surplus inventory can be sold ... but for pennies, if there is a buyer. Its marginal cost is close to 0.
EDIT to be clearer : the cost of managing inventory (the warehouse, the shelf, stock control software etc) increases the price via Distributors Inc, but reduces the price Shenzen Inc needs to charge. because they want to get rid of this nuisance to save money.
Anything Shenzen Inc can do cheaply, to add value to surplus inventory and shift it, is worthwhile. It keeps their PCB plant, connector suppliers, and assembly technicians employed. It may allow trainee engineers practice in designing PCBs and translators practice on user manuals. And the work doesn't have to be to the same contractually imposed standards as the smartphone business. It uses the cheapest materials, perhaps recycling connectors or PCB laminate rejected from the prime production line. It may actually be built semi-officially after hours or in a garage instead of the shiny new factory.
Then it's sold in bulk to dealers who redistribute it however they can ... often via the auction sites.
---
Fundamentally, both routes to you involve added value and much greater expense than the price of the raw chip.
It is quite possible that the manufactured board may - by leveraging marginal costs in ways such as these - reach you at lower cost than the chip, even without resorting to illegal practices.
If that suits your needs, it's a good deal, and even a few cents return instead of a loss can be good deal for the vendor. But it can put your own business at risk. The supply may dry up at any moment, with no guarantee of future price or even availability - even without considering possibilities like rejects or counterfeit.
All in all, it's not surprising that the price of the finished product hovers around the price of the same IC from Distributors Inc. That's the price the end market will bear... | The cheapest you can find at digikey is still pretty far from the cheapest you can actually buy it because you are still going through a distributor.
If you want to actually buy it cheaply, you go to silicon labs or the fabrication plant directly. For instance, they can be ordered for about 85 cents each in quantities of 100 on alibaba. |
194,914 | I am planning on carrying out a design using the CP2102 Interface IC. The cheapest price I can source (for bulk purchase of 1500 parts) is from Digikey at 2.34$/piece. A price of 2.34$ is approximately 151 Indian rupees.
However, CP2102 modules (with usb connectors etc.) are available on ebay India for prices as low as 162 Indian Rupees. How do they do get such ridculously low prices? I can't even imagine competing against such prices. So any ideas on how prices can be reduced? Any experiences? | 2015/10/12 | [
"https://electronics.stackexchange.com/questions/194914",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/57437/"
] | So you want to make an Interface Module, using an Interface IC, but you find that buying the IC from Distributors Inc costs the same as an entire module (including connectors) from Shenzen Inc via well known auction site, FortyThieves.com.
Assuming the question is not *"Where should I buy to get the best prices?"* but *"How is it possible to make money selling entire modules at the same price as the raw IC?"*
Also assuming that all parties are honest and legitimate parties to the deal ... as other answers note, this may not always be the case.
(Names and actual prices are of course fictitious)
---
The first thing to note is the economy of scale.
Buying your Interface IC may net you a better deal in 1500s than buying 1 or 10, but the IC fab probably cannot afford to set up a production run for less than a million. So Distributors Inc and Shenzen Inc both negotiate with the fab to buy a million pieces, at probably a quarter of the best price you can see. (Maybe a tenth : actual figures are rarely made public. Maybe Shenzen Inc name a better price on the back of another deal, or during a recession when the fab want to keep the plant running. But let's assume the same price)
Now both buyers have a million parts - a significant investment, with inventory costs to boot. Distributors Inc reclaim that investment by passing on high prices to you. In return you have a simple buying process, essentially no risk of counterfeit parts, friendly application engineers, usually no lead times on common items, and all that is easily worth the quadrupling in price.
Shenzen Inc didn't start negotiations until they were about to land a firm order for a million smartphones at a price that covers their costs nicely. If they buy an entire run designed to produce a million good parts, and the yield is higher than (cautious) predictions, they are left with maybe a hundred thousand parts surplus inventory.
---
The second thing to note is the importance of marginal costs.
The true price of these surplus parts is not 1/4 or 1/10 of the price you pay : it is reduced by the cost of managing inventory. Unlike the distributor, to whom it is adding value to the part (so it's available as a service to customers) it is an excess cost to the manufacturer. Surplus inventory can be sold ... but for pennies, if there is a buyer. Its marginal cost is close to 0.
EDIT to be clearer : the cost of managing inventory (the warehouse, the shelf, stock control software etc) increases the price via Distributors Inc, but reduces the price Shenzen Inc needs to charge. because they want to get rid of this nuisance to save money.
Anything Shenzen Inc can do cheaply, to add value to surplus inventory and shift it, is worthwhile. It keeps their PCB plant, connector suppliers, and assembly technicians employed. It may allow trainee engineers practice in designing PCBs and translators practice on user manuals. And the work doesn't have to be to the same contractually imposed standards as the smartphone business. It uses the cheapest materials, perhaps recycling connectors or PCB laminate rejected from the prime production line. It may actually be built semi-officially after hours or in a garage instead of the shiny new factory.
Then it's sold in bulk to dealers who redistribute it however they can ... often via the auction sites.
---
Fundamentally, both routes to you involve added value and much greater expense than the price of the raw chip.
It is quite possible that the manufactured board may - by leveraging marginal costs in ways such as these - reach you at lower cost than the chip, even without resorting to illegal practices.
If that suits your needs, it's a good deal, and even a few cents return instead of a loss can be good deal for the vendor. But it can put your own business at risk. The supply may dry up at any moment, with no guarantee of future price or even availability - even without considering possibilities like rejects or counterfeit.
All in all, it's not surprising that the price of the finished product hovers around the price of the same IC from Distributors Inc. That's the price the end market will bear... | Reputable companies are very selective about who they buy their parts from. They want traceability back to the manufacturer to minimise the risk of counterfiets. Mouser for example explicitly promise that all their parts have been sourced either from the manufacturer directly or from the manufacturer's authorised distributors.
It is often possible to get the chips cheaper from less reputable sources (the sort of vendors you commonly find on sites like alibaba). Some of these will be legitimate surplus but a lot will be conterfiet. The rock bottom price "direct from china" board vendors are almost certainly buying on this market.
Also 1500 part's is hardly "bulk", especially for a low value part. |
61,183,446 | I'm trying to learn the current version of Angular, v9. And I'm running on Windows 10, though I wouldn't have thought that would matter for a client-side technology.
The tutorials say I should start with `npm install -g @angular/cli`, so I do that. It prints a bunch of warnings about several dozen packages, but otherwise appears to work (I've never used npm before, so I don't know what to expect).
The next step is to create a project with "ng new", so I try to do that, but it fails with a weird error:
```
C:\temp\ngtest>ng new my-first-project
C:\Users\Mark\AppData\Roaming\npm\node_modules\@angular\cli\bin\ng:17
var version = process.versions.node.split('.').map(part => Number(part));
^^
SyntaxError: Unexpected token =>
at exports.runInThisContext (vm.js:73:16)
at Module._compile (module.js:443:25)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
at node.js:814:3
C:\temp\ngtest>
```
I really didn't expect a syntax error at this point, and I have no idea what to do about it.
Google didn't turn up any hits on this particular error, but several similar errors suggest tracking down package incompatibilities or dependencies. I have no idea how to do that, and I guess I thought the whole point of npm was to take care of stuff like that for me.
Help?
P.S. Just to establish a baseline, imagine a clever guy, decent programmer, who has been teleported from the year 2000 to 2020. Programming is still programming, of course - but the infrastructure is bewildering and frankly incomprehensible. There are at least a dozen layers of stuff that "everybody" knows so thoroughly that they don't even think about it any more. | 2020/04/13 | [
"https://Stackoverflow.com/questions/61183446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/470369/"
] | Use f strings:
```
print(f"Macro average precision : {precision_score(y_true, y_pred, average='macro')*100}%\n")
```
Or convert the value to string, and add (*concatenate*) the strings:
```
print('Macro average precision : ' + str(precision_score(y_true, y_pred, average='macro')*100) + "%\n")
```
See [the discussion here](https://stackoverflow.com/questions/59180574/string-concatenation-with-vs-f-string_) of the merits of each; basically the first is more convenient; and the second is computationally faster, and perhaps more simple to understand. | The simple, "low-tech" way is to correct your (lack of) output expression. Convert the float to a string and concatenate. To make it easy to follow:
```
pct = precision_score(y_true, y_pred, average='macro')*100
print('Macro average precision : ' + str(pct) + "%\n")
```
This is inelegant, but easy to follow. |
61,183,446 | I'm trying to learn the current version of Angular, v9. And I'm running on Windows 10, though I wouldn't have thought that would matter for a client-side technology.
The tutorials say I should start with `npm install -g @angular/cli`, so I do that. It prints a bunch of warnings about several dozen packages, but otherwise appears to work (I've never used npm before, so I don't know what to expect).
The next step is to create a project with "ng new", so I try to do that, but it fails with a weird error:
```
C:\temp\ngtest>ng new my-first-project
C:\Users\Mark\AppData\Roaming\npm\node_modules\@angular\cli\bin\ng:17
var version = process.versions.node.split('.').map(part => Number(part));
^^
SyntaxError: Unexpected token =>
at exports.runInThisContext (vm.js:73:16)
at Module._compile (module.js:443:25)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
at node.js:814:3
C:\temp\ngtest>
```
I really didn't expect a syntax error at this point, and I have no idea what to do about it.
Google didn't turn up any hits on this particular error, but several similar errors suggest tracking down package incompatibilities or dependencies. I have no idea how to do that, and I guess I thought the whole point of npm was to take care of stuff like that for me.
Help?
P.S. Just to establish a baseline, imagine a clever guy, decent programmer, who has been teleported from the year 2000 to 2020. Programming is still programming, of course - but the infrastructure is bewildering and frankly incomprehensible. There are at least a dozen layers of stuff that "everybody" knows so thoroughly that they don't even think about it any more. | 2020/04/13 | [
"https://Stackoverflow.com/questions/61183446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/470369/"
] | Use f strings:
```
print(f"Macro average precision : {precision_score(y_true, y_pred, average='macro')*100}%\n")
```
Or convert the value to string, and add (*concatenate*) the strings:
```
print('Macro average precision : ' + str(precision_score(y_true, y_pred, average='macro')*100) + "%\n")
```
See [the discussion here](https://stackoverflow.com/questions/59180574/string-concatenation-with-vs-f-string_) of the merits of each; basically the first is more convenient; and the second is computationally faster, and perhaps more simple to understand. | You can try this:
```
print('accuracy: {:.2f}%'.format(100*accuracy_score(y_true, y_pred)))
``` |
61,183,446 | I'm trying to learn the current version of Angular, v9. And I'm running on Windows 10, though I wouldn't have thought that would matter for a client-side technology.
The tutorials say I should start with `npm install -g @angular/cli`, so I do that. It prints a bunch of warnings about several dozen packages, but otherwise appears to work (I've never used npm before, so I don't know what to expect).
The next step is to create a project with "ng new", so I try to do that, but it fails with a weird error:
```
C:\temp\ngtest>ng new my-first-project
C:\Users\Mark\AppData\Roaming\npm\node_modules\@angular\cli\bin\ng:17
var version = process.versions.node.split('.').map(part => Number(part));
^^
SyntaxError: Unexpected token =>
at exports.runInThisContext (vm.js:73:16)
at Module._compile (module.js:443:25)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
at node.js:814:3
C:\temp\ngtest>
```
I really didn't expect a syntax error at this point, and I have no idea what to do about it.
Google didn't turn up any hits on this particular error, but several similar errors suggest tracking down package incompatibilities or dependencies. I have no idea how to do that, and I guess I thought the whole point of npm was to take care of stuff like that for me.
Help?
P.S. Just to establish a baseline, imagine a clever guy, decent programmer, who has been teleported from the year 2000 to 2020. Programming is still programming, of course - but the infrastructure is bewildering and frankly incomprehensible. There are at least a dozen layers of stuff that "everybody" knows so thoroughly that they don't even think about it any more. | 2020/04/13 | [
"https://Stackoverflow.com/questions/61183446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/470369/"
] | Use f strings:
```
print(f"Macro average precision : {precision_score(y_true, y_pred, average='macro')*100}%\n")
```
Or convert the value to string, and add (*concatenate*) the strings:
```
print('Macro average precision : ' + str(precision_score(y_true, y_pred, average='macro')*100) + "%\n")
```
See [the discussion here](https://stackoverflow.com/questions/59180574/string-concatenation-with-vs-f-string_) of the merits of each; basically the first is more convenient; and the second is computationally faster, and perhaps more simple to understand. | One of the ways to go about fixing this is by using string concatenation. You can add the percent symbol to your output from your function using a simple + operator. However, the output of your function needs to be cast to a string data type in order to be able to concatenate it with a string. To cast something to a string, use str()
So the correct way to fix your print statement using this explanation would be:
```
print('Macro average precision : ' + str(precision_score(y_true, y_pred, average='macro')*100) + "%\n")
``` |
33,542,666 | I have the following problem: My goal is to get two lines as a result at once. It's two times the same "select" statement, just with another ID. With my code I just get the second line. How is it possible to get both lines at once?
```
select
table1.attr1 + table2.attr2 as total,
table1.id
FROM table1, table2
WHERE table.id = 1 AND table2.id = 1;
select
table1.attr1 + table2.attr2 as total,
table1.id
FROM table1, table2
WHERE table.id = 2 AND table2.id = 2;
``` | 2015/11/05 | [
"https://Stackoverflow.com/questions/33542666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4183630/"
] | Use explicit `joins` with `on` clause:
```
select t1.attr1 + t2.attr2 as total
, t1.id
FROM table1 t1 join table2 t2 on t1.id = t2.id
WHERE t1.id in (1, 2)
``` | Modify your join condition:
```
SELECT
table1.attr1 + table2.attr2 as total,
table1.id
FROM table1, table2
WHERE (table.id = 1 AND table2.id = 1)
OR (table.id = 2 AND table2.id = 2)
``` |
16,910,108 | Anyone? please help me to figure this out. I'm getting an android.database.cursorindexoutofboundsexception error and I don't why. I'm sure that I name my columns correct but still I got it. What I am trying to do is just to get the companycode of the given company name.
Here my code my DatabaseAdapter
```
public Cursor getCompanyCode(String company)
{
Cursor c = dbSqlite.query(Constants.DATABASE_TABLE_COMPANY,
new String[] { Constants.DATABASE_COLUMN_ID,
Constants.COMPANY_CODE,Constants.COMPANY_NAME},
Constants.COMPANY_CODE+" = ?",
new String[]{company}, null, null, null);
if (c != null)
{
c.moveToFirst();
}
return c;
}
```
and here another code to get company code of the given company
```
Cursor companyCode = databaseAdapter.getCompanyCode(company);
code = companyCode.getString(companyCode.getColumnIndex(Constants.COMPANY_CODE));
```
and here is my logcat.
```
06-04 12:54:48.085: E/AndroidRuntime(27134): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.uni.customercare/com.uni.customercare.ViewSummaryActivity}: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
``` | 2013/06/04 | [
"https://Stackoverflow.com/questions/16910108",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2447165/"
] | Here you need to modify some css code.
```
#cssmenu > ul > li > a {
color: #A0A0A0;
font-family: Verdana,'Lucida Grande';
font-size: 15px;
/*line-height: 70px;
padding: 0;*/
position: relative;
top: 7px;
transition: color 0.15s ease 0s;
}
```
Demo: <http://jsfiddle.net/y5Fhc/8/> | anchor in not needed in the li of search box and I have added a class in the li of search box to make it center of the nav bar.
css
```
li.search{
line-height:40px;
}
```
html
```
<li class='active search'><span>
<form method="get" action="/search" id="advsearch">
<input name="q" type="text" size="40" placeholder="Search..." />
</form>
</li>
```
[jsFiddle File](http://jsfiddle.net/y5Fhc/7/) |
53,828,014 | I am using `spring-security-5`, `spring-boot 2.0.5` and `oauth2`. I have checked and test by online reference.
Like :
[Spring Security and OAuth2 to protect REST API endpoints](https://dzone.com/articles/spring-boot-2-applications-and-oauth-2-legacy-appr)
[Spring Boot 2 Applications and OAuth 2](https://dzone.com/articles/spring-boot-2-applications-and-oauth-2-legacy-appr)
Everything is fine in my project.
When I request this URL , `http://localhost:8080/api/oauth/token`, I get response as
[![enter image description here](https://i.stack.imgur.com/EskRN.png)](https://i.stack.imgur.com/EskRN.png)
**And I restart the server(Tomcat)**, I request that URL again, I get response as
[![enter image description here](https://i.stack.imgur.com/Wx8mz.png)](https://i.stack.imgur.com/Wx8mz.png)
So my question is, how the client-app can get `access_token` again after `Tomcat` or `spring-boot` application is **restart**?
**One thing**
For that kind of situation, if I delete the record of `OAUTH_CLIENT_DETAILS` table in database, It is OK to request again. I also get `access_token` again.
**Update**
Please don't miss understanding response `json` format, every response I wrap by custom object like as below.
```
{
"status": "SUCCESS", <-- here my custom
"data": {
"timestamp": "2018-12-18T07:17:00.776+0000", <-- actual response from oauth2
"status": 401, <-- actual response from oauth2
"error": "Unauthorized", <-- actual response from oauth2
"message": "Unauthorized", <-- actual response from oauth2
"path": "/api/oauth/token" <-- actual response from oauth2
}
}
```
**Update 2**
I use `JDBCTokenStore`, all of `oauth` information keep in database
```
package com.mutu.spring.rest.oauth2;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
static final String CLIEN_ID = "zto-api-client";
// static final String CLIENT_SECRET = "zto-api-client";
static final String CLIENT_SECRET = "$2a$04$HvD/aIuuta3B5DjXXzL08OSIcYEoFsAYK9Ys4fKpMNHTODZm.mzsq";
static final String GRANT_TYPE_PASSWORD = "password";
static final String AUTHORIZATION_CODE = "authorization_code";
static final String REFRESH_TOKEN = "refresh_token";
static final String IMPLICIT = "implicit";
static final String SCOPE_READ = "read";
static final String SCOPE_WRITE = "write";
static final String TRUST = "trust";
static final int ACCESS_TOKEN_VALIDITY_SECONDS = 1*60;
static final int FREFRESH_TOKEN_VALIDITY_SECONDS = 2*60;
@Autowired
private AuthenticationManager authenticationManager;
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Autowired
private DataSource dataSource;
@Bean
public TokenStore tokenStore() {
return new JdbcTokenStore(dataSource);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()");
}
@Override
public void configure(ClientDetailsServiceConfigurer configurer) throws Exception {
configurer
.jdbc(dataSource)
.withClient(CLIEN_ID)
.secret("{bcrypt}" + CLIENT_SECRET)
.authorizedGrantTypes(GRANT_TYPE_PASSWORD, AUTHORIZATION_CODE, REFRESH_TOKEN, IMPLICIT )
// .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
.scopes(SCOPE_READ, SCOPE_WRITE, TRUST)
.accessTokenValiditySeconds(ACCESS_TOKEN_VALIDITY_SECONDS)
.refreshTokenValiditySeconds(FREFRESH_TOKEN_VALIDITY_SECONDS);
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore())
.authenticationManager(authenticationManager);
}
}
``` | 2018/12/18 | [
"https://Stackoverflow.com/questions/53828014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1573835/"
] | Capabilities are options that you can use to customize and configure a ChromeDriver session.
The WebDriver language APIs provides ways to pass capabilities to ChromeDriver.
The exact mechanism differs by the language, but most languages use one or both of the following mechanisms:
1. Use the ChromeOptions class. This is supported by Java, Python, etc.
2. Use the DesiredCapabilities class. This is supported by Python,
Ruby, etc. While it is also available in Java, its usage in Java is deprecated.
for detail read this [Link](https://sites.google.com/a/chromium.org/chromedriver/capabilities) | chromeOptions - is used in Selenium to customize the Chrome browser (majorly in Java)
**Example:**
```
ChromeOptions options = new ChromeOptions();
driver = new ChromeDriver(options);
```
desiredCapablities - was used earlier in Selenium using Java (now its deprecated and not being used.
(now DesiredCapablities are used in Appium driver for Mobile Automation) |
53,828,014 | I am using `spring-security-5`, `spring-boot 2.0.5` and `oauth2`. I have checked and test by online reference.
Like :
[Spring Security and OAuth2 to protect REST API endpoints](https://dzone.com/articles/spring-boot-2-applications-and-oauth-2-legacy-appr)
[Spring Boot 2 Applications and OAuth 2](https://dzone.com/articles/spring-boot-2-applications-and-oauth-2-legacy-appr)
Everything is fine in my project.
When I request this URL , `http://localhost:8080/api/oauth/token`, I get response as
[![enter image description here](https://i.stack.imgur.com/EskRN.png)](https://i.stack.imgur.com/EskRN.png)
**And I restart the server(Tomcat)**, I request that URL again, I get response as
[![enter image description here](https://i.stack.imgur.com/Wx8mz.png)](https://i.stack.imgur.com/Wx8mz.png)
So my question is, how the client-app can get `access_token` again after `Tomcat` or `spring-boot` application is **restart**?
**One thing**
For that kind of situation, if I delete the record of `OAUTH_CLIENT_DETAILS` table in database, It is OK to request again. I also get `access_token` again.
**Update**
Please don't miss understanding response `json` format, every response I wrap by custom object like as below.
```
{
"status": "SUCCESS", <-- here my custom
"data": {
"timestamp": "2018-12-18T07:17:00.776+0000", <-- actual response from oauth2
"status": 401, <-- actual response from oauth2
"error": "Unauthorized", <-- actual response from oauth2
"message": "Unauthorized", <-- actual response from oauth2
"path": "/api/oauth/token" <-- actual response from oauth2
}
}
```
**Update 2**
I use `JDBCTokenStore`, all of `oauth` information keep in database
```
package com.mutu.spring.rest.oauth2;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
static final String CLIEN_ID = "zto-api-client";
// static final String CLIENT_SECRET = "zto-api-client";
static final String CLIENT_SECRET = "$2a$04$HvD/aIuuta3B5DjXXzL08OSIcYEoFsAYK9Ys4fKpMNHTODZm.mzsq";
static final String GRANT_TYPE_PASSWORD = "password";
static final String AUTHORIZATION_CODE = "authorization_code";
static final String REFRESH_TOKEN = "refresh_token";
static final String IMPLICIT = "implicit";
static final String SCOPE_READ = "read";
static final String SCOPE_WRITE = "write";
static final String TRUST = "trust";
static final int ACCESS_TOKEN_VALIDITY_SECONDS = 1*60;
static final int FREFRESH_TOKEN_VALIDITY_SECONDS = 2*60;
@Autowired
private AuthenticationManager authenticationManager;
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Autowired
private DataSource dataSource;
@Bean
public TokenStore tokenStore() {
return new JdbcTokenStore(dataSource);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()");
}
@Override
public void configure(ClientDetailsServiceConfigurer configurer) throws Exception {
configurer
.jdbc(dataSource)
.withClient(CLIEN_ID)
.secret("{bcrypt}" + CLIENT_SECRET)
.authorizedGrantTypes(GRANT_TYPE_PASSWORD, AUTHORIZATION_CODE, REFRESH_TOKEN, IMPLICIT )
// .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
.scopes(SCOPE_READ, SCOPE_WRITE, TRUST)
.accessTokenValiditySeconds(ACCESS_TOKEN_VALIDITY_SECONDS)
.refreshTokenValiditySeconds(FREFRESH_TOKEN_VALIDITY_SECONDS);
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore())
.authenticationManager(authenticationManager);
}
}
``` | 2018/12/18 | [
"https://Stackoverflow.com/questions/53828014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1573835/"
] | `ChromeOptions` class has introduced in the latest/updated version of Selenium. It is helpful to make changes in the Chrome browser whereas, `DesiredCapabilities` is an old concept (its usage in Java is deprecated.) to configure or make changes in the browser.
But we can use both `DesiredCapabilities` and `Chromeoptions` class via merge method. Pls find below code:
```
DesiredCapabilities cap = new DesiredCapabilities(); // instantiate DC Class
ChromeOptions options = new ChromeOptions(); // instantiate CO Class
options.merge(cap); // passing DC class object to CO Class
driver = new ChromeDriver(options);
``` | chromeOptions - is used in Selenium to customize the Chrome browser (majorly in Java)
**Example:**
```
ChromeOptions options = new ChromeOptions();
driver = new ChromeDriver(options);
```
desiredCapablities - was used earlier in Selenium using Java (now its deprecated and not being used.
(now DesiredCapablities are used in Appium driver for Mobile Automation) |
53,828,014 | I am using `spring-security-5`, `spring-boot 2.0.5` and `oauth2`. I have checked and test by online reference.
Like :
[Spring Security and OAuth2 to protect REST API endpoints](https://dzone.com/articles/spring-boot-2-applications-and-oauth-2-legacy-appr)
[Spring Boot 2 Applications and OAuth 2](https://dzone.com/articles/spring-boot-2-applications-and-oauth-2-legacy-appr)
Everything is fine in my project.
When I request this URL , `http://localhost:8080/api/oauth/token`, I get response as
[![enter image description here](https://i.stack.imgur.com/EskRN.png)](https://i.stack.imgur.com/EskRN.png)
**And I restart the server(Tomcat)**, I request that URL again, I get response as
[![enter image description here](https://i.stack.imgur.com/Wx8mz.png)](https://i.stack.imgur.com/Wx8mz.png)
So my question is, how the client-app can get `access_token` again after `Tomcat` or `spring-boot` application is **restart**?
**One thing**
For that kind of situation, if I delete the record of `OAUTH_CLIENT_DETAILS` table in database, It is OK to request again. I also get `access_token` again.
**Update**
Please don't miss understanding response `json` format, every response I wrap by custom object like as below.
```
{
"status": "SUCCESS", <-- here my custom
"data": {
"timestamp": "2018-12-18T07:17:00.776+0000", <-- actual response from oauth2
"status": 401, <-- actual response from oauth2
"error": "Unauthorized", <-- actual response from oauth2
"message": "Unauthorized", <-- actual response from oauth2
"path": "/api/oauth/token" <-- actual response from oauth2
}
}
```
**Update 2**
I use `JDBCTokenStore`, all of `oauth` information keep in database
```
package com.mutu.spring.rest.oauth2;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
static final String CLIEN_ID = "zto-api-client";
// static final String CLIENT_SECRET = "zto-api-client";
static final String CLIENT_SECRET = "$2a$04$HvD/aIuuta3B5DjXXzL08OSIcYEoFsAYK9Ys4fKpMNHTODZm.mzsq";
static final String GRANT_TYPE_PASSWORD = "password";
static final String AUTHORIZATION_CODE = "authorization_code";
static final String REFRESH_TOKEN = "refresh_token";
static final String IMPLICIT = "implicit";
static final String SCOPE_READ = "read";
static final String SCOPE_WRITE = "write";
static final String TRUST = "trust";
static final int ACCESS_TOKEN_VALIDITY_SECONDS = 1*60;
static final int FREFRESH_TOKEN_VALIDITY_SECONDS = 2*60;
@Autowired
private AuthenticationManager authenticationManager;
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Autowired
private DataSource dataSource;
@Bean
public TokenStore tokenStore() {
return new JdbcTokenStore(dataSource);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()");
}
@Override
public void configure(ClientDetailsServiceConfigurer configurer) throws Exception {
configurer
.jdbc(dataSource)
.withClient(CLIEN_ID)
.secret("{bcrypt}" + CLIENT_SECRET)
.authorizedGrantTypes(GRANT_TYPE_PASSWORD, AUTHORIZATION_CODE, REFRESH_TOKEN, IMPLICIT )
// .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
.scopes(SCOPE_READ, SCOPE_WRITE, TRUST)
.accessTokenValiditySeconds(ACCESS_TOKEN_VALIDITY_SECONDS)
.refreshTokenValiditySeconds(FREFRESH_TOKEN_VALIDITY_SECONDS);
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore())
.authenticationManager(authenticationManager);
}
}
``` | 2018/12/18 | [
"https://Stackoverflow.com/questions/53828014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1573835/"
] | `ChromeOptions` class has introduced in the latest/updated version of Selenium. It is helpful to make changes in the Chrome browser whereas, `DesiredCapabilities` is an old concept (its usage in Java is deprecated.) to configure or make changes in the browser.
But we can use both `DesiredCapabilities` and `Chromeoptions` class via merge method. Pls find below code:
```
DesiredCapabilities cap = new DesiredCapabilities(); // instantiate DC Class
ChromeOptions options = new ChromeOptions(); // instantiate CO Class
options.merge(cap); // passing DC class object to CO Class
driver = new ChromeDriver(options);
``` | Capabilities are options that you can use to customize and configure a ChromeDriver session.
The WebDriver language APIs provides ways to pass capabilities to ChromeDriver.
The exact mechanism differs by the language, but most languages use one or both of the following mechanisms:
1. Use the ChromeOptions class. This is supported by Java, Python, etc.
2. Use the DesiredCapabilities class. This is supported by Python,
Ruby, etc. While it is also available in Java, its usage in Java is deprecated.
for detail read this [Link](https://sites.google.com/a/chromium.org/chromedriver/capabilities) |
584,733 | The Linux log `/var/log/wtmp` according to the man page <http://linux.die.net/man/5/wtmp> stores "utmp" events for many system events, like logging into it (LOGIN\_PROCESS `ut_type`), changing runlevel (RUN\_LVL `ut_type`) and other.
There is `last` utility, which parses wtmp and prints who was logged into the system, and when it was rebooted.
Is there tool to display other records from `wtmp` log?
What is the process which writes info into `wtmp` log? | 2014/03/26 | [
"https://serverfault.com/questions/584733",
"https://serverfault.com",
"https://serverfault.com/users/24008/"
] | There are several simple perl parsers for wtmp files, like `wtmp.pl` by "Brocade Blue"
<http://brocadeblue.blogspot.com/2012/10/perl-script-to-parse-wtmp-logs.html>
Full source of `wtmp.pl` with minor typos fixed:
```
#!/usr/bin/perl
@type = (
"Empty", "Run Lvl", "Boot", "New Time", "Old Time", "Init",
"Login", "Normal", "Term", "Account"
);
$recs = "";
while (<>) {
$recs .= $_;
}
foreach ( split( /(.{384})/s, $recs ) ) {
next if length($_) == 0 ;
my ( $type, $pid, $line, $inittab, $user, $host, $t1, $t2, $t3, $t4, $t5 ) =
$_ =~ /(.{4})(.{4})(.{32})(.{4})(.{32})(.{256})(.{4})(.{4})(.{4})(.{4})(.{4})/s;
if ( defined $line && $line =~ /\w/ ) { ##FILTER
$line =~ s/\x00+//g;
$host =~ s/\x00+//g;
$user =~ s/\x00+//g;
printf(
"%s %-8s %-12s %10s %-45s \n",
scalar( gmtime( unpack( "I4", $t3 ) ) ),
$type[ unpack( "I4", $type ) ],
$user, $line, $host
);
}
}
printf "\n"
```
The script may not work on 64-bit machines. The "384" and long line with `(.{4})` should be fixed for 64-bit environment.
PS: to see really all records, disable the expression in the `if` marked with "`##FILTER`". | You should look at the audit log instead.
Try using `ausearch`, it offers what `utmp` does and more. |
1,845,669 | In Struts 1 you could have, in struts-config.xml, a declaration like:
```
<action path="/first" forward="/second.do">
```
Is something similar also possible in Spring, or can I map an URL only to a controller? I am using Spring 2.5.x.
I could off course map the URL to the same controller as:
```
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/first.do">theController</prop>
<prop key="/second.do">theController</prop>
...
```
Or maybe use the `org.springframework.web.servlet.mvc.ParameterizableViewController` and have something like:
```
<bean id="theDummyController" class="org.springframework.web.servlet.mvc.ParameterizableViewController">
<property name="viewName" value="forward:second.do"/>
</bean>
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/first.do">theDummyController</prop>
<prop key="/second.do">theController</prop>
...
```
I know I could be complicating things and I should just stick to the simple stuff that gets the job done, but I would like this to be more like a statement of the kind: "this URL is in fact a shortcut (or alias) to this other URL" (don't ask why... long story...) which is somehow visible with the `ParameterizableViewController` but not completely.
So, is this possible?
Thank you! | 2009/12/04 | [
"https://Stackoverflow.com/questions/1845669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I finally ended up creating a separate URL handler mapping where I grouped together the URL aliases. I then resorted to a very detailed description of what the contained mappings are all about, something like:
```
<bean id="aliasUrlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<description>
<![CDATA[
The following URLs are in fact shortcuts (or aliases)
to other URLs etc etc (...I'll spare you the ugly part)
]]>
</description>
<property name="mappings">
<props>
<prop key="/first.do">theController</prop>
...
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/second.do">theController</prop>
...
``` | I'm not familiar enough with Spring MVC to know the easiest way to do what you want there. However, the [UrlRewriteFilter project](http://tuckey.org/urlrewrite/) makes it easy to setup rules to forward one url to another url. |
1,845,669 | In Struts 1 you could have, in struts-config.xml, a declaration like:
```
<action path="/first" forward="/second.do">
```
Is something similar also possible in Spring, or can I map an URL only to a controller? I am using Spring 2.5.x.
I could off course map the URL to the same controller as:
```
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/first.do">theController</prop>
<prop key="/second.do">theController</prop>
...
```
Or maybe use the `org.springframework.web.servlet.mvc.ParameterizableViewController` and have something like:
```
<bean id="theDummyController" class="org.springframework.web.servlet.mvc.ParameterizableViewController">
<property name="viewName" value="forward:second.do"/>
</bean>
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/first.do">theDummyController</prop>
<prop key="/second.do">theController</prop>
...
```
I know I could be complicating things and I should just stick to the simple stuff that gets the job done, but I would like this to be more like a statement of the kind: "this URL is in fact a shortcut (or alias) to this other URL" (don't ask why... long story...) which is somehow visible with the `ParameterizableViewController` but not completely.
So, is this possible?
Thank you! | 2009/12/04 | [
"https://Stackoverflow.com/questions/1845669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I finally ended up creating a separate URL handler mapping where I grouped together the URL aliases. I then resorted to a very detailed description of what the contained mappings are all about, something like:
```
<bean id="aliasUrlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<description>
<![CDATA[
The following URLs are in fact shortcuts (or aliases)
to other URLs etc etc (...I'll spare you the ugly part)
]]>
</description>
<property name="mappings">
<props>
<prop key="/first.do">theController</prop>
...
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/second.do">theController</prop>
...
``` | You could make something easily that allows you to specify "this URL is in fact a shortcut (or alias) to this other URL" by implementing [HandlerInterceptor](http://static.springsource.org/spring/docs/2.5.x/reference/mvc.html#mvc-handlermapping-interceptor) and have your implementation contain a property that is map of URLs that should redirect, or forward, to other URLs.
In your XML you just add a bean for this interceptor, and configure it which URLs should redirect to what, and add a reference to the interceptor to the SimpleUrlHandlerMapping's interceptors property. |
1,845,669 | In Struts 1 you could have, in struts-config.xml, a declaration like:
```
<action path="/first" forward="/second.do">
```
Is something similar also possible in Spring, or can I map an URL only to a controller? I am using Spring 2.5.x.
I could off course map the URL to the same controller as:
```
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/first.do">theController</prop>
<prop key="/second.do">theController</prop>
...
```
Or maybe use the `org.springframework.web.servlet.mvc.ParameterizableViewController` and have something like:
```
<bean id="theDummyController" class="org.springframework.web.servlet.mvc.ParameterizableViewController">
<property name="viewName" value="forward:second.do"/>
</bean>
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/first.do">theDummyController</prop>
<prop key="/second.do">theController</prop>
...
```
I know I could be complicating things and I should just stick to the simple stuff that gets the job done, but I would like this to be more like a statement of the kind: "this URL is in fact a shortcut (or alias) to this other URL" (don't ask why... long story...) which is somehow visible with the `ParameterizableViewController` but not completely.
So, is this possible?
Thank you! | 2009/12/04 | [
"https://Stackoverflow.com/questions/1845669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I finally ended up creating a separate URL handler mapping where I grouped together the URL aliases. I then resorted to a very detailed description of what the contained mappings are all about, something like:
```
<bean id="aliasUrlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<description>
<![CDATA[
The following URLs are in fact shortcuts (or aliases)
to other URLs etc etc (...I'll spare you the ugly part)
]]>
</description>
<property name="mappings">
<props>
<prop key="/first.do">theController</prop>
...
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/second.do">theController</prop>
...
``` | I would recommend managing the URL-based rules outside the Spring config files? Keep the Spring config files clean and rewrite/manage your URLs outside. Have a look at <http://tuckey.org/urlrewrite/>.
I hope it helps,
-florin |
66,245,620 | I have a table that looks something like this:
```
Agency Year Total PopGroup
01 2017 3467 3C
01 2018 3444 3C
01 2019 3567 3C
02 2017 1000 1C
02 2018 1354 1C
02 2019 1333 1C
03 2017 6784 2C
03 2018 3453 2C
04 2017 3333 2C
```
If an agency has a row for year 2019, I want to duplicate this row and call it 2020 (basically, an estimate population for 2020). Desired result:
```
Agency Year Total PopGroup
01 2017 3467 3C
01 2018 3444 3C
01 2019 3567 3C
01 2020 3567 3C
02 2017 1000 1C
02 2018 1354 1C
02 2019 1333 1C
02 2020 1333 1C
03 2017 6784 2C
03 2018 3453 2C
04 2017 3333 2C
```
I think I should use something like:
```
INSERT INTO table
WHERE Year = 2019
```
but I'm a little stuck. What can I try next? | 2021/02/17 | [
"https://Stackoverflow.com/questions/66245620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5875276/"
] | In your Execute SQL Task, use a stored procedure like below :
```
IF OBJECT_ID('dbo.Testtable', 'U') IS NOT NULL
DROP TABLE dbo.Testtable;
DECLARE @sqlCommand varchar(1000)
DECLARE @columnList varchar(100)
DECLARE @table varchar(75)
DECLARE @sqldisplay varchar(1000)
SET @columnList = (SELECT SUBSTRING(Query_Column, CHARINDEX('SELECT', Query_Column) +6
, CHARINDEX('FROM',Query_Column) - CHARINDEX('SELECT', Query_Column) - Len('FROM')-2)
FROM dbo.Mytab)
SET @table = (SELECT SUBSTRING(Query_Column, CHARINDEX('FROM',Query_Column) + LEN('FROM'), LEN(Query_Column))
FROM dbo.Mytab)
SET @sqlCommand = 'SELECT' +@columnlist + 'INTO dbo.Testtable FROM' + @table
SET @sqldisplay = 'SELECT * FROM dbo.Testtable'
EXEC (@sqlCommand)
EXEC (@sqldisplay)
``` | I advise you to use "Execute SQL Task" instead of "Data Flow Task".
In this component you can use an SQL Query.
Please find below a sample of query to do the stuff :
```
declare @query varchar(1000);
select @query = [Query_Column] FROM Test where ID = 1 ;
set @query = concat(@query,' into temp_table');
exec(@query)
```
after that you have can :
* create a data flow from temp\_table
or
* enrich the sql query above to feed the expected table from temp\_table
[![enter image description here](https://i.stack.imgur.com/tFIvz.png)](https://i.stack.imgur.com/tFIvz.png) |
20,098,713 | I am getting this error when trying to run my project on localhost
**Exception Details: System.Web.HttpException: A page can have only one server-side Form tag**
This is my `ASP.NET` form
```
<form id="consultationform" runat="server">
<%-- Consultation --%>
<%-- Name --%>
<asp:Label ID="namelabel" runat="server" Text="Name"></asp:Label>
<asp:TextBox ID="namebox" runat="server"></asp:TextBox><br />
<%-- email --%>
<asp:Label ID="emaillabel" runat="server" Text="Email"></asp:Label>
<asp:TextBox ID="emailbox" runat="server"></asp:TextBox><br />
<%-- restaurant --%>
<asp:Label ID="restaurantlabel" runat="server" Text="Restaurant"></asp:Label>
<asp:TextBox ID="restaurantbox" runat="server"></asp:TextBox><br />
<%-- Address --%>
<asp:Label ID="addresslabel" runat="server" Text="Address"></asp:Label>
<asp:TextBox ID="addressbox1" runat="server"></asp:TextBox><br />
<asp:TextBox ID="addressbox2" runat="server"></asp:TextBox><br />
<asp:TextBox ID="addressbox3" runat="server"></asp:TextBox><br />
<%-- County --%>
<asp:Label ID="countylabel" runat="server" Text="County"></asp:Label>
<asp:DropDownList ID="countrydropdown" runat="server"
DataSourceID="CountySqlDataSource" DataTextField="CountyName"
DataValueField="CountyName" AppendDataBoundItems="True" AutoPostBack="True">
<asp:ListItem Value="" Text="Select a County"></asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="CountySqlDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [CountyName] FROM [Counties]"></asp:SqlDataSource>
<br />
<%-- Telephone --%>
<asp:Label ID="telephonelabel" runat="server" Text="Telephone"></asp:Label>
<asp:TextBox ID="telephonebox" runat="server"></asp:TextBox><br />
<%-- Calendar --%>
<asp:Label ID="datelabel" runat="server" Text="Date (What suits you?)"></asp:Label><asp:Calendar
ID="Calendar1" runat="server"></asp:Calendar><br />
<%-- Additional Info --%>
<asp:Label ID="infolabel" runat="server" Text="Additional Information (That may help us further)"></asp:Label><br />
<asp:TextBox ID="infobox" runat="server"></asp:TextBox><br />
<%-- Menu Upload --%>
<asp:Label ID="menulabel" runat="server" Text="Menu"></asp:Label><asp:FileUpload
ID="FileUpload1" runat="server" /><br />
<%-- Book Button --%>
<asp:Button ID="bookbtn" runat="server" Text="Book Now" />
</form>
```
I don't understand why it is happening. I only have one form tag on the page. Any help on the matter is much appreciated.
Should note, page renders completely fine if I remove the `form` tag. | 2013/11/20 | [
"https://Stackoverflow.com/questions/20098713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1732515/"
] | If you are using a masterpage, remove the form from your webform and inside the masterpage form add a content placeholder.
Use that content placeholder within your webforms like you were trying to use the form.
You may need to click the little arrow to the right of the content placeholder in the form in order to enable it. | in your master page, you should have at least:
```
<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site1.master.cs"Inherits="WebApplication1.Site1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
```
you can then remove all other form tags from your project, beacuse the master has one in use.
remember to add content pages properly also, in the body, contentplaceholder. |
43,910 | Article 1, paragraph 2 of the United Nations charter allows for the right of self-determination.
>
> 2. To develop friendly relations among nations based on respect for the principle of equal rights and self-determination of peoples, and to take other appropriate measures to strengthen universal peace;
>
>
>
The [wikipedia](https://en.wikipedia.org/wiki/Self-determination#Current_issues) article on self determination lists a number of issues around the definition of self-determination and its conflicts with territorial integrity, local constitutions and so on.
Practically today there are a number of secessionist movements such as Catalan, Scotland, Puerto Rico and Quebec. Are there any United Nations backed groups, or other international groups, working on dealing with the issues highlighted by these movements and the others listed on wikipedia and elsewhere to try to provide a structure or framework for peaceful expression of self-determination and secession from recognised sovereign states?
A full framing of rules for self-determination would also require addressing scenarios where a people wish to join another state. Real world examples would include Puerto Rico, Northern Ireland/RoI and topically (tongue in cheek) Greenland. | 2019/08/22 | [
"https://politics.stackexchange.com/questions/43910",
"https://politics.stackexchange.com",
"https://politics.stackexchange.com/users/18367/"
] | Decolonization is part of the self-assigned [goals](https://www.un.org/en/global-issues/decolonization) of United Nations. The Declaration on the Granting of Independence to Colonial Countries and Peoples was adopted by UN General Assembly in [1960](https://www.refworld.org/docid/3b00f06e2f.html).
The United Nations keeps an official [list](https://www.un.org/dppa/decolonization/en/nsgt) of Non-Self-Governing Territories, currently including 17 territories for a total population of circa 2 million. None of the territories mentioned in the OP (Quebec, Catalonia...) are considered as Non-Self-Governing Territories by the UN, but for instance the US Virgin Islands, Gibraltar and French Polynesia are.
UN also includes a Special Committee on Decolonization. According to [Wikipedia](https://en.wikipedia.org/wiki/Special_Committee_on_Decolonization):
>
> In a June 2016 report, the Special Committee called for the United States to expedite the process to allow self-determination in Puerto Rico.
>
>
>
The Secretary General also supports efforts toward decolonization of such territories. For instance, [here](https://www.un.org/press/en/2019/sgsm19467.doc.htm) is a speech of current SG Antonio Guterres where he notably rejoices that
>
> Last November, in a referendum, New Caledonians expressed their will on their future and on the status of the Territory. This was an important step forward in the decolonization process.
>
>
> | Within Europe there is the FUEN - the Federal Union of European Nationalities (<https://www.fuen.org>), an umbrella organisation of the autochthonous, national minorities / ethnic groups in Europe. They include among others the Catalans, South-Tyrolean Germans, Szekelys (Hungarians) of Transylvania, etc. They are the pan-european civil society representative of European minorities advocating language rights and other issues related to self-determination. |
43,020,433 | I want to populate a textbox on a form using VBA. I want it to first open the form, then go to a New record and then populate a textbox on that New record.
```
Private Sub btn_AddAccount()
DoCmd.OpenForm "tbl_MonitorAccounts", , , , acFormAdd, acDialog, NewData
DoCmd.GoToRecord , , acNewRec
Me.MonitorAccount = "FUNC00265"
End Sub
```
Please help me because the code above does not work unfortunately.
Edit: I think it has to do something with that the field is bound. Is it possible to populate bound records using VBA? | 2017/03/25 | [
"https://Stackoverflow.com/questions/43020433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6848927/"
] | For your first question, it means that `x` of shape (2, 3, 1) has 2 slices of `3x1` arrays.
```
In [40]: x
Out[40]:
array([[[1],
[2], # <= slice 1 of shape 3x1
[3]],
[[4],
[5], # <= slice 2 of shape 3x1
[6]]])
```
Now, when you execute `x[1:2]`, it just hands you over the first slice but not including the second slice since in Python & NumPy it's always left inclusive and right exclusive (something like half-open interval, i.e. [1,2) )
```
In [42]: x[1:2]
Out[42]:
array([[[4],
[5],
[6]]])
```
This is why you just get the first slice.
For your second question,
```
In [45]: x.ndim
Out[45]: 3
```
So, when you use ellipsis, it just stretches out your array to size 3.
```
In [47]: x[...,0]
Out[47]:
array([[1, 2, 3],
[4, 5, 6]])
```
The above code means, you take both slices from the array x, and stretch it row-wise.
But instead, if you do
```
In [49]: x[0, ..., 0]
Out[49]: array([1, 2, 3])
```
Here, you just take the first slice from `x` and stretch it row-wise. | Now, when you execute x[1:2], it just hands you over the **first slice**.
My question is shouldn't it be **second slice**. As the output is slice 2
```
In [42]: x[1:2]
Out[42]:
array([[[4],
[5],
[6]]])
``` |
14,060,125 | I have the following code in which data from a database's table is displayed in a table. But after 2-3 records, it is not displaying records properly.
This is the code:
```
<tr>
<?php do { ?>
<td> </td>
<td><?php echo $row_Recordset1['notification']; ?></td>
<td><?php echo $row_Recordset1['online_date']; ?></td>
<td> </td>
<td> </td>
</tr>
<?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
```
It generates the following output:
![My 3rs record's notification is empty, and 4th record is not displaying properly.](https://i.stack.imgur.com/hdkSA.jpg)
Row HTML Output is:
```
<form id="form1" name="form1" method="post" action="">
<table width="900" align="center" cellpadding="0" cellspacing="0">
<tr>
<td rowspan="6"> </td>
<td colspan="5"><div align="center">Active Notifications </div></td>
<td rowspan="6"> </td>
</tr>
<tr>
<td colspan="5"> </td>
</tr>
<tr>
<td>No.</td>
<td>Notifications</td>
<td>Online Date </td>
<td colspan="2">Transactions</td>
</tr>
<tr>
<td> </td>
<td>Our New destinations are Countries.</td>
<td>2012-12-27</td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td>abcdefgh</td>
<td>2012-12-27</td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td>Hi</td>
<td>2012-12-27</td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td>hello</td>
<td>2012-12-27</td>
<td> </td>
<td> </td>
</tr>
<tr>
<td colspan="5"> </td>
</tr>
<tr>
<td> </td>
</tr>
</table>
</form>
``` | 2012/12/27 | [
"https://Stackoverflow.com/questions/14060125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1624583/"
] | your `<tr>` tag is outside of the loop, while the closing one is inside. | What do you mean by not being displayed correctly? from html point of view or data point of view? If from html point of view, you are opening the tr outside the loop, however you are closing it inside the loop. Basicly your structure would look like: `tr td td td td /tr td td td td /tr` instead of `tr td td td td /tr tr td td td td \tr` |
14,060,125 | I have the following code in which data from a database's table is displayed in a table. But after 2-3 records, it is not displaying records properly.
This is the code:
```
<tr>
<?php do { ?>
<td> </td>
<td><?php echo $row_Recordset1['notification']; ?></td>
<td><?php echo $row_Recordset1['online_date']; ?></td>
<td> </td>
<td> </td>
</tr>
<?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
```
It generates the following output:
![My 3rs record's notification is empty, and 4th record is not displaying properly.](https://i.stack.imgur.com/hdkSA.jpg)
Row HTML Output is:
```
<form id="form1" name="form1" method="post" action="">
<table width="900" align="center" cellpadding="0" cellspacing="0">
<tr>
<td rowspan="6"> </td>
<td colspan="5"><div align="center">Active Notifications </div></td>
<td rowspan="6"> </td>
</tr>
<tr>
<td colspan="5"> </td>
</tr>
<tr>
<td>No.</td>
<td>Notifications</td>
<td>Online Date </td>
<td colspan="2">Transactions</td>
</tr>
<tr>
<td> </td>
<td>Our New destinations are Countries.</td>
<td>2012-12-27</td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td>abcdefgh</td>
<td>2012-12-27</td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td>Hi</td>
<td>2012-12-27</td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td>hello</td>
<td>2012-12-27</td>
<td> </td>
<td> </td>
</tr>
<tr>
<td colspan="5"> </td>
</tr>
<tr>
<td> </td>
</tr>
</table>
</form>
``` | 2012/12/27 | [
"https://Stackoverflow.com/questions/14060125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1624583/"
] | First, I'm thinking your loop should be a plain `while` loop instead of a `do ... while`, unless you have some code earlier on that is getting the first record.
Second, your `<tr>` tag was outside the loop and it should be inside it:
```
<?php while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)) { ?>
<tr>
<td> </td>
<td><?php echo $row_Recordset1['notification']; ?></td>
<td><?php echo $row_Recordset1['online_date']; ?></td>
<td> </td>
<td> </td>
</tr>
<?php } ?>
``` | What do you mean by not being displayed correctly? from html point of view or data point of view? If from html point of view, you are opening the tr outside the loop, however you are closing it inside the loop. Basicly your structure would look like: `tr td td td td /tr td td td td /tr` instead of `tr td td td td /tr tr td td td td \tr` |
23,644,062 | I have here two select boxes. The process is like this <http://www.w3schools.com/ajax/ajax_database.asp>. What I need to display only the value between the two select boxes. How I can do that in one function? Any help will appreciate.
```
<script>
function showUser(str) {
var $txtHint = $('#txtHint');
if (str=="") {
$txtHint.html('');
return;
}
$txtHint.load('ajax.php?q='+str)
}
</script>
<select name="customers" id="customers" onchange="showUser(this.value)">
<option value="">Select a customer:</option>
<option value="ALFKI">Alfreds Futterkiste</option>
<option value="NORTS ">North/South</option>
<option value="WOLZA">Wolski Zajazd</option>
</select>
<select name="city" class="city">
<option selected="selected">--Select City--</option>
</select>
``` | 2014/05/14 | [
"https://Stackoverflow.com/questions/23644062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3631428/"
] | First, take the function that you're calling inside `change()`, and declare it separately. Then, call `.change()` on that function twice.
E.g.
```
$(document).ready(function() {
var myChangeFunction = function() {
var city = $(".city").val();
var customer = $("#customer").val();
if (city && customer) {
// do something only if both are set
}
};
$(".city").change(myChangeFunction);
$("#customer").change(myChangeFunction);
});
``` | I think I understood what you need.
You need both selects to call the same function onchange.
That function will get some info, and load it. You need it to load it in different places regarding which was the select that changed.
If that's what you need, check this fiddle:
<http://jsfiddle.net/hige/4878B/>
Remember to uncomment the .load() line, and delete the `console.log()` one.
Hope it helps! |
51,682,434 | I am using jQuery to add/remove more `div`. Here is my code:
**jQuer Code:**
```
$(document).ready(function() {
$('#oneway').click(function() {
$('.oneway_wrap').show();
$('.return_wrap').hide();
});
});
// Add/remove code
var counting = 0;
$("body").on("click",".add_button",function(){
// this is not the correct way to increment... :(
$('.counting').html(counting);
var html = $(".oneway_wrap").first().clone();
$(html).find(".change").html("<a class='btn btn-danger remove remove_more'>- Remove</a> <button class='btn add_button add_more'><strong>Add More (+)</strong></button>");
$(".oneway_wrap").last().after(html);
counting++;
});
```
**HTML Code:**
```
<!-- oneway wrap -->
<div class="oneway_wrap">
<div class="row">
<div class="form-group">
<div class="col-md-12">
<h5 class="badge badge-success counting">Details 1</h5><hr><br/>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Guest Name</label>
<input type="text" name="ow_gname[]" class="form-control" placeholder="Guest name">
</div>
</div>
<div class="col-md-12">
<div class="form-group change">
<a class="btn add_button add_more"><strong>Add More (+)</strong></a>
</div>
</div>
</div>
</div><!-- oneway wrap end -->
<!-- return wrap -->
<div class="return_wrap">
<!-- same html code here... for retrun way with return classes -->
</div><!-- return wrap end -->
```
This add/remove is working fine. **Now I want to show the number of rows added or removed in this class(counting)**
```
<h5 class="badge badge-success counting">Details 1</h5><hr><br/>
```
**So, If 2 extra row added then it will be `Details 2, Details 3...`**
In jQuery I am using this: `$('.counting').html(counting);` But I don't think it's a correct way and the result is always the same.
I mean, If 2 extra row added then the counting is showing Details 2, Details 2 but should be Details 2, Details 3, Details 4...
How can I do this? | 2018/08/04 | [
"https://Stackoverflow.com/questions/51682434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1091439/"
] | you can generate the innerHTML like this
```
$("body").on("click",".add_button",function(){
var html = $(".oneway_wrap").first().clone();
$(html).find(".change").html("<a class='btn btn-danger remove remove_more'>- Remove</a> <button class='btn add_button add_more'><strong>Add More (+)</strong></button>");
$(".oneway_wrap").last().after(html);
$('.counting').each(function(i, elm) {
$(elm).text('Detail ' + (i + 1));
});
});
``` | you can use .length to count rows. please see following code snippet.
```
var counting = 0;
$("body").on("click",".add_button",function(){
// Now i think this is proper way to count rows :(
$('.counting').html("Details "+$(document).find(".row").length);
var html = $(".oneway_wrap").first().clone();
$(html).find(".change").html("<a class='btn btn-danger remove remove_more'>- Remove</a> <button class='btn add_button add_more'><strong>Add More (+)</strong></button>");
$(".oneway_wrap").last().after(html);
counting++;
});
``` |
37,935,366 | I have csv, with a lot of column,
```
+---------+------------------+
| NAME | ADDRESS |
+---------+------------------+
| JOHN | ADDRESS 1 |
| MARY | ADDRESS 2 |
+---------+------------------+
```
And this one will be uploaded to the web app. My question is, I want to store the name of file in additional column (last column in each row.)
```
+---------+------------------+-------------+
| NAME | ADDRESS | NAME FILE |
+---------+------------------+-------------|
| JOHN | ADDRESS 1 | MAIN.CSV |
| MARY | ADDRESS 2 | MAIN.CSV |
+---------+------------------+-------------+
```
This is my code :
```
$csv = $this->input->post('path'); //PATH CSV
$nama_file = $this->input->post('nama'); // NAME OF FILE
$tryOne = array();
if (file_exists($csv)) {
$file = fopen($csv, 'r'); // r flag is for readonly mode
fgetcsv($file, 1000, ",");
while (( $line = fgetcsv($file) ) !== false) { // if line exists
$tryOne[] = $line; // add to array
}
fclose($file);
}
```
THE RESULT LIKE THIS
```
Array
(
[0] => Array
(
[0] => JOHN
[1] => ADDRESS 1
)
[1] => Array
(
[0] => MARY
[1] => ADDRESS 2
)
)
```
Any help it so appreciated. | 2016/06/21 | [
"https://Stackoverflow.com/questions/37935366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4452417/"
] | As explained in [this answer](https://stackoverflow.com/questions/16321193/date-change-when-converting-from-xmlgregoriancalendar-to-calendar), your calendar is being shifted because you have specified your year as `1`, meaning that this falls out of the `GregorianCalendar` and into the Julian Calendar, which `XMLGregorianCalendar` does not support.
Simply use `xmlC.setYear(2016);` to fix this. | try this into your code
```
XMLGregorianCalendar xmlC;
Calendar cal=Calendar.getInstance();
try {
xmlC = DatatypeFactory.newInstance().newXMLGregorianCalendar();
xmlC.setYear(cal.get(Calendar.YEAR));
....
``` |
19,912,187 | I'm getting the following javascript error on all a4j:commandlink on our site. This error only occurred on IE 10. No problem with IE 8 / 9.
Message: Object doesn't support property or method 'setProperty'
Line: 6
Char: 148
Code: 0
URI: <http://localhost.com:9082/a4j_3_1_6.GAorg.ajax4jsf.javascript.AjaxScript.jsf>
I can't be sure but the following appears to be the statement in error:
oDoc.setProperty("SelectionLanguage","XPath")
and oDoc appears to be created thru this statemetn: oDoc=new ActiveXObject(idList[i]
Anyone having the same problem? | 2013/11/11 | [
"https://Stackoverflow.com/questions/19912187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2187053/"
] | Below is what I did to resolve this issue:
1) Download sarissa-full-0.9.9.6.zip from <http://sourceforge.net/projects/sarissa/>
2) Find the sarissa.js file in sarissa-full-0.9.9.6.zip and open it with wordpad.
3) Find the AJAX.js file in richfaces-impl-3.1.6.GA.jar and open it with wordpad.
4) Within AJAX.js, there is a section of code that is really a copy of old version of sarissa.js. This section of code starts and ends like below:
/\*\*
\* ====================================================================
\* About
\* ====================================================================
\* Sarissa is an ECMAScript library acting as a cross-browser wrapper for native XML APIs.
\* The library supports Gecko based browsers like Mozilla and Firefox,
\* Internet Explorer (5.5+ with MSXML3.0+), Konqueror, Safari and a little of Opera
\* @version ${project.version}
\* @author: Manos Batsis, mailto: mbatsis at users full stop sourceforge full stop net
. . . .
. . . .
. . . .
// EOF
5) Replace this entire section of sarissa code in AJAX.js with the codes in sarissa.js (see #2).
6) Now search for all texts in AJAX.js that start with \_SARISSA. Append Sarissa. in front of the text if it does not have one. For example: if(\_SARISSA\_IS\_IE){ should be changed to if(Sarissa.\_SARISSA\_IS\_IE){
7) Now replace below (see <http://sourceforge.net/p/sarissa/bugs/62/>):
Sarissa.\_SARISSA\_IS\_IE9 = Sarissa.\_SARISSA\_IS\_IE && navigator.userAgent.toLowerCase().indexOf("msie 9") > -1;
with
Sarissa.\_SARISSA\_IS\_IE9 = Sarissa.\_SARISSA\_IS\_IE && (navigator.userAgent.toLowerCase().indexOf("msie 9") > -1 || navigator.userAgent.toLowerCase().indexOf("msie 10") > -1 || document.documentMode >= 9);
8) Save and replace this newly updated AJAX.js into richfaces-impl-3.1.6.GA.jar.
9) Now you are ready to test it out. Note: For some odd reason, for IE10 to take the newly updated AJAX.js, I've to access the page and do a save as to save the enire html to my local. Once I did that the new AJAX.js starts to take effect. There is probably other way to refresh the cache but this is the one that works for me. | I also had to delete the following row in the Ajax.js:
LOG.debug("Hidden JSF state fields: "+idsSpan); |
2,564,767 | Firstly, This might seem like a long question. I don't think it is... The code is just an overview of what I'm currently doing. It doesn't feel right, so I am looking for constructive criticism and warnings for pitfalls and suggestions of what I can do.
I have a database with business objects.
I need to access properties of parent objects.
I need to maintain some sort of state through business objects.
If you look at the classes, I don't think that the access modifiers are right. I don't think its structured very well. Most of the relationships are modelled with public properties. SubAccount.Account.User.ID <-- all of those are public..
Is there a better way to model a relationship between classes than this so it's not so "public"?
The other part of this question is about resources:
If I was to make a User.GetUserList() function that returns a List, and I had 9000 users, when I call the GetUsers method, it will make 9000 User objects and inside that it will make 9000 new AccountCollection objects. What can I do to make this project not so resource hungry?
Please find the code below and rip it to shreds.
```
public class User {
public string ID {get;set;}
public string FirstName {get; set;}
public string LastName {get; set;}
public string PhoneNo {get; set;}
public AccountCollection accounts {get; set;}
public User {
accounts = new AccountCollection(this);
}
public static List<Users> GetUsers() {
return Data.GetUsers();
}
}
public AccountCollection : IEnumerable<Account> {
private User user;
public AccountCollection(User user) {
this.user = user;
}
public IEnumerable<Account> GetEnumerator() {
return Data.GetAccounts(user);
}
}
public class Account {
public User User {get; set;} //This is public so that the subaccount can access its Account's User's ID
public int ID;
public string Name;
public Account(User user) {
this.user = user;
}
}
public SubAccountCollection : IEnumerable<SubAccount> {
public Account account {get; set;}
public SubAccountCollection(Account account) {
this.account = account;
}
public IEnumerable<SubAccount> GetEnumerator() {
return Data.GetSubAccounts(account);
}
}
public class SubAccount {
public Account account {get; set;} //this is public so that my Data class can access the account, to get the account's user's ID.
public SubAccount(Account account) {
this.account = account;
}
public Report GenerateReport() {
Data.GetReport(this);
}
}
public static class Data {
public static List<Account> GetSubAccounts(Account account) {
using (var dc = new databaseDataContext()) {
List<SubAccount> query = (from a in dc.Accounts
where a.UserID == account.User.ID //this is getting the account's user's ID
select new SubAccount(account) {
ID = a.ID,
Name = a.Name,
}).ToList();
}
}
public static List<Account> GetAccounts(User user) {
using (var dc = new databaseDataContext()) {
List<Account> query = (from a in dc.Accounts
where a.UserID == User.ID //this is getting the user's ID
select new Account(user) {
ID = a.ID,
Name = a.Name,
}).ToList();
}
}
public static Report GetReport(SubAccount subAccount) {
Report report = new Report();
//database access code here
//need to get the user id of the subaccount's account for data querying.
//i've got the subaccount, but how should i get the user id.
//i would imagine something like this:
int accountID = subAccount.Account.User.ID;
//but this would require the subaccount's Account property to be public.
//i do not want this to be accessible from my other project (UI).
//reading up on internal seems to do the trick, but within my code it still feels
//public. I could restrict the property to read, and only private set.
return report;
}
public static List<User> GetUsers() {
using (var dc = new databaseDataContext()) {
var query = (from u in dc.Users
select new User {
ID = u.ID,
FirstName = u.FirstName,
LastName = u.LastName,
PhoneNo = u.PhoneNo
}).ToList();
return query;
}
}
}
``` | 2010/04/02 | [
"https://Stackoverflow.com/questions/2564767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/236476/"
] | This answer has ended up containing a lot of buzz word headings. Hopefully I explain each one and why it applies here. I think each concept I introduce below is worth considering - they aren't always applicable but I find they are all things I personally find valuable when I think about the structure of a system.
### Single Responsibility
Start by thinking about the responsibility of each object - what is its job? Generally you'll find a better design once you decide on a single job for each class. Currently a lot of your classes are doing too much, holding logic that should really exist as services.
The first example of the above is your User class:
```
public class User {
public string ID {get;set;}
public string FirstName {get; set;}
public string LastName {get; set;}
public string PhoneNo {get; set;}
public AccountCollection accounts {get; set;}
public User {
accounts = new AccountCollection(this);
}
public static List<Users> GetUsers() {
return Data.GetUsers();
}
}
```
Why does this provide a method that retrieves users from the data source? That functionality should be moved out into a users service.
Another key example of this is the GenerateReport method on the SubAccount - don't have your report generation logic so tightly tied to the SubAccount object. Splitting this out will give you more flexibility and reduce the change of changes to your SubAccount breaking the report logic.
### Lazy Loading
Again looking at your User class - why does it load all the users accounts on instantiation? Are these objects always going to be used every time you work with a User?
It would generally be better to introduce lazy loading - only retrieve an account when you need it. Of course there are times when you want eager loading (if you know you will want the object soon so want ot reduce database access) but you should be able to design for these exceptions.
### Dependency Injection
This sort of follows on from both the lazy loading point and the single responsibility point. You have a lot of hard coded references to things like your Data class. This is making your design more rigid - refactoring your data access to introduce lazy loading, or changing the way that user records is retrieve is much harder now that many classes are all directly accessing the data access logic.
### Digest objects
Hat tip to Cade Roux - I'd never heard the term Digest objects, usually called them light weight DTOs.
As Cade says, there is no reason to retrieve a rich list containing fully functioning user objects if all you are doing is displaying a combo box of user names that is bound to the unique ids.
Introduce a light weight user object that only stores the very basic user information.
This is again another reason to introduce a services/repository abstraction, and some sort of dependency injection. Changing the types of objects retreived from the data store becomes much easier when you have encapsulated your data retrieval away from your actual objects, and when you are not tightly bound to your data access implementation.
### Law of Demeter
Your objects know too much about the internal structure of each other. Allowing drill down through a User to the Accounts and then to the SubAccount is muddling the responsibility of each object. You are able to set sub account information from the user object when arguably you shouldn't be.
I always struggle with this principle, since drilling through the heirarchy seems very convenient. The problem is that it will stop you thinking proberly about the encapsulation and role of each object.
Perhaps don't expose your Account object from user - instead try introducing properties and methods that expose the relevant members of the Account object. Look at a GetAccount method instead of a Account property, so that you force yourself to work with an account object rather than treat it as a property of the User. | Lazy loading - do not make the AccountCollection objects inside the Users unless it is accessed. Alternatively, you can have it retrieve the account collections at the same time as the users and avoid 1 + 9000 database trips.
Have more selective collection retrieval methods (i.e. what are you going to do with 9000 users? If you need all their information, it's not so much of a waste).
Have smaller "digest" objects which are used for long lists like dropdowns and lookups - these objects are simple read-only business objects - usually containing only a small amout of information and which can be used to retrieve fully blown objects.
If you are doing pagination, is the list of users loaded once and stored in the web server and then paginated from the cached copy, or is the collection loaded every time from the database and pagination done by the control? |
2,564,767 | Firstly, This might seem like a long question. I don't think it is... The code is just an overview of what I'm currently doing. It doesn't feel right, so I am looking for constructive criticism and warnings for pitfalls and suggestions of what I can do.
I have a database with business objects.
I need to access properties of parent objects.
I need to maintain some sort of state through business objects.
If you look at the classes, I don't think that the access modifiers are right. I don't think its structured very well. Most of the relationships are modelled with public properties. SubAccount.Account.User.ID <-- all of those are public..
Is there a better way to model a relationship between classes than this so it's not so "public"?
The other part of this question is about resources:
If I was to make a User.GetUserList() function that returns a List, and I had 9000 users, when I call the GetUsers method, it will make 9000 User objects and inside that it will make 9000 new AccountCollection objects. What can I do to make this project not so resource hungry?
Please find the code below and rip it to shreds.
```
public class User {
public string ID {get;set;}
public string FirstName {get; set;}
public string LastName {get; set;}
public string PhoneNo {get; set;}
public AccountCollection accounts {get; set;}
public User {
accounts = new AccountCollection(this);
}
public static List<Users> GetUsers() {
return Data.GetUsers();
}
}
public AccountCollection : IEnumerable<Account> {
private User user;
public AccountCollection(User user) {
this.user = user;
}
public IEnumerable<Account> GetEnumerator() {
return Data.GetAccounts(user);
}
}
public class Account {
public User User {get; set;} //This is public so that the subaccount can access its Account's User's ID
public int ID;
public string Name;
public Account(User user) {
this.user = user;
}
}
public SubAccountCollection : IEnumerable<SubAccount> {
public Account account {get; set;}
public SubAccountCollection(Account account) {
this.account = account;
}
public IEnumerable<SubAccount> GetEnumerator() {
return Data.GetSubAccounts(account);
}
}
public class SubAccount {
public Account account {get; set;} //this is public so that my Data class can access the account, to get the account's user's ID.
public SubAccount(Account account) {
this.account = account;
}
public Report GenerateReport() {
Data.GetReport(this);
}
}
public static class Data {
public static List<Account> GetSubAccounts(Account account) {
using (var dc = new databaseDataContext()) {
List<SubAccount> query = (from a in dc.Accounts
where a.UserID == account.User.ID //this is getting the account's user's ID
select new SubAccount(account) {
ID = a.ID,
Name = a.Name,
}).ToList();
}
}
public static List<Account> GetAccounts(User user) {
using (var dc = new databaseDataContext()) {
List<Account> query = (from a in dc.Accounts
where a.UserID == User.ID //this is getting the user's ID
select new Account(user) {
ID = a.ID,
Name = a.Name,
}).ToList();
}
}
public static Report GetReport(SubAccount subAccount) {
Report report = new Report();
//database access code here
//need to get the user id of the subaccount's account for data querying.
//i've got the subaccount, but how should i get the user id.
//i would imagine something like this:
int accountID = subAccount.Account.User.ID;
//but this would require the subaccount's Account property to be public.
//i do not want this to be accessible from my other project (UI).
//reading up on internal seems to do the trick, but within my code it still feels
//public. I could restrict the property to read, and only private set.
return report;
}
public static List<User> GetUsers() {
using (var dc = new databaseDataContext()) {
var query = (from u in dc.Users
select new User {
ID = u.ID,
FirstName = u.FirstName,
LastName = u.LastName,
PhoneNo = u.PhoneNo
}).ToList();
return query;
}
}
}
``` | 2010/04/02 | [
"https://Stackoverflow.com/questions/2564767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/236476/"
] | Lazy loading - do not make the AccountCollection objects inside the Users unless it is accessed. Alternatively, you can have it retrieve the account collections at the same time as the users and avoid 1 + 9000 database trips.
Have more selective collection retrieval methods (i.e. what are you going to do with 9000 users? If you need all their information, it's not so much of a waste).
Have smaller "digest" objects which are used for long lists like dropdowns and lookups - these objects are simple read-only business objects - usually containing only a small amout of information and which can be used to retrieve fully blown objects.
If you are doing pagination, is the list of users loaded once and stored in the web server and then paginated from the cached copy, or is the collection loaded every time from the database and pagination done by the control? | Okay, just a quick comment on the code as you have it at the moment.
```
public class SubAccount {
public Account account {get; set;} //this is public so that my Data class can access the account, to get the account's user's ID.
public SubAccount(Account account) {
this.account = account;
}
[snip]
}
```
You don't even need a setter on the `Account` property if it is passed in on the ctor and then assigned to the backing field.
Setting a property by passing it on on the ctor can be a very good practice to follow, but it falls over if your data object is going to be serialized, i.e. if it is retrieved or sent to a web service - in this case you will need at least an `internal` setter on the `Account` property.
**Edit:** you can still use this DI type behaviour on the constructor, but the problem is that this constructor will not get called when the object is rehydrated from a serialized form (i.e. when it has been passed to/from a web service). So if you are going to use web services you will additionally need to have a parameterless constructor, and either a public or internal setter on the Account property (if you are going for an internal setter then you will also need to specify the `InternalsVisibleToAttribute` in your *AssemblyInfo.cs* file. |
2,564,767 | Firstly, This might seem like a long question. I don't think it is... The code is just an overview of what I'm currently doing. It doesn't feel right, so I am looking for constructive criticism and warnings for pitfalls and suggestions of what I can do.
I have a database with business objects.
I need to access properties of parent objects.
I need to maintain some sort of state through business objects.
If you look at the classes, I don't think that the access modifiers are right. I don't think its structured very well. Most of the relationships are modelled with public properties. SubAccount.Account.User.ID <-- all of those are public..
Is there a better way to model a relationship between classes than this so it's not so "public"?
The other part of this question is about resources:
If I was to make a User.GetUserList() function that returns a List, and I had 9000 users, when I call the GetUsers method, it will make 9000 User objects and inside that it will make 9000 new AccountCollection objects. What can I do to make this project not so resource hungry?
Please find the code below and rip it to shreds.
```
public class User {
public string ID {get;set;}
public string FirstName {get; set;}
public string LastName {get; set;}
public string PhoneNo {get; set;}
public AccountCollection accounts {get; set;}
public User {
accounts = new AccountCollection(this);
}
public static List<Users> GetUsers() {
return Data.GetUsers();
}
}
public AccountCollection : IEnumerable<Account> {
private User user;
public AccountCollection(User user) {
this.user = user;
}
public IEnumerable<Account> GetEnumerator() {
return Data.GetAccounts(user);
}
}
public class Account {
public User User {get; set;} //This is public so that the subaccount can access its Account's User's ID
public int ID;
public string Name;
public Account(User user) {
this.user = user;
}
}
public SubAccountCollection : IEnumerable<SubAccount> {
public Account account {get; set;}
public SubAccountCollection(Account account) {
this.account = account;
}
public IEnumerable<SubAccount> GetEnumerator() {
return Data.GetSubAccounts(account);
}
}
public class SubAccount {
public Account account {get; set;} //this is public so that my Data class can access the account, to get the account's user's ID.
public SubAccount(Account account) {
this.account = account;
}
public Report GenerateReport() {
Data.GetReport(this);
}
}
public static class Data {
public static List<Account> GetSubAccounts(Account account) {
using (var dc = new databaseDataContext()) {
List<SubAccount> query = (from a in dc.Accounts
where a.UserID == account.User.ID //this is getting the account's user's ID
select new SubAccount(account) {
ID = a.ID,
Name = a.Name,
}).ToList();
}
}
public static List<Account> GetAccounts(User user) {
using (var dc = new databaseDataContext()) {
List<Account> query = (from a in dc.Accounts
where a.UserID == User.ID //this is getting the user's ID
select new Account(user) {
ID = a.ID,
Name = a.Name,
}).ToList();
}
}
public static Report GetReport(SubAccount subAccount) {
Report report = new Report();
//database access code here
//need to get the user id of the subaccount's account for data querying.
//i've got the subaccount, but how should i get the user id.
//i would imagine something like this:
int accountID = subAccount.Account.User.ID;
//but this would require the subaccount's Account property to be public.
//i do not want this to be accessible from my other project (UI).
//reading up on internal seems to do the trick, but within my code it still feels
//public. I could restrict the property to read, and only private set.
return report;
}
public static List<User> GetUsers() {
using (var dc = new databaseDataContext()) {
var query = (from u in dc.Users
select new User {
ID = u.ID,
FirstName = u.FirstName,
LastName = u.LastName,
PhoneNo = u.PhoneNo
}).ToList();
return query;
}
}
}
``` | 2010/04/02 | [
"https://Stackoverflow.com/questions/2564767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/236476/"
] | This answer has ended up containing a lot of buzz word headings. Hopefully I explain each one and why it applies here. I think each concept I introduce below is worth considering - they aren't always applicable but I find they are all things I personally find valuable when I think about the structure of a system.
### Single Responsibility
Start by thinking about the responsibility of each object - what is its job? Generally you'll find a better design once you decide on a single job for each class. Currently a lot of your classes are doing too much, holding logic that should really exist as services.
The first example of the above is your User class:
```
public class User {
public string ID {get;set;}
public string FirstName {get; set;}
public string LastName {get; set;}
public string PhoneNo {get; set;}
public AccountCollection accounts {get; set;}
public User {
accounts = new AccountCollection(this);
}
public static List<Users> GetUsers() {
return Data.GetUsers();
}
}
```
Why does this provide a method that retrieves users from the data source? That functionality should be moved out into a users service.
Another key example of this is the GenerateReport method on the SubAccount - don't have your report generation logic so tightly tied to the SubAccount object. Splitting this out will give you more flexibility and reduce the change of changes to your SubAccount breaking the report logic.
### Lazy Loading
Again looking at your User class - why does it load all the users accounts on instantiation? Are these objects always going to be used every time you work with a User?
It would generally be better to introduce lazy loading - only retrieve an account when you need it. Of course there are times when you want eager loading (if you know you will want the object soon so want ot reduce database access) but you should be able to design for these exceptions.
### Dependency Injection
This sort of follows on from both the lazy loading point and the single responsibility point. You have a lot of hard coded references to things like your Data class. This is making your design more rigid - refactoring your data access to introduce lazy loading, or changing the way that user records is retrieve is much harder now that many classes are all directly accessing the data access logic.
### Digest objects
Hat tip to Cade Roux - I'd never heard the term Digest objects, usually called them light weight DTOs.
As Cade says, there is no reason to retrieve a rich list containing fully functioning user objects if all you are doing is displaying a combo box of user names that is bound to the unique ids.
Introduce a light weight user object that only stores the very basic user information.
This is again another reason to introduce a services/repository abstraction, and some sort of dependency injection. Changing the types of objects retreived from the data store becomes much easier when you have encapsulated your data retrieval away from your actual objects, and when you are not tightly bound to your data access implementation.
### Law of Demeter
Your objects know too much about the internal structure of each other. Allowing drill down through a User to the Accounts and then to the SubAccount is muddling the responsibility of each object. You are able to set sub account information from the user object when arguably you shouldn't be.
I always struggle with this principle, since drilling through the heirarchy seems very convenient. The problem is that it will stop you thinking proberly about the encapsulation and role of each object.
Perhaps don't expose your Account object from user - instead try introducing properties and methods that expose the relevant members of the Account object. Look at a GetAccount method instead of a Account property, so that you force yourself to work with an account object rather than treat it as a property of the User. | Okay, just a quick comment on the code as you have it at the moment.
```
public class SubAccount {
public Account account {get; set;} //this is public so that my Data class can access the account, to get the account's user's ID.
public SubAccount(Account account) {
this.account = account;
}
[snip]
}
```
You don't even need a setter on the `Account` property if it is passed in on the ctor and then assigned to the backing field.
Setting a property by passing it on on the ctor can be a very good practice to follow, but it falls over if your data object is going to be serialized, i.e. if it is retrieved or sent to a web service - in this case you will need at least an `internal` setter on the `Account` property.
**Edit:** you can still use this DI type behaviour on the constructor, but the problem is that this constructor will not get called when the object is rehydrated from a serialized form (i.e. when it has been passed to/from a web service). So if you are going to use web services you will additionally need to have a parameterless constructor, and either a public or internal setter on the Account property (if you are going for an internal setter then you will also need to specify the `InternalsVisibleToAttribute` in your *AssemblyInfo.cs* file. |
652,770 | Here is the script to create my tables:
```
CREATE TABLE clients (
client_i INT(11),
PRIMARY KEY (client_id)
);
CREATE TABLE projects (
project_id INT(11) UNSIGNED,
client_id INT(11) UNSIGNED,
PRIMARY KEY (project_id)
);
CREATE TABLE posts (
post_id INT(11) UNSIGNED,
project_id INT(11) UNSIGNED,
PRIMARY KEY (post_id)
);
```
In my PHP code, when deleting a client, I want to delete all projects posts:
```
DELETE
FROM posts
INNER JOIN projects ON projects.project_id = posts.project_id
WHERE projects.client_id = :client_id;
```
The posts table does not have a foreign key `client_id`, only `project_id`. I want to delete the posts in projects that have the passed `client_id`.
This is not working right now because no posts are deleted. | 2009/03/17 | [
"https://Stackoverflow.com/questions/652770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/74980/"
] | Try like below:
```
DELETE posts.*,projects.*
FROM posts
INNER JOIN projects ON projects.project_id = posts.project_id
WHERE projects.client_id = :client_id;
``` | If join does not work for you you may try this solution. It is for deleting orphan records from t1 when not using foreign keys + specific where condition. I.e. it deletes records from table1, that have empty field "code" and that do not have records in table2, matching by field "name".
```
delete table1 from table1 t1
where t1.code = ''
and 0=(select count(t2.name) from table2 t2 where t2.name=t1.name);
``` |
652,770 | Here is the script to create my tables:
```
CREATE TABLE clients (
client_i INT(11),
PRIMARY KEY (client_id)
);
CREATE TABLE projects (
project_id INT(11) UNSIGNED,
client_id INT(11) UNSIGNED,
PRIMARY KEY (project_id)
);
CREATE TABLE posts (
post_id INT(11) UNSIGNED,
project_id INT(11) UNSIGNED,
PRIMARY KEY (post_id)
);
```
In my PHP code, when deleting a client, I want to delete all projects posts:
```
DELETE
FROM posts
INNER JOIN projects ON projects.project_id = posts.project_id
WHERE projects.client_id = :client_id;
```
The posts table does not have a foreign key `client_id`, only `project_id`. I want to delete the posts in projects that have the passed `client_id`.
This is not working right now because no posts are deleted. | 2009/03/17 | [
"https://Stackoverflow.com/questions/652770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/74980/"
] | Or the same thing, with a slightly different (IMO friendlier) syntax:
```
DELETE FROM posts
USING posts, projects
WHERE projects.project_id = posts.project_id AND projects.client_id = :client_id;
```
BTW, with mysql using joins is almost always a way faster than subqueries... | Another method of deleting using a sub select that is better than using `IN` would be `WHERE` `EXISTS`
```
DELETE FROM posts
WHERE EXISTS ( SELECT 1
FROM projects
WHERE projects.client_id = posts.client_id);
```
One reason to use this instead of the join is that a `DELETE` with `JOIN` forbids the use of `LIMIT`. If you wish to delete in blocks so as not to produce full table locks, you can add `LIMIT` use this `DELETE WHERE EXISTS` method. |
652,770 | Here is the script to create my tables:
```
CREATE TABLE clients (
client_i INT(11),
PRIMARY KEY (client_id)
);
CREATE TABLE projects (
project_id INT(11) UNSIGNED,
client_id INT(11) UNSIGNED,
PRIMARY KEY (project_id)
);
CREATE TABLE posts (
post_id INT(11) UNSIGNED,
project_id INT(11) UNSIGNED,
PRIMARY KEY (post_id)
);
```
In my PHP code, when deleting a client, I want to delete all projects posts:
```
DELETE
FROM posts
INNER JOIN projects ON projects.project_id = posts.project_id
WHERE projects.client_id = :client_id;
```
The posts table does not have a foreign key `client_id`, only `project_id`. I want to delete the posts in projects that have the passed `client_id`.
This is not working right now because no posts are deleted. | 2009/03/17 | [
"https://Stackoverflow.com/questions/652770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/74980/"
] | Since you are selecting multiple tables, The table to delete from is no longer unambiguous. You need to *select*:
```
DELETE posts FROM posts
INNER JOIN projects ON projects.project_id = posts.project_id
WHERE projects.client_id = :client_id
```
In this case, `table_name1` and `table_name2` are the same table, so this will work:
```
DELETE projects FROM posts INNER JOIN [...]
```
You can even delete from both tables if you wanted to:
```
DELETE posts, projects FROM posts INNER JOIN [...]
```
Note that `order by` and `limit` [don't work for multi-table deletes](http://dev.mysql.com/doc/refman/5.7/en/delete.html).
Also be aware that if you declare an alias for a table, you must use the alias when referring to the table:
```
DELETE p FROM posts as p INNER JOIN [...]
```
---
[Contributions from Carpetsmoker and etc](https://stackoverflow.com/revisions/4192849/4). | I'm more used to the subquery solution to this, but I have not tried it in MySQL:
```
DELETE FROM posts
WHERE project_id IN (
SELECT project_id
FROM projects
WHERE client_id = :client_id
);
``` |
652,770 | Here is the script to create my tables:
```
CREATE TABLE clients (
client_i INT(11),
PRIMARY KEY (client_id)
);
CREATE TABLE projects (
project_id INT(11) UNSIGNED,
client_id INT(11) UNSIGNED,
PRIMARY KEY (project_id)
);
CREATE TABLE posts (
post_id INT(11) UNSIGNED,
project_id INT(11) UNSIGNED,
PRIMARY KEY (post_id)
);
```
In my PHP code, when deleting a client, I want to delete all projects posts:
```
DELETE
FROM posts
INNER JOIN projects ON projects.project_id = posts.project_id
WHERE projects.client_id = :client_id;
```
The posts table does not have a foreign key `client_id`, only `project_id`. I want to delete the posts in projects that have the passed `client_id`.
This is not working right now because no posts are deleted. | 2009/03/17 | [
"https://Stackoverflow.com/questions/652770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/74980/"
] | Another method of deleting using a sub select that is better than using `IN` would be `WHERE` `EXISTS`
```
DELETE FROM posts
WHERE EXISTS ( SELECT 1
FROM projects
WHERE projects.client_id = posts.client_id);
```
One reason to use this instead of the join is that a `DELETE` with `JOIN` forbids the use of `LIMIT`. If you wish to delete in blocks so as not to produce full table locks, you can add `LIMIT` use this `DELETE WHERE EXISTS` method. | Try this,
```
DELETE posts.*
FROM posts
INNER JOIN projects ON projects.project_id = posts.project_id
WHERE projects.client_id = :client_id
``` |
652,770 | Here is the script to create my tables:
```
CREATE TABLE clients (
client_i INT(11),
PRIMARY KEY (client_id)
);
CREATE TABLE projects (
project_id INT(11) UNSIGNED,
client_id INT(11) UNSIGNED,
PRIMARY KEY (project_id)
);
CREATE TABLE posts (
post_id INT(11) UNSIGNED,
project_id INT(11) UNSIGNED,
PRIMARY KEY (post_id)
);
```
In my PHP code, when deleting a client, I want to delete all projects posts:
```
DELETE
FROM posts
INNER JOIN projects ON projects.project_id = posts.project_id
WHERE projects.client_id = :client_id;
```
The posts table does not have a foreign key `client_id`, only `project_id`. I want to delete the posts in projects that have the passed `client_id`.
This is not working right now because no posts are deleted. | 2009/03/17 | [
"https://Stackoverflow.com/questions/652770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/74980/"
] | You can also use ALIAS like this it works just used it on my database! t is the table need deleting from!
```
DELETE t FROM posts t
INNER JOIN projects p ON t.project_id = p.project_id
AND t.client_id = p.client_id
``` | Try this,
```
DELETE posts.*
FROM posts
INNER JOIN projects ON projects.project_id = posts.project_id
WHERE projects.client_id = :client_id
``` |
652,770 | Here is the script to create my tables:
```
CREATE TABLE clients (
client_i INT(11),
PRIMARY KEY (client_id)
);
CREATE TABLE projects (
project_id INT(11) UNSIGNED,
client_id INT(11) UNSIGNED,
PRIMARY KEY (project_id)
);
CREATE TABLE posts (
post_id INT(11) UNSIGNED,
project_id INT(11) UNSIGNED,
PRIMARY KEY (post_id)
);
```
In my PHP code, when deleting a client, I want to delete all projects posts:
```
DELETE
FROM posts
INNER JOIN projects ON projects.project_id = posts.project_id
WHERE projects.client_id = :client_id;
```
The posts table does not have a foreign key `client_id`, only `project_id`. I want to delete the posts in projects that have the passed `client_id`.
This is not working right now because no posts are deleted. | 2009/03/17 | [
"https://Stackoverflow.com/questions/652770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/74980/"
] | **Single Table Delete:**
**In order to delete entries from `posts` table:**
```
DELETE ps
FROM clients C
INNER JOIN projects pj ON C.client_id = pj.client_id
INNER JOIN posts ps ON pj.project_id = ps.project_id
WHERE C.client_id = :client_id;
```
**In order to delete entries from `projects` table:**
```
DELETE pj
FROM clients C
INNER JOIN projects pj ON C.client_id = pj.client_id
INNER JOIN posts ps ON pj.project_id = ps.project_id
WHERE C.client_id = :client_id;
```
**In order to delete entries from `clients` table:**
```
DELETE C
FROM clients C
INNER JOIN projects pj ON C.client_id = pj.client_id
INNER JOIN posts ps ON pj.project_id = ps.project_id
WHERE C.client_id = :client_id;
```
---
**Multiple Tables Delete:**
In order to delete entries from multiple tables out of the joined results you need to specify the table names after `DELETE` as comma separated list:
Suppose you want to delete entries from all the three tables (`posts`,`projects`,`clients`) for a particular client :
```
DELETE C,pj,ps
FROM clients C
INNER JOIN projects pj ON C.client_id = pj.client_id
INNER JOIN posts ps ON pj.project_id = ps.project_id
WHERE C.client_id = :client_id
``` | Try like below:
```
DELETE posts.*,projects.*
FROM posts
INNER JOIN projects ON projects.project_id = posts.project_id
WHERE projects.client_id = :client_id;
``` |
652,770 | Here is the script to create my tables:
```
CREATE TABLE clients (
client_i INT(11),
PRIMARY KEY (client_id)
);
CREATE TABLE projects (
project_id INT(11) UNSIGNED,
client_id INT(11) UNSIGNED,
PRIMARY KEY (project_id)
);
CREATE TABLE posts (
post_id INT(11) UNSIGNED,
project_id INT(11) UNSIGNED,
PRIMARY KEY (post_id)
);
```
In my PHP code, when deleting a client, I want to delete all projects posts:
```
DELETE
FROM posts
INNER JOIN projects ON projects.project_id = posts.project_id
WHERE projects.client_id = :client_id;
```
The posts table does not have a foreign key `client_id`, only `project_id`. I want to delete the posts in projects that have the passed `client_id`.
This is not working right now because no posts are deleted. | 2009/03/17 | [
"https://Stackoverflow.com/questions/652770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/74980/"
] | One solution is to use subquery
```
DELETE FROM posts WHERE post_id in (SELECT post_id FROM posts p
INNER JOIN projects prj ON p.project_id = prj.project_id
INNER JOIN clients c on prj.client_id = c.client_id WHERE c.client_id = :client_id
);
```
The subquery returns the ID that need to be deleted; all three tables are connected using joins and only those records are deleted that meets the filter condition (in yours case i.e. client\_id in the where clause). | -- Note that you can not use an alias over the table where you need delete
```
DELETE tbl_pagos_activos_usuario
FROM tbl_pagos_activos_usuario, tbl_usuarios b, tbl_facturas c
Where tbl_pagos_activos_usuario.usuario=b.cedula
and tbl_pagos_activos_usuario.cod=c.cod
and tbl_pagos_activos_usuario.rif=c.identificador
and tbl_pagos_activos_usuario.usuario=c.pay_for
and tbl_pagos_activos_usuario.nconfppto=c.nconfppto
and NOT ISNULL(tbl_pagos_activos_usuario.nconfppto)
and c.estatus=50
``` |
652,770 | Here is the script to create my tables:
```
CREATE TABLE clients (
client_i INT(11),
PRIMARY KEY (client_id)
);
CREATE TABLE projects (
project_id INT(11) UNSIGNED,
client_id INT(11) UNSIGNED,
PRIMARY KEY (project_id)
);
CREATE TABLE posts (
post_id INT(11) UNSIGNED,
project_id INT(11) UNSIGNED,
PRIMARY KEY (post_id)
);
```
In my PHP code, when deleting a client, I want to delete all projects posts:
```
DELETE
FROM posts
INNER JOIN projects ON projects.project_id = posts.project_id
WHERE projects.client_id = :client_id;
```
The posts table does not have a foreign key `client_id`, only `project_id`. I want to delete the posts in projects that have the passed `client_id`.
This is not working right now because no posts are deleted. | 2009/03/17 | [
"https://Stackoverflow.com/questions/652770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/74980/"
] | You just need to specify that you want to delete the entries from the `posts` table:
```
DELETE posts
FROM posts
INNER JOIN projects ON projects.project_id = posts.project_id
WHERE projects.client_id = :client_id
```
EDIT: For more information you can see [this alternative answer](https://stackoverflow.com/a/29204958/214545) | I'm more used to the subquery solution to this, but I have not tried it in MySQL:
```
DELETE FROM posts
WHERE project_id IN (
SELECT project_id
FROM projects
WHERE client_id = :client_id
);
``` |
652,770 | Here is the script to create my tables:
```
CREATE TABLE clients (
client_i INT(11),
PRIMARY KEY (client_id)
);
CREATE TABLE projects (
project_id INT(11) UNSIGNED,
client_id INT(11) UNSIGNED,
PRIMARY KEY (project_id)
);
CREATE TABLE posts (
post_id INT(11) UNSIGNED,
project_id INT(11) UNSIGNED,
PRIMARY KEY (post_id)
);
```
In my PHP code, when deleting a client, I want to delete all projects posts:
```
DELETE
FROM posts
INNER JOIN projects ON projects.project_id = posts.project_id
WHERE projects.client_id = :client_id;
```
The posts table does not have a foreign key `client_id`, only `project_id`. I want to delete the posts in projects that have the passed `client_id`.
This is not working right now because no posts are deleted. | 2009/03/17 | [
"https://Stackoverflow.com/questions/652770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/74980/"
] | Try like below:
```
DELETE posts.*,projects.*
FROM posts
INNER JOIN projects ON projects.project_id = posts.project_id
WHERE projects.client_id = :client_id;
``` | ```
mysql> INSERT INTO tb1 VALUES(1,1),(2,2),(3,3),(6,60),(7,70),(8,80);
mysql> INSERT INTO tb2 VALUES(1,1),(2,2),(3,3),(4,40),(5,50),(9,90);
```
**DELETE records FROM one table :**
```
mysql> DELETE tb1 FROM tb1,tb2 WHERE tb1.id= tb2.id;
```
**DELETE RECORDS FROM both tables:**
```
mysql> DELETE tb2,tb1 FROM tb2 JOIN tb1 USING(id);
``` |
652,770 | Here is the script to create my tables:
```
CREATE TABLE clients (
client_i INT(11),
PRIMARY KEY (client_id)
);
CREATE TABLE projects (
project_id INT(11) UNSIGNED,
client_id INT(11) UNSIGNED,
PRIMARY KEY (project_id)
);
CREATE TABLE posts (
post_id INT(11) UNSIGNED,
project_id INT(11) UNSIGNED,
PRIMARY KEY (post_id)
);
```
In my PHP code, when deleting a client, I want to delete all projects posts:
```
DELETE
FROM posts
INNER JOIN projects ON projects.project_id = posts.project_id
WHERE projects.client_id = :client_id;
```
The posts table does not have a foreign key `client_id`, only `project_id`. I want to delete the posts in projects that have the passed `client_id`.
This is not working right now because no posts are deleted. | 2009/03/17 | [
"https://Stackoverflow.com/questions/652770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/74980/"
] | Or the same thing, with a slightly different (IMO friendlier) syntax:
```
DELETE FROM posts
USING posts, projects
WHERE projects.project_id = posts.project_id AND projects.client_id = :client_id;
```
BTW, with mysql using joins is almost always a way faster than subqueries... | Try like below:
```
DELETE posts.*,projects.*
FROM posts
INNER JOIN projects ON projects.project_id = posts.project_id
WHERE projects.client_id = :client_id;
``` |
74,030,411 | I have a continuous `time` variable and I want to plot a heatmap of values. To do so using `ggplot` and `geom_tile()` I bin the `time` into `time_bin` and parse the bounds of the resulting intervals. My question is somewhat related to [this one](https://stackoverflow.com/questions/49395469/how-to-use-scale-x-discrete-with-intervals-created-by-cut), which has no answer.
Here's a toy `data.frame`
```
grouped_df [36 Γ 5] (S3: grouped_df/tbl_df/tbl/data.frame)
$ y : chr [1:36] "1" "1" "1" "1" ...
$ time_bin: Factor w/ 100 levels "(-0.03,0.3]",..: 1 2 3 4 1 2 3 4 1 2 ...
$ value : num [1:36] -0.4 -0.512 -0.608 -0.725 0.757 ...
$ low : num [1:36] -0.03 0.3 0.601 0.901 -0.03 0.3 0.601 0.901 -0.03 0.3 ...
$ high : num [1:36] 0.3 0.601 0.901 1.2 0.3 0.601 0.901 1.2 0.3 0.601 ...
- attr(*, "groups")= tibble [9 Γ 2] (S3: tbl_df/tbl/data.frame)
..$ y : chr [1:9] "1" "2" "3" "4" ...
..$ .rows: list<int> [1:9]
.. ..$ : int [1:4] 1 2 3 4
.. ..$ : int [1:4] 5 6 7 8
.. ..$ : int [1:4] 9 10 11 12
.. ..$ : int [1:4] 13 14 15 16
.. ..$ : int [1:4] 17 18 19 20
.. ..$ : int [1:4] 21 22 23 24
.. ..$ : int [1:4] 25 26 27 28
.. ..$ : int [1:4] 29 30 31 32
.. ..$ : int [1:4] 33 34 35 36
.. ..@ ptype: int(0)
..- attr(*, ".drop")= logi TRUE
> dput(toy)
structure(list(y = c("1", "1", "1", "1", "2", "2", "2", "2",
"3", "3", "3", "3", "4", "4", "4", "4", "5", "5", "5", "5", "6",
"6", "6", "6", "7", "7", "7", "7", "8", "8", "8", "8", "9", "9",
"9", "9"), time_bin = structure(c(1L, 2L, 3L, 4L, 1L, 2L, 3L,
4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L,
4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L), .Label = c("(-0.03,0.3]",
"(0.3,0.601]", "(0.601,0.901]", "(0.901,1.2]", "(1.2,1.5]", "(1.5,1.8]",
"(1.8,2.1]", "(2.1,2.4]", "(2.4,2.7]", "(2.7,3]", "(3,3.3]",
"(3.3,3.6]", "(3.6,3.9]", "(3.9,4.2]", "(4.2,4.5]", "(4.5,4.81]",
"(4.81,5.11]", "(5.11,5.41]", "(5.41,5.71]", "(5.71,6.01]", "(6.01,6.31]",
"(6.31,6.61]", "(6.61,6.91]", "(6.91,7.21]", "(7.21,7.51]", "(7.51,7.81]",
"(7.81,8.11]", "(8.11,8.41]", "(8.41,8.71]", "(8.71,9.01]", "(9.01,9.31]",
"(9.31,9.61]", "(9.61,9.91]", "(9.91,10.2]", "(10.2,10.5]", "(10.5,10.8]",
"(10.8,11.1]", "(11.1,11.4]", "(11.4,11.7]", "(11.7,12]", "(12,12.3]",
"(12.3,12.6]", "(12.6,12.9]", "(12.9,13.2]", "(13.2,13.5]", "(13.5,13.8]",
"(13.8,14.1]", "(14.1,14.4]", "(14.4,14.7]", "(14.7,15]", "(15,15.3]",
"(15.3,15.6]", "(15.6,15.9]", "(15.9,16.2]", "(16.2,16.5]", "(16.5,16.8]",
"(16.8,17.1]", "(17.1,17.4]", "(17.4,17.7]", "(17.7,18]", "(18,18.3]",
"(18.3,18.6]", "(18.6,18.9]", "(18.9,19.2]", "(19.2,19.5]", "(19.5,19.8]",
"(19.8,20.1]", "(20.1,20.4]", "(20.4,20.7]", "(20.7,21]", "(21,21.3]",
"(21.3,21.6]", "(21.6,21.9]", "(21.9,22.2]", "(22.2,22.5]", "(22.5,22.8]",
"(22.8,23.1]", "(23.1,23.4]", "(23.4,23.7]", "(23.7,24]", "(24,24.3]",
"(24.3,24.6]", "(24.6,24.9]", "(24.9,25.2]", "(25.2,25.5]", "(25.5,25.8]",
"(25.8,26.1]", "(26.1,26.4]", "(26.4,26.7]", "(26.7,27]", "(27,27.3]",
"(27.3,27.6]", "(27.6,27.9]", "(27.9,28.2]", "(28.2,28.5]", "(28.5,28.8]",
"(28.8,29.1]", "(29.1,29.4]", "(29.4,29.7]", "(29.7,30.1]"), class = "factor"),
value = c(-0.400237814865178, -0.511748154576217, -0.608275784372335,
-0.7247244523613, 0.757330374272958, 0.776718248240655, 0.790724987842227,
0.998768292393676, 1.77979507741577, 1.52945992260953, 1.23688248753942,
0.908341101522855, -1.19238496743088, -1.26961869177189,
-1.32516082947541, -1.38508403291503, -0.629615898978496,
-0.620941659841269, -0.654461627603879, -0.751893145646679,
2.37041367819975, 2.51316431734167, 2.79123079147629, 3.1167959195256,
-0.519653805023003, -0.660372294607146, -0.972330338954077,
-1.31768889807071, 2.11290890332694, 2.21939390456188, 2.21971276073297,
2.15853062905871, 0.0602363209937846, 0.296034218681414,
0.372831656177899, 0.273945402834637), low = c(-0.03, 0.3,
0.601, 0.901, -0.03, 0.3, 0.601, 0.901, -0.03, 0.3, 0.601,
0.901, -0.03, 0.3, 0.601, 0.901, -0.03, 0.3, 0.601, 0.901,
-0.03, 0.3, 0.601, 0.901, -0.03, 0.3, 0.601, 0.901, -0.03,
0.3, 0.601, 0.901, -0.03, 0.3, 0.601, 0.901), high = c(0.3,
0.601, 0.901, 1.2, 0.3, 0.601, 0.901, 1.2, 0.3, 0.601, 0.901,
1.2, 0.3, 0.601, 0.901, 1.2, 0.3, 0.601, 0.901, 1.2, 0.3,
0.601, 0.901, 1.2, 0.3, 0.601, 0.901, 1.2, 0.3, 0.601, 0.901,
1.2, 0.3, 0.601, 0.901, 1.2)), class = c("grouped_df", "tbl_df",
"tbl", "data.frame"), row.names = c(NA, -36L), groups = structure(list(
y = c("1", "2", "3", "4", "5", "6", "7", "8", "9"), .rows = structure(list(
1:4, 5:8, 9:12, 13:16, 17:20, 21:24, 25:28, 29:32, 33:36), ptype = integer(0), class = c("vctrs_list_of",
"vctrs_vctr", "list"))), row.names = c(NA, -9L), class = c("tbl_df",
"tbl", "data.frame"), .drop = TRUE))
```
To plot it, I use
```
toy %>%
ggplot() +
geom_tile(aes(x=time_bin, y=y, fill=value), color=NA)+
geom_vline(aes(xintercept = unique(time_bin[length(time_bin)/2])))
```
Which produces
[![enter image description here](https://i.stack.imgur.com/dPRIE.png)](https://i.stack.imgur.com/dPRIE.png)
I would like the x axis to be labeled only using the first portion of the breaks (-0.03, 0.3, ...). I have been trying to use `scale_x_discrete(breaks, labels)` with different approaches but haven't made much progress. The x scale is long in the real data, so ideally it I would be able to do something like `scale_x_discrete(breaks=scales::pretty_breaks(5))`, but that's also not working.
I also tried using the `low` and `high` values that I parse from the cut, but that creates tile plots that contain vertical white lines everywhere.
Update
------
Using insight from one of the answers, I used `factor(low)` because my parsing works well, but the proposed `readr::parse_number()` does not. This gets the labels into the proper format.
The remaining portion of the question would be, how to show less factor levels using `scale_x_discrete(breaks = ...)` ?
For example, this seems to decimate the axis, a bit cumbersome but kinda works (from [here](https://stackoverflow.com/questions/66275692/r-skip-labels-in-discrete-x-axis))
```
scale_x_discrete(breaks = function(x){x[c(rep(FALSE, 9), TRUE)]})+
```
EDIT
----
For completeness....I am parsing the results from `cut` using
```
parse_cuts <- function(x){
# This f(x) is made to be used as
# mutate(map_df(time_bin, function(.x) parse_cuts(as.character(.x))))
out <- sapply(strsplit(x, "\\(|,|]"), function(qq) as.numeric(qq[-1]))[,1]
names(out) <- c("low", "high")
return(unlist(out))
}
``` | 2022/10/11 | [
"https://Stackoverflow.com/questions/74030411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3215940/"
] | We could use `parse_number` from `readr` package it is in `tidyverse`. To apply here we first have to transform `time_bin` to character:
Update: transformed x to factor(x)
```
library(tidyverse)
toy %>%
mutate(x = factor(parse_number(as.character(time_bin)))) %>%
ggplot() +
geom_tile(aes(x=x, y=y, fill=value), color=NA)+
geom_vline(aes(xintercept = unique(x[length(x)/2])))
xlab("time_bin")
```
[![enter image description here](https://i.stack.imgur.com/NHSwZ.png)](https://i.stack.imgur.com/NHSwZ.png) | A possible way to solve this, using insight from other answers. Not the prettiest but somewhat gets the job done. It might be a good idea to do a labeller function, like `label_decimate()` to produce the subset.
```
toy %>%
mutate(x = factor(low)) %>%
ggplot() +
geom_tile(aes(x=x, y=y, fill=value), color=NA)+
geom_vline(aes(xintercept = unique(x[length(x)/2])))+
scale_x_discrete(breaks = function(x){x[c(rep(FALSE, 9), TRUE)]})
``` |
74,030,411 | I have a continuous `time` variable and I want to plot a heatmap of values. To do so using `ggplot` and `geom_tile()` I bin the `time` into `time_bin` and parse the bounds of the resulting intervals. My question is somewhat related to [this one](https://stackoverflow.com/questions/49395469/how-to-use-scale-x-discrete-with-intervals-created-by-cut), which has no answer.
Here's a toy `data.frame`
```
grouped_df [36 Γ 5] (S3: grouped_df/tbl_df/tbl/data.frame)
$ y : chr [1:36] "1" "1" "1" "1" ...
$ time_bin: Factor w/ 100 levels "(-0.03,0.3]",..: 1 2 3 4 1 2 3 4 1 2 ...
$ value : num [1:36] -0.4 -0.512 -0.608 -0.725 0.757 ...
$ low : num [1:36] -0.03 0.3 0.601 0.901 -0.03 0.3 0.601 0.901 -0.03 0.3 ...
$ high : num [1:36] 0.3 0.601 0.901 1.2 0.3 0.601 0.901 1.2 0.3 0.601 ...
- attr(*, "groups")= tibble [9 Γ 2] (S3: tbl_df/tbl/data.frame)
..$ y : chr [1:9] "1" "2" "3" "4" ...
..$ .rows: list<int> [1:9]
.. ..$ : int [1:4] 1 2 3 4
.. ..$ : int [1:4] 5 6 7 8
.. ..$ : int [1:4] 9 10 11 12
.. ..$ : int [1:4] 13 14 15 16
.. ..$ : int [1:4] 17 18 19 20
.. ..$ : int [1:4] 21 22 23 24
.. ..$ : int [1:4] 25 26 27 28
.. ..$ : int [1:4] 29 30 31 32
.. ..$ : int [1:4] 33 34 35 36
.. ..@ ptype: int(0)
..- attr(*, ".drop")= logi TRUE
> dput(toy)
structure(list(y = c("1", "1", "1", "1", "2", "2", "2", "2",
"3", "3", "3", "3", "4", "4", "4", "4", "5", "5", "5", "5", "6",
"6", "6", "6", "7", "7", "7", "7", "8", "8", "8", "8", "9", "9",
"9", "9"), time_bin = structure(c(1L, 2L, 3L, 4L, 1L, 2L, 3L,
4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L,
4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L), .Label = c("(-0.03,0.3]",
"(0.3,0.601]", "(0.601,0.901]", "(0.901,1.2]", "(1.2,1.5]", "(1.5,1.8]",
"(1.8,2.1]", "(2.1,2.4]", "(2.4,2.7]", "(2.7,3]", "(3,3.3]",
"(3.3,3.6]", "(3.6,3.9]", "(3.9,4.2]", "(4.2,4.5]", "(4.5,4.81]",
"(4.81,5.11]", "(5.11,5.41]", "(5.41,5.71]", "(5.71,6.01]", "(6.01,6.31]",
"(6.31,6.61]", "(6.61,6.91]", "(6.91,7.21]", "(7.21,7.51]", "(7.51,7.81]",
"(7.81,8.11]", "(8.11,8.41]", "(8.41,8.71]", "(8.71,9.01]", "(9.01,9.31]",
"(9.31,9.61]", "(9.61,9.91]", "(9.91,10.2]", "(10.2,10.5]", "(10.5,10.8]",
"(10.8,11.1]", "(11.1,11.4]", "(11.4,11.7]", "(11.7,12]", "(12,12.3]",
"(12.3,12.6]", "(12.6,12.9]", "(12.9,13.2]", "(13.2,13.5]", "(13.5,13.8]",
"(13.8,14.1]", "(14.1,14.4]", "(14.4,14.7]", "(14.7,15]", "(15,15.3]",
"(15.3,15.6]", "(15.6,15.9]", "(15.9,16.2]", "(16.2,16.5]", "(16.5,16.8]",
"(16.8,17.1]", "(17.1,17.4]", "(17.4,17.7]", "(17.7,18]", "(18,18.3]",
"(18.3,18.6]", "(18.6,18.9]", "(18.9,19.2]", "(19.2,19.5]", "(19.5,19.8]",
"(19.8,20.1]", "(20.1,20.4]", "(20.4,20.7]", "(20.7,21]", "(21,21.3]",
"(21.3,21.6]", "(21.6,21.9]", "(21.9,22.2]", "(22.2,22.5]", "(22.5,22.8]",
"(22.8,23.1]", "(23.1,23.4]", "(23.4,23.7]", "(23.7,24]", "(24,24.3]",
"(24.3,24.6]", "(24.6,24.9]", "(24.9,25.2]", "(25.2,25.5]", "(25.5,25.8]",
"(25.8,26.1]", "(26.1,26.4]", "(26.4,26.7]", "(26.7,27]", "(27,27.3]",
"(27.3,27.6]", "(27.6,27.9]", "(27.9,28.2]", "(28.2,28.5]", "(28.5,28.8]",
"(28.8,29.1]", "(29.1,29.4]", "(29.4,29.7]", "(29.7,30.1]"), class = "factor"),
value = c(-0.400237814865178, -0.511748154576217, -0.608275784372335,
-0.7247244523613, 0.757330374272958, 0.776718248240655, 0.790724987842227,
0.998768292393676, 1.77979507741577, 1.52945992260953, 1.23688248753942,
0.908341101522855, -1.19238496743088, -1.26961869177189,
-1.32516082947541, -1.38508403291503, -0.629615898978496,
-0.620941659841269, -0.654461627603879, -0.751893145646679,
2.37041367819975, 2.51316431734167, 2.79123079147629, 3.1167959195256,
-0.519653805023003, -0.660372294607146, -0.972330338954077,
-1.31768889807071, 2.11290890332694, 2.21939390456188, 2.21971276073297,
2.15853062905871, 0.0602363209937846, 0.296034218681414,
0.372831656177899, 0.273945402834637), low = c(-0.03, 0.3,
0.601, 0.901, -0.03, 0.3, 0.601, 0.901, -0.03, 0.3, 0.601,
0.901, -0.03, 0.3, 0.601, 0.901, -0.03, 0.3, 0.601, 0.901,
-0.03, 0.3, 0.601, 0.901, -0.03, 0.3, 0.601, 0.901, -0.03,
0.3, 0.601, 0.901, -0.03, 0.3, 0.601, 0.901), high = c(0.3,
0.601, 0.901, 1.2, 0.3, 0.601, 0.901, 1.2, 0.3, 0.601, 0.901,
1.2, 0.3, 0.601, 0.901, 1.2, 0.3, 0.601, 0.901, 1.2, 0.3,
0.601, 0.901, 1.2, 0.3, 0.601, 0.901, 1.2, 0.3, 0.601, 0.901,
1.2, 0.3, 0.601, 0.901, 1.2)), class = c("grouped_df", "tbl_df",
"tbl", "data.frame"), row.names = c(NA, -36L), groups = structure(list(
y = c("1", "2", "3", "4", "5", "6", "7", "8", "9"), .rows = structure(list(
1:4, 5:8, 9:12, 13:16, 17:20, 21:24, 25:28, 29:32, 33:36), ptype = integer(0), class = c("vctrs_list_of",
"vctrs_vctr", "list"))), row.names = c(NA, -9L), class = c("tbl_df",
"tbl", "data.frame"), .drop = TRUE))
```
To plot it, I use
```
toy %>%
ggplot() +
geom_tile(aes(x=time_bin, y=y, fill=value), color=NA)+
geom_vline(aes(xintercept = unique(time_bin[length(time_bin)/2])))
```
Which produces
[![enter image description here](https://i.stack.imgur.com/dPRIE.png)](https://i.stack.imgur.com/dPRIE.png)
I would like the x axis to be labeled only using the first portion of the breaks (-0.03, 0.3, ...). I have been trying to use `scale_x_discrete(breaks, labels)` with different approaches but haven't made much progress. The x scale is long in the real data, so ideally it I would be able to do something like `scale_x_discrete(breaks=scales::pretty_breaks(5))`, but that's also not working.
I also tried using the `low` and `high` values that I parse from the cut, but that creates tile plots that contain vertical white lines everywhere.
Update
------
Using insight from one of the answers, I used `factor(low)` because my parsing works well, but the proposed `readr::parse_number()` does not. This gets the labels into the proper format.
The remaining portion of the question would be, how to show less factor levels using `scale_x_discrete(breaks = ...)` ?
For example, this seems to decimate the axis, a bit cumbersome but kinda works (from [here](https://stackoverflow.com/questions/66275692/r-skip-labels-in-discrete-x-axis))
```
scale_x_discrete(breaks = function(x){x[c(rep(FALSE, 9), TRUE)]})+
```
EDIT
----
For completeness....I am parsing the results from `cut` using
```
parse_cuts <- function(x){
# This f(x) is made to be used as
# mutate(map_df(time_bin, function(.x) parse_cuts(as.character(.x))))
out <- sapply(strsplit(x, "\\(|,|]"), function(qq) as.numeric(qq[-1]))[,1]
names(out) <- c("low", "high")
return(unlist(out))
}
``` | 2022/10/11 | [
"https://Stackoverflow.com/questions/74030411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3215940/"
] | We could use `parse_number` from `readr` package it is in `tidyverse`. To apply here we first have to transform `time_bin` to character:
Update: transformed x to factor(x)
```
library(tidyverse)
toy %>%
mutate(x = factor(parse_number(as.character(time_bin)))) %>%
ggplot() +
geom_tile(aes(x=x, y=y, fill=value), color=NA)+
geom_vline(aes(xintercept = unique(x[length(x)/2])))
xlab("time_bin")
```
[![enter image description here](https://i.stack.imgur.com/NHSwZ.png)](https://i.stack.imgur.com/NHSwZ.png) | A simple base-r solution is to `gsub` the left edge of the interval out and `cbind` this to the `data` argument of `ggplot`. A slightly different regex (`^.*,([-.0-9]+).$`) would allow you to extract the right edge.
```
ggplot(cbind(toy, "time" = gsub("^.([-.0-9]+),.*$", "\\1", toy$time_bin))) +
geom_tile(aes(x=time, y=y, fill=value), color=NA)+
geom_vline(aes(xintercept = unique(time[length(time)/2])))
```
[![enter image description here](https://i.stack.imgur.com/q6jKe.png)](https://i.stack.imgur.com/q6jKe.png)
However, **this is misleading**, as the x axis "looks" continuous, but is in fact a series of stacked factors which just happen to be in order and roughly contiguous. A better approach is to turn the x `aes` into a genuine numeric, which will also let you specify your `scale` breaks more easily.
```
ggplot(cbind(toy, "time" = as.numeric(gsub("^.([-.0-9]+),.*$", "\\1", toy$time_bin)))) +
geom_tile(aes(x=time, y=y, fill=value), color=NA)+
geom_vline(aes(xintercept = unique(time[length(time)/2])))
```
[![enter image description here](https://i.stack.imgur.com/icuQ0.png)](https://i.stack.imgur.com/icuQ0.png)
Note however that this will leave gaps where the tile sizes don't quite match (the distance between -0.030 and 0.300 is bigger than that between 0.300 and 0.601, and this is correctly shown here). If this is true in your real data, you can either fudge the width of the `geom_tile`, or use `geom_rect` and specify `xmax` and `xmin` from the left and right edges of the cut interval.
```
ggplot(cbind(toy,
"time_l" = as.numeric(gsub("^.([-.0-9]+),.*$", "\\1", toy$time_bin)),
"time_r" = as.numeric(gsub("^.*,([-.0-9]+).$", "\\1", toy$time_bin)),
"y_l" = as.numeric(toy$y) - 0.5,
"y_r" = as.numeric(toy$y) + 0.5
)) +
geom_rect(aes(xmin=time_l, xmax=time_r, ymin=y_l, ymax=y_r, fill=value), color=NA)+
geom_vline(aes(xintercept = unique(time_l[length(time_l)/2])))
```
[![enter image description here](https://i.stack.imgur.com/2YwWl.png)](https://i.stack.imgur.com/2YwWl.png) |
74,030,411 | I have a continuous `time` variable and I want to plot a heatmap of values. To do so using `ggplot` and `geom_tile()` I bin the `time` into `time_bin` and parse the bounds of the resulting intervals. My question is somewhat related to [this one](https://stackoverflow.com/questions/49395469/how-to-use-scale-x-discrete-with-intervals-created-by-cut), which has no answer.
Here's a toy `data.frame`
```
grouped_df [36 Γ 5] (S3: grouped_df/tbl_df/tbl/data.frame)
$ y : chr [1:36] "1" "1" "1" "1" ...
$ time_bin: Factor w/ 100 levels "(-0.03,0.3]",..: 1 2 3 4 1 2 3 4 1 2 ...
$ value : num [1:36] -0.4 -0.512 -0.608 -0.725 0.757 ...
$ low : num [1:36] -0.03 0.3 0.601 0.901 -0.03 0.3 0.601 0.901 -0.03 0.3 ...
$ high : num [1:36] 0.3 0.601 0.901 1.2 0.3 0.601 0.901 1.2 0.3 0.601 ...
- attr(*, "groups")= tibble [9 Γ 2] (S3: tbl_df/tbl/data.frame)
..$ y : chr [1:9] "1" "2" "3" "4" ...
..$ .rows: list<int> [1:9]
.. ..$ : int [1:4] 1 2 3 4
.. ..$ : int [1:4] 5 6 7 8
.. ..$ : int [1:4] 9 10 11 12
.. ..$ : int [1:4] 13 14 15 16
.. ..$ : int [1:4] 17 18 19 20
.. ..$ : int [1:4] 21 22 23 24
.. ..$ : int [1:4] 25 26 27 28
.. ..$ : int [1:4] 29 30 31 32
.. ..$ : int [1:4] 33 34 35 36
.. ..@ ptype: int(0)
..- attr(*, ".drop")= logi TRUE
> dput(toy)
structure(list(y = c("1", "1", "1", "1", "2", "2", "2", "2",
"3", "3", "3", "3", "4", "4", "4", "4", "5", "5", "5", "5", "6",
"6", "6", "6", "7", "7", "7", "7", "8", "8", "8", "8", "9", "9",
"9", "9"), time_bin = structure(c(1L, 2L, 3L, 4L, 1L, 2L, 3L,
4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L,
4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L), .Label = c("(-0.03,0.3]",
"(0.3,0.601]", "(0.601,0.901]", "(0.901,1.2]", "(1.2,1.5]", "(1.5,1.8]",
"(1.8,2.1]", "(2.1,2.4]", "(2.4,2.7]", "(2.7,3]", "(3,3.3]",
"(3.3,3.6]", "(3.6,3.9]", "(3.9,4.2]", "(4.2,4.5]", "(4.5,4.81]",
"(4.81,5.11]", "(5.11,5.41]", "(5.41,5.71]", "(5.71,6.01]", "(6.01,6.31]",
"(6.31,6.61]", "(6.61,6.91]", "(6.91,7.21]", "(7.21,7.51]", "(7.51,7.81]",
"(7.81,8.11]", "(8.11,8.41]", "(8.41,8.71]", "(8.71,9.01]", "(9.01,9.31]",
"(9.31,9.61]", "(9.61,9.91]", "(9.91,10.2]", "(10.2,10.5]", "(10.5,10.8]",
"(10.8,11.1]", "(11.1,11.4]", "(11.4,11.7]", "(11.7,12]", "(12,12.3]",
"(12.3,12.6]", "(12.6,12.9]", "(12.9,13.2]", "(13.2,13.5]", "(13.5,13.8]",
"(13.8,14.1]", "(14.1,14.4]", "(14.4,14.7]", "(14.7,15]", "(15,15.3]",
"(15.3,15.6]", "(15.6,15.9]", "(15.9,16.2]", "(16.2,16.5]", "(16.5,16.8]",
"(16.8,17.1]", "(17.1,17.4]", "(17.4,17.7]", "(17.7,18]", "(18,18.3]",
"(18.3,18.6]", "(18.6,18.9]", "(18.9,19.2]", "(19.2,19.5]", "(19.5,19.8]",
"(19.8,20.1]", "(20.1,20.4]", "(20.4,20.7]", "(20.7,21]", "(21,21.3]",
"(21.3,21.6]", "(21.6,21.9]", "(21.9,22.2]", "(22.2,22.5]", "(22.5,22.8]",
"(22.8,23.1]", "(23.1,23.4]", "(23.4,23.7]", "(23.7,24]", "(24,24.3]",
"(24.3,24.6]", "(24.6,24.9]", "(24.9,25.2]", "(25.2,25.5]", "(25.5,25.8]",
"(25.8,26.1]", "(26.1,26.4]", "(26.4,26.7]", "(26.7,27]", "(27,27.3]",
"(27.3,27.6]", "(27.6,27.9]", "(27.9,28.2]", "(28.2,28.5]", "(28.5,28.8]",
"(28.8,29.1]", "(29.1,29.4]", "(29.4,29.7]", "(29.7,30.1]"), class = "factor"),
value = c(-0.400237814865178, -0.511748154576217, -0.608275784372335,
-0.7247244523613, 0.757330374272958, 0.776718248240655, 0.790724987842227,
0.998768292393676, 1.77979507741577, 1.52945992260953, 1.23688248753942,
0.908341101522855, -1.19238496743088, -1.26961869177189,
-1.32516082947541, -1.38508403291503, -0.629615898978496,
-0.620941659841269, -0.654461627603879, -0.751893145646679,
2.37041367819975, 2.51316431734167, 2.79123079147629, 3.1167959195256,
-0.519653805023003, -0.660372294607146, -0.972330338954077,
-1.31768889807071, 2.11290890332694, 2.21939390456188, 2.21971276073297,
2.15853062905871, 0.0602363209937846, 0.296034218681414,
0.372831656177899, 0.273945402834637), low = c(-0.03, 0.3,
0.601, 0.901, -0.03, 0.3, 0.601, 0.901, -0.03, 0.3, 0.601,
0.901, -0.03, 0.3, 0.601, 0.901, -0.03, 0.3, 0.601, 0.901,
-0.03, 0.3, 0.601, 0.901, -0.03, 0.3, 0.601, 0.901, -0.03,
0.3, 0.601, 0.901, -0.03, 0.3, 0.601, 0.901), high = c(0.3,
0.601, 0.901, 1.2, 0.3, 0.601, 0.901, 1.2, 0.3, 0.601, 0.901,
1.2, 0.3, 0.601, 0.901, 1.2, 0.3, 0.601, 0.901, 1.2, 0.3,
0.601, 0.901, 1.2, 0.3, 0.601, 0.901, 1.2, 0.3, 0.601, 0.901,
1.2, 0.3, 0.601, 0.901, 1.2)), class = c("grouped_df", "tbl_df",
"tbl", "data.frame"), row.names = c(NA, -36L), groups = structure(list(
y = c("1", "2", "3", "4", "5", "6", "7", "8", "9"), .rows = structure(list(
1:4, 5:8, 9:12, 13:16, 17:20, 21:24, 25:28, 29:32, 33:36), ptype = integer(0), class = c("vctrs_list_of",
"vctrs_vctr", "list"))), row.names = c(NA, -9L), class = c("tbl_df",
"tbl", "data.frame"), .drop = TRUE))
```
To plot it, I use
```
toy %>%
ggplot() +
geom_tile(aes(x=time_bin, y=y, fill=value), color=NA)+
geom_vline(aes(xintercept = unique(time_bin[length(time_bin)/2])))
```
Which produces
[![enter image description here](https://i.stack.imgur.com/dPRIE.png)](https://i.stack.imgur.com/dPRIE.png)
I would like the x axis to be labeled only using the first portion of the breaks (-0.03, 0.3, ...). I have been trying to use `scale_x_discrete(breaks, labels)` with different approaches but haven't made much progress. The x scale is long in the real data, so ideally it I would be able to do something like `scale_x_discrete(breaks=scales::pretty_breaks(5))`, but that's also not working.
I also tried using the `low` and `high` values that I parse from the cut, but that creates tile plots that contain vertical white lines everywhere.
Update
------
Using insight from one of the answers, I used `factor(low)` because my parsing works well, but the proposed `readr::parse_number()` does not. This gets the labels into the proper format.
The remaining portion of the question would be, how to show less factor levels using `scale_x_discrete(breaks = ...)` ?
For example, this seems to decimate the axis, a bit cumbersome but kinda works (from [here](https://stackoverflow.com/questions/66275692/r-skip-labels-in-discrete-x-axis))
```
scale_x_discrete(breaks = function(x){x[c(rep(FALSE, 9), TRUE)]})+
```
EDIT
----
For completeness....I am parsing the results from `cut` using
```
parse_cuts <- function(x){
# This f(x) is made to be used as
# mutate(map_df(time_bin, function(.x) parse_cuts(as.character(.x))))
out <- sapply(strsplit(x, "\\(|,|]"), function(qq) as.numeric(qq[-1]))[,1]
names(out) <- c("low", "high")
return(unlist(out))
}
``` | 2022/10/11 | [
"https://Stackoverflow.com/questions/74030411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3215940/"
] | A possible way to solve this, using insight from other answers. Not the prettiest but somewhat gets the job done. It might be a good idea to do a labeller function, like `label_decimate()` to produce the subset.
```
toy %>%
mutate(x = factor(low)) %>%
ggplot() +
geom_tile(aes(x=x, y=y, fill=value), color=NA)+
geom_vline(aes(xintercept = unique(x[length(x)/2])))+
scale_x_discrete(breaks = function(x){x[c(rep(FALSE, 9), TRUE)]})
``` | A simple base-r solution is to `gsub` the left edge of the interval out and `cbind` this to the `data` argument of `ggplot`. A slightly different regex (`^.*,([-.0-9]+).$`) would allow you to extract the right edge.
```
ggplot(cbind(toy, "time" = gsub("^.([-.0-9]+),.*$", "\\1", toy$time_bin))) +
geom_tile(aes(x=time, y=y, fill=value), color=NA)+
geom_vline(aes(xintercept = unique(time[length(time)/2])))
```
[![enter image description here](https://i.stack.imgur.com/q6jKe.png)](https://i.stack.imgur.com/q6jKe.png)
However, **this is misleading**, as the x axis "looks" continuous, but is in fact a series of stacked factors which just happen to be in order and roughly contiguous. A better approach is to turn the x `aes` into a genuine numeric, which will also let you specify your `scale` breaks more easily.
```
ggplot(cbind(toy, "time" = as.numeric(gsub("^.([-.0-9]+),.*$", "\\1", toy$time_bin)))) +
geom_tile(aes(x=time, y=y, fill=value), color=NA)+
geom_vline(aes(xintercept = unique(time[length(time)/2])))
```
[![enter image description here](https://i.stack.imgur.com/icuQ0.png)](https://i.stack.imgur.com/icuQ0.png)
Note however that this will leave gaps where the tile sizes don't quite match (the distance between -0.030 and 0.300 is bigger than that between 0.300 and 0.601, and this is correctly shown here). If this is true in your real data, you can either fudge the width of the `geom_tile`, or use `geom_rect` and specify `xmax` and `xmin` from the left and right edges of the cut interval.
```
ggplot(cbind(toy,
"time_l" = as.numeric(gsub("^.([-.0-9]+),.*$", "\\1", toy$time_bin)),
"time_r" = as.numeric(gsub("^.*,([-.0-9]+).$", "\\1", toy$time_bin)),
"y_l" = as.numeric(toy$y) - 0.5,
"y_r" = as.numeric(toy$y) + 0.5
)) +
geom_rect(aes(xmin=time_l, xmax=time_r, ymin=y_l, ymax=y_r, fill=value), color=NA)+
geom_vline(aes(xintercept = unique(time_l[length(time_l)/2])))
```
[![enter image description here](https://i.stack.imgur.com/2YwWl.png)](https://i.stack.imgur.com/2YwWl.png) |
55,538,141 | I'm using Python 3.7, Django, and BeautifulSoup. I am currnently looking for "span" elements in my document that contain the text "Review". I do so like this
```
html = urllib2.urlopen(req, timeout=settings.SOCKET_TIMEOUT_IN_SECONDS).read()
my_soup = BeautifulSoup(html, features="html.parser")
rev_elts = my_soup.findAll("span", text=re.compile("Review"))
for rev_elt in rev_elts:
... processing
```
but I'd like to add a wrinkle to where I don't want to consider those elements if they have a DIV ancestor with the class "child". So for example, I don't want to consider something like this
```
<div class="child">
<p>
<span class="s">Reviews</span>
...
</p>
</div>
```
How can I adjust my search to take this into account? | 2019/04/05 | [
"https://Stackoverflow.com/questions/55538141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1235929/"
] | First, I will create an example dataset to match the provided summary
```r
set.seed(42)
df <- data.frame(sex = sample(c("M", "F"), size = 100, replace = TRUE),
age_d = runif(100, 18, 80),
d = sample(1:5, size = 100, replace = TRUE),
dis_dur = runif(100, 20, 43),
stringsAsFactors = FALSE)
str(df)
#> 'data.frame': 100 obs. of 4 variables:
#> $ sex : chr "M" "M" "M" "M" ...
#> $ age_d : num 56.8 31.5 31.4 42.1 76.4 ...
#> $ d : int 2 1 4 3 5 2 4 2 3 2 ...
#> $ dis_dur: num 33.3 21.7 23.8 37 30.9 ...
```
load and attach the qwraps2 namespace
```r
library(qwraps2)
```
by default qwraps2 formats output in LaTeX. To have the default switched to
markdown set the following option
```r
options(qwraps2_markup = "markdown")
```
**Update:** as of version 0.5.0 of qwraps2, the use of the `.data` pronoun is
no longer needed or recommended.
```r
stats_summary1 <-
list("Sex (female)" =
list("number (%)" = ~ qwraps2::n_perc(sex=="F", digits = 1)),
"Age" =
list("min" = ~ min(age_d, digits = 1),
"max" = ~ max(age_d, digits = 1),
"median (IQR)" = ~ qwraps2::median_iqr(age_d, digits = 1)),
"Disease" =
list("A" = ~ qwraps2::n_perc(d==1, digits = 1),
"B" = ~ qwraps2::n_perc(d==2, digits = 1),
"C" = ~ qwraps2::n_perc(d==3, digits = 1),
"D" = ~ qwraps2::n_perc(d==4, digits = 1),
"E" = ~ qwraps2::n_perc(d==5, digits = 1)),
"Disease duration" =
list("min" = ~ min(dis_dur, digits = 1),
"max" = ~ max(dis_dur, digits = 1),
"median (IQR)" = ~ qwraps2::median_iqr(dis_dur, digits = 1))
)
whole <- summary_table(df, stats_summary1)
whole
#>
#>
#> | |df (N = 100) |
#> |:-------------------------|:-----------------|
#> |**Sex (female)** | |
#> | number (%) |56 (56.0%) |
#> |**Age** | |
#> | min |1 |
#> | max |77.6816968536004 |
#> | median (IQR) |52.8 (33.7, 64.8) |
#> |**Disease** | |
#> | A |26 (26.0%) |
#> | B |20 (20.0%) |
#> | C |15 (15.0%) |
#> | D |21 (21.0%) |
#> | E |18 (18.0%) |
#> |**Disease duration** | |
#> | min |1 |
#> | max |42.5464100171812 |
#> | median (IQR) |31.0 (25.1, 35.8) |
```
This sould resolve the issue with the forward slash on the percentage sign
(needed escape for LaTeX). Make sure you have the `results = "asis"` chunk
option set so the table will render nicely in your final document.
As for the omitted subheadings, the `qwraps2_summary_table` object is a
character matrix with the class attribute set accordingly and has the
additional attribute `rgroups` which is used by the printing methods to
format the output correctly.
```r
str(whole)
#> 'qwraps2_summary_table' chr [1:12, 1] "56 (56.0%)" "1" "77.6816968536004" ...
#> - attr(*, "dimnames")=List of 2
#> ..$ : chr [1:12] "number (%)" "min" "max" "median (IQR)" ...
#> ..$ : chr "df (N = 100)"
#> - attr(*, "rgroups")= Named int [1:4] 1 3 5 3
#> ..- attr(*, "names")= chr [1:4] "Sex (female)" "Age" "Disease" "Disease duration"
#> - attr(*, "n")= int 100
```
Created on 2020-09-14 by the [reprex package](https://reprex.tidyverse.org) (v0.3.0)
```r
devtools::session_info()
#> β Session info βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
#> setting value
#> version R version 4.0.2 (2020-06-22)
#> os macOS Catalina 10.15.6
#> system x86_64, darwin17.0
#> ui X11
#> language (EN)
#> collate en_US.UTF-8
#> ctype en_US.UTF-8
#> tz America/Denver
#> date 2020-09-14
#>
#> β Packages βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
#> package * version date lib source
#> assertthat 0.2.1 2019-03-21 [1] CRAN (R 4.0.0)
#> backports 1.1.9 2020-08-24 [1] CRAN (R 4.0.2)
#> callr 3.4.4 2020-09-07 [1] CRAN (R 4.0.2)
#> cli 2.0.2 2020-02-28 [1] CRAN (R 4.0.0)
#> crayon 1.3.4 2017-09-16 [1] CRAN (R 4.0.0)
#> desc 1.2.0 2018-05-01 [1] CRAN (R 4.0.0)
#> devtools 2.3.1 2020-07-21 [1] CRAN (R 4.0.2)
#> digest 0.6.25 2020-02-23 [1] CRAN (R 4.0.0)
#> ellipsis 0.3.1 2020-05-15 [1] CRAN (R 4.0.0)
#> evaluate 0.14 2019-05-28 [1] CRAN (R 4.0.0)
#> fansi 0.4.1 2020-01-08 [1] CRAN (R 4.0.0)
#> fs 1.5.0 2020-07-31 [1] CRAN (R 4.0.2)
#> glue 1.4.2 2020-08-27 [1] CRAN (R 4.0.2)
#> highr 0.8 2019-03-20 [1] CRAN (R 4.0.0)
#> htmltools 0.5.0 2020-06-16 [1] CRAN (R 4.0.0)
#> knitr 1.29 2020-06-23 [1] CRAN (R 4.0.0)
#> magrittr 1.5 2014-11-22 [1] CRAN (R 4.0.0)
#> memoise 1.1.0 2017-04-21 [1] CRAN (R 4.0.0)
#> pkgbuild 1.1.0 2020-07-13 [1] CRAN (R 4.0.2)
#> pkgload 1.1.0 2020-05-29 [1] CRAN (R 4.0.0)
#> prettyunits 1.1.1 2020-01-24 [1] CRAN (R 4.0.0)
#> processx 3.4.4 2020-09-03 [1] CRAN (R 4.0.2)
#> ps 1.3.4 2020-08-11 [1] CRAN (R 4.0.2)
#> qwraps2 * 0.5.0 2020-08-31 [1] local
#> R6 2.4.1 2019-11-12 [1] CRAN (R 4.0.0)
#> Rcpp 1.0.5 2020-07-06 [1] CRAN (R 4.0.0)
#> remotes 2.2.0 2020-07-21 [1] CRAN (R 4.0.2)
#> rlang 0.4.7 2020-07-09 [1] CRAN (R 4.0.2)
#> rmarkdown 2.3 2020-06-18 [1] CRAN (R 4.0.0)
#> rprojroot 1.3-2 2018-01-03 [1] CRAN (R 4.0.0)
#> sessioninfo 1.1.1 2018-11-05 [1] CRAN (R 4.0.0)
#> stringi 1.5.3 2020-09-09 [1] CRAN (R 4.0.2)
#> stringr 1.4.0 2019-02-10 [1] CRAN (R 4.0.0)
#> testthat 2.3.2 2020-03-02 [1] CRAN (R 4.0.0)
#> usethis 1.6.1 2020-04-29 [1] CRAN (R 4.0.0)
#> withr 2.2.0 2020-04-20 [1] CRAN (R 4.0.0)
#> xfun 0.17 2020-09-09 [1] CRAN (R 4.0.2)
#> yaml 2.2.1 2020-02-01 [1] CRAN (R 4.0.0)
#>
#> [1] /Library/Frameworks/R.framework/Versions/4.0/Resources/library
``` | Your example is not really reproducible since you `data` is is not provided.
What worked for me was the following:
* Instead of using the summary statistics arguments from `qwraps2`, I use the ones from the `carpenter` package. This is because in PDF documents rendered through the `bookdown` package, `qwraps2::mean_sd()` renders the "Β±" sign as `±` in the table.
Instead, `carpenter::stat_meanSD()` avoids the "Β±" sign and uses brackets for the SD instead. You could do another workaround with `paste()` though if you prefer the "Β±" sign.
* The fact that `qwraps2` is ignoring the top-level headings like `Sex (female)`, `Age` etc. in your example is very annoying. My workaround here is to manually re-introduce these headings through the `kableExtra` package. In you example this would be something like this:
.
```
options(qwraps2_markup = "markdown")
summary_table(df, stats_summary1) %>%
kableExtra::pack_rows("Sex (female)", 1, 1) %>%
kableExtra::pack_rows("Age", 2, 4) %>%
kableExtra::pack_rows("Disease", 5, 9) %>%
kableExtra::pack_rows("Disease duration", 10, 12)
``` |
53,062,028 | I have the code below. Class1 assins the values to the lists(list1, list2,list3). When using these lists inside Class2, the print statement used as a test inside the `calc` function prints a empty list '[]' instead of the data that was stored inside it in Class1. So the calcuation will also return a empty value.
```
class Class2(Class1):
def __init__(self, Class1):
self.arg1 = Class1.arg1
self.arg2 = Class1.arg2
self.arg3 = Class1.arg3
self.arg4 = []
def calc(self, Class1):
for row in Class1.arg1:
self.arg4.append(Class1.list2 + Class1.list3)
print(Class1.arg1)
return self.arg4
cInput = Class1([],[],[])
Test = Class2(cInput ).calc(cInput)
```
Below is my Class1 and a example of how I populate the list(Class1 functions correctly)
```
class Class1:
def __init__(self, list1, list2, list3):
self.arg1= list1
self.arg2= list2
self.arg3= list3
def getList1(filename1):
with open(filename1, "r") as csv1
csvReader1 = csv.DictReader(csv1)
list1= []
for row in zip(csvReader1):
list1.append((row1["arg1"]))
return list1
``` | 2018/10/30 | [
"https://Stackoverflow.com/questions/53062028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | One way to go:
To compare data in the If statement you need to add logical operators. It's the same if you want to say `m = n` or `b = a`. [So add AND in this case](https://www.techonthenet.com/excel/formulas/and_vba.php).
When you apply `If` you also need to end with `End If`
```
Sub tsat()
Dim m As Long
Dim n As Long
Dim b As Long
m = 1
n = 1
b = 1
If (m = n And m = b) Then
Sheet1.Activate
Sheet1.Copy
MsgBox "This new workbook will be saved as MyWb.xls(x)"
'Save new workbook as MyWb.xls(x) into the folder where ThisWorkbook is stored
ActiveWorkbook.SaveAs ThisWorkbook.Path & "\MNP", xlWorkbookNormal
MsgBox "It is saved as " & ActiveWorkbook.FullName & vbLf & "Press OK to close it"
' Close the saved copy
ActiveWorkbook.Close False
Else
MsgBox "Values are not equal. " & " m=" & m & ", n=" & n & ", b=" & b
End If
End Sub
``` | I'm not sure what you're trying to do - but if you want to save sheet1 as a copy under a different name then
```
Sub Demo
Dim m,n,b
If application.worksheetfunction.And(m=n,m=b) then
dim wbTarget as workbook
set wbtarget = workbooks.add()
ThisWorkbook.Sheets(1).copy before:=wbtarget.sheets(1)
wbTarget.saveas ThisWorkbook.Path & "\MNP.xlsx"
wbtarget.close
msgbox "Sheet 1 has been saved as MNP.xlsx"
end if
end Sub
``` |
12,862 | I have a sensor outputting correct, calibrated North-East-Down referenced quaternions describing the orientation of the sensor. It also outputs raw, sensor referenced acceleration data, **inclusive** of gravity. I want NED free acceleration, without gravity.
What I have been doing is rotating the acceleration data by the quaternion, and subtracting gravity from the z axis. this doesnt really make sense to me.
I think it should be something more like
1. Rotate acceleration data by the quaternion (brings data to some strange frame?
2. Subtract gravity from z axis
3. Inverse rotation (back to sensor frame?)
4. Second inverse rotation? (goes to NED frame??)
Any explanation would be appreciated | 2017/07/19 | [
"https://robotics.stackexchange.com/questions/12862",
"https://robotics.stackexchange.com",
"https://robotics.stackexchange.com/users/17602/"
] | I think you have the concept down. I'm not sure what the "some strange frame" would be, or how you would have a transform to that frame.
You know, by physics, that gravity points down in the world frame. You know, by your sensor's orientation quaternion, how the sensor is oriented relative to the world.
So, as you mention:
1. Rotate acceleration data by the quaternion **from** the sensor frame **to** the world frame.
2. Subtract gravity from the down axis (typically z or y - be sure to read the sensor's data sheet!)
3. Rotate the acceleration data **from** the world frame **to** the sensor frame.
I'm not positive why you would want that last step though, unless you were doing something **strictly** in the local frame. Generally you would care about how an object is oriented or how it moves *with regards to an arbitrary start location in the world frame.*
That is, once you rotate the acceleration data to the world frame, you can remove gravity, and then perform your single and double integrations to get speed and position *with respect to the world frame.* I'm not sure what you get by going *back* to the sensor frame after removing gravity.
Maybe this is your fourth point?
>
> Second inverse rotation? (goes to NED frame??)
>
>
>
Right, because again you care about how the object moves *with respect to the world*. If you don't care about that relationship then you're in a pretty small minority of IMU applications, and I personally can't really imagine the scenario you're working with.
But, if you look, your points three and four cancel and you're left with one and two - rotate to world frames, remove gravity. | Accelerometer frames are kind of tricky. They treat the sign differently for gravity and regular accelerations. This is the equation they use:
$$
a\_{accelerometer} = a\_{sensorFrame} - g
$$
See this question for more info:
[Why do 3-axis accelerometers seemingly have a left-handed coordinate system?](https://robotics.stackexchange.com/questions/1858/why-do-3-axis-accelerometers-seemingly-have-a-left-handed-coordinate-system) |