qid
int64 1
74.7M
| question
stringlengths 15
55.4k
| date
stringlengths 10
10
| metadata
sequencelengths 3
3
| response_j
stringlengths 2
32.4k
| response_k
stringlengths 9
40.5k
|
---|---|---|---|---|---|
41,588,101 | Can anyone help me with adding an additional models.CharField to my Django cities\_light\_region table.
This is what i want to implement:
```
class MyRegion(Region):
state_code = models.CharField(max_length=100, default='XXX', blank=True)
class Meta:
proxy = True
```
Error:
?: (models.E017) Proxy model 'MyRegion' contains model fields. | 2017/01/11 | [
"https://Stackoverflow.com/questions/41588101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3774814/"
] | We can do this with below trick
```
class Model(object):
'''
Skip extra field validation "models.E017"
'''
@classmethod
def _check_model(cls):
errors = []
return errors
class MyRegion(Model, Region):
state_code = models.CharField(max_length=100, default='XXX', blank=True)
class Meta:
proxy = True
``` | Well, the error message say it all : a proxy model cannot contain model fields, for the very obvious reason that [a proxy model is a class that uses the table of another model and only add or override behaviour](https://docs.djangoproject.com/en/1.10/topics/db/models/#proxy-models). |
127,142 | I know is not the best, but I'd like to display an image before another already referred. I mean I'd like to cite image 2 before image 1 but display them in the correct order. This is becasue image 1 is very small and I want to display it at the top (or bottom of the page) while image 2 is very big and is iserted in its own page.
LaTeX correctly display images in the order I recall them in the text, but I'd like to avoid this, but only for these two images.
>
> E.g.
>
>
> Text text text see Image 2. Text text text see Image 1.
>
>
> Display image 1 in the same page (top or bottom).
>
>
> Newpage with image 2.
>
>
>
How can I do this?
Thankyou! | 2013/08/07 | [
"https://tex.stackexchange.com/questions/127142",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/32689/"
] | This works. But don't do this.
```
\documentclass{article}
\usepackage{graphicx}
\begin{document}
Text text text see Image~\ref{fig:B}. Text text text see Image~\ref{fig:A}.
\begin{figure}[htb]
\centering
\includegraphics[width=4in]{example-image-a}
\caption{Caption here}
\label{fig:A}
\end{figure}
%\clearpage %% uncomment if needed to shipout all floats before this point.
\begin{figure}[htb]
\centering
\includegraphics[width=4in]{example-image-b}
\caption{Caption here}
\label{fig:B}
\end{figure}
\end{document}
```
![enter image description here](https://i.stack.imgur.com/rAxN5.png)
For more information on float placement, see [this answer](https://tex.stackexchange.com/a/39020/11232) by Frank. | This can easily be resolved by using the `float` package in conjunction with the parameter `[H]`:
```
\documentclass{article}
\usepackage{float}
\begin{document}
\begin{figure}[H]
...picture code...
\label{fig:figA}
\end{figure}
\begin{figure}[H]
...picture code...
\label{fig:figB}
\end{figure}
\end{document}
```
By using the `[H]` option the figure will appear exactly where you put the code. So you can define the order manually. |
4,583,607 | here's a very simple js but i don't know where to begin.
in a html page, if some text is enclosed by angle brackets, like this:
```
〈some text〉
```
i want the text to be colored (but not the brackets).
in normal html, i'd code it like this
```
〈<span class="booktitle">some text</span>〉
```
So, my question is, how do i start to write such a js script that search the text and replace it with span tags?
some basic guide on how to would be sufficient. Thanks.
(i know i need to read the whole html, find the match perhaps using regex, then replace the page with the new one. But have no idea how that can be done with js/DOM. Do i need to traverse every element, get their inner text, do possible replacement? A short example would be greatly appreciated.) | 2011/01/03 | [
"https://Stackoverflow.com/questions/4583607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/369203/"
] | It depends partially on how cautious you need to be not to disturb event handlers on the elements you're traversing. If it's your page and you're in control of the handlers, you may not need to worry; if you're doing a library or bookmarklet or similar, you need to be *very* careful.
For example, consider this markup:
```
<p>And <a href='foo.html'>the 〈foo〉 is 〈bar〉</a>.</p>
```
If you did this:
```
var p = /* ...get a reference to the `p` element... */;
p.innerHTML = p.innerHTML.replace(/〈([^〉]*)〉/g, function(whole, c0) {
return "〈<span class='booktitle'>" + c0 + "</span>〉";
});
```
[(live example)](http://jsbin.com/edacu3/2) *(the example uses unicode escapes and HTML numeric entities for 〈 and 〉 rather than the literals above, because JSBin [doesn't like them raw](http://jsbin.com/edacu3/2), presumably an encoding issue)*
...that would *work* and be really easy (as you see), but if there were an event handler on the `a`, it would get blown away (because we're destroying the `a` and recreating it). But if your text is uncomplicated and you're in control of the event handlers on it, that kind of simple solution might be all you need.
To be (almost) completely minimal-impact will require walking the DOM tree and only processing text nodes. For that, you'd be using [`Node#childNodes`](http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1451460987) (for walking through the DOM), [`Node#nodeType`](http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-111237558) (to know what kind of node you're dealing with), [`Node#nodeValue`](http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-F68D080) (to get the text of a text node), [`Node#splitText`](http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-38853C1D) (on the text nodes, to split them in two so you can move one of them into your `span`), and [`Node#appendChild`](http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-184E7107) (to rehome the text node that you need to put in your `span`; don't worry about removing them from their parent, `appendChild` handles that for you). The above are covered by the DOM specification ([v2 here](http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/), [v3 here](http://www.w3.org/TR/DOM-Level-3-Core/); most browsers are somewhere between the two; the links in the text above are to the DOM2 spec).
You'll want to be careful about this sort of case:
```
<p>The 〈foo <em>and</em> bar〉.</p>
```
...where the 〈 and the 〉 are in different text nodes (both children of the `p`, on either side of an `em` element); there you'll have to move part of each text node and the whole of the `em` into your `span`, most likely.
Hopefully that's enough to get you started. | If the text could be anywhere in the page, you have to traverse through each DOM element, split the text when you found a match using a regex.
I have put my code up there on jsfiddle: <http://jsfiddle.net/thai/RjHqe/>
**What it does:** It looks at the node you put it in,
* If it's an **element**, then it looks into every child nodes of it.
* If it's a **text node**, it finds the text enclosed in 〈angle brackets〉. If there is a match (look at the first match only), then it splits the text node into 3 parts:
+ `left` (the opening bracket and also text before that)
+ `middle` (the text inside the angle bracket)
+ `right` (the closing bracket and text after it)the `middle` part is wrapped inside the `<span>` and the `right` part is being looked for more angle brackets. |
140,903 | I am having a bit of trouble with my survival data.
Basically I am trying to assess whether or not the cox proportional hazard assumption is met, by ploting the schoenfeld residuals in R.
I have several variables and some of them have 3 or more categories.
As far as I know, Schoenfeld residuals are adjusted for each individual and each variable. So, when I tried to get the residuals for each of this variables with 3 or more categories, I was expecting to have one residual for individual, but instead I got more.
It's my first time using R with survival data, so probably I am doing something wrong. Here is the code I used with a variable that has 4 categories.
```
>fit=survfit(s~data$school)
#Cox Model
>summary(coxph(s~data$school))
#Test for proportional hazards assumption
>cox.zph(coxph(s~data$school))
#Schoenfeld residuals (defined for each variable for uncensored subjects)
>res=residuals(coxph(s~data$school), type="schoenfeld", collapse=F)
```
When I call the first 3 rows (time = 7 days), I get a set of 3 residuals per individual:
```
> res[1:3,]
data$school2 data$school3 data$school4
7 -0.6250424 -0.1333578 0.8462863
7 -0.6250424 -0.1333578 0.8462863
7 0.3749576 -0.1333578 -0.1537137
```
Can anyone please help me we this? | 2015/03/08 | [
"https://stats.stackexchange.com/questions/140903",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/70688/"
] | Occasionally it is a good idea to concentrate the effects of a categorical predictor just for the purpose of checking proportional hazards or interaction. If you don't want 3 d.f. for the PH test you can use `predict(fit, type='terms')` to get one column for each predictor, then run `cox.cph`. This doesn't exactly preserve type I error but it's close. The method doesn't recognize that 3 parameters are being estimated instead of 1. | There is a separate Schoenfeld residual *for each covariate* for every uncensored individual.
In the case of a categorical covariate with $k$ levels, $k-1$ dummy variates appear in the model. |
416,108 | For an ideal OpAmp the voltages at the inputs are said to be of equal value and the currents 0, however, for we also know that $$V\_\text{out}=A(V\_p-V\_n)$$ but if the voltages are the same the output should always be 0!
I know that what I'm saying is wrong, but I don't know where the loophole is, and I can't find it anywhere.
[![enter image description here](https://i.stack.imgur.com/5dXFM.png)](https://i.stack.imgur.com/5dXFM.png) | 2019/01/09 | [
"https://electronics.stackexchange.com/questions/416108",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/201757/"
] | >
> For an ideal op-amp the voltages at the inputs are said to be of equal value ...
>
>
>
No. If negative feedback is applied and the output is not driven into saturation then the inputs will be very, very close to equal.
>
> ... and the currents 0, ...
>
>
>
Yes, due to the high and sometimes very, very high input impedance.
>
> ... however, for we also know that \$ V\_{out}=A(V\_p−V\_n) \$
> but if the voltages are the same the output should always be 0!
>
>
>
Correct. And that is why the voltages are not the same (but very, very close). The difference in voltages can be worked out by rearranging your formula to $$ V\_p - V\_n = \frac {V\_{out}}{A} $$ and since A is very large the difference in inputs is very small - so small that it's *almost* zero.
![schematic](https://i.stack.imgur.com/JnKk7.png)
[simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fJnKk7.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/)
*Figure 1. Non-inverting amplifier with a gain of 2.*
---
From the comments:
>
> When analyzing an op-amp circuit with negative feedback assuming it is ideal we make the assumptions (almost in this order):
>
>
> 1. Input voltages are the same;
>
>
>
Yes, but we know deep down that they are slightly different.
>
> 2. The gain of the op-amp goes to infinity;
>
>
>
The gain of the op-amp is fixed as specified in the datasheet. 1M to 10M would be typical.
>
> 3. Work out the output voltage and find out that the gain is finite and dependent of the circuit around the op-amp.
>
>
>
The gain of **the complete circuit** is "finite" (a modest value, say, of 1 to 1k) rather than the open-loop gain of 1M to 10M which hasn't changed, no matter what the feedback arrangement is.
>
> If in a circuit the only thing that causes a gain is the op-amp then the gain of the circuit is the gain of the op-amp, so our reasoning appears to be flawed.
>
>
>
Nope. You're forgetting the negative feedback. This *controls* the overall circuit gain and corrects any variations and non-linearities in the op-amp itself.
---
>
> I think I just got it, my problem now lies in "How" does the negative feedback controls the circuit gain, ...
>
>
>
Let's look at Figure 1 again.
* Initially Vp is at 0 V so the output and Vn are at 0 V too.
* VP is suddenly and instantly switched from 0 to +1 V.
* VP - Vn = 1 V so (since the open-loop gain of the op-amp itself is 1M) the output starts to swing towards +1,000,000 V at a rate limited by the slew rate of the op-amp.
* As it does, VP - Vn is decreasing and by the time Vout reaches 0.5 V, VP - Vn = 0.75 V so the output is now trying to swing to 750,000 V (but is still only at 0.5 V). Remember that the feedback is dividing by 2.
* This process continues so that as the output gets approaches 2.0 V the difference between the inputs is getting close to zero and so the target output voltage is falling too. The feedback is reducing the output drive and bringing it under control.
* Very quickly the output reaches 2.0 V and at this point Vn is just a millionth or two below 1 V and the circuit is stable, balanced, happy and under control. | The loophole is that, for an **ideal** op-amp, \$A = +\infty\$. Hence, unless you reach saturation, \$V\_p - V\_n = {V\_{out} \over A} = {V\_{out} \over +\infty} = 0\$.
**Edit:**
If that helps you, you can consider a non-ideal op-amp with a finite \$A\$ gain, using it in an inverter configuration, as you suggested in your comment:
![schematic](https://i.stack.imgur.com/b0Ggr.png)
[simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fb0Ggr.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/)
Then you have both \$V\_{out} = A (V\_+ - V\_-) = A (0 - V\_-) = - A V\_-\$ and \$V\_- = {V\_{in} + V\_{out} \over 2}\$. That leads to \$V\_{out} = - {A \over A+2} V\_{in}\$ and \$V\_- = {1 \over A+2} V\_{in}\$.
Now, when \$A \to +\infty\$, you have \$V\_{out} \to -V\_{in}\$ and \$V\_- \to 0\$. |
416,108 | For an ideal OpAmp the voltages at the inputs are said to be of equal value and the currents 0, however, for we also know that $$V\_\text{out}=A(V\_p-V\_n)$$ but if the voltages are the same the output should always be 0!
I know that what I'm saying is wrong, but I don't know where the loophole is, and I can't find it anywhere.
[![enter image description here](https://i.stack.imgur.com/5dXFM.png)](https://i.stack.imgur.com/5dXFM.png) | 2019/01/09 | [
"https://electronics.stackexchange.com/questions/416108",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/201757/"
] | The loophole is that, for an **ideal** op-amp, \$A = +\infty\$. Hence, unless you reach saturation, \$V\_p - V\_n = {V\_{out} \over A} = {V\_{out} \over +\infty} = 0\$.
**Edit:**
If that helps you, you can consider a non-ideal op-amp with a finite \$A\$ gain, using it in an inverter configuration, as you suggested in your comment:
![schematic](https://i.stack.imgur.com/b0Ggr.png)
[simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fb0Ggr.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/)
Then you have both \$V\_{out} = A (V\_+ - V\_-) = A (0 - V\_-) = - A V\_-\$ and \$V\_- = {V\_{in} + V\_{out} \over 2}\$. That leads to \$V\_{out} = - {A \over A+2} V\_{in}\$ and \$V\_- = {1 \over A+2} V\_{in}\$.
Now, when \$A \to +\infty\$, you have \$V\_{out} \to -V\_{in}\$ and \$V\_- \to 0\$. | One formula often used in thinking about opamp behavior is
Closed Loop Gain = G /(1 + G \* H)
where G = the open-loop-gain and H is the feedback-factor.
Suppose the G rolls off with frequency, and suppose the H is 0.0001 (purpose is to produce a precision gain of 10,000x).
What happens in a real opamp?
[![enter image description here](https://i.stack.imgur.com/cprw5.png)](https://i.stack.imgur.com/cprw5.png)
Look at the right side axis, where linear-error is plotted,
Notice the error is 10%, at 10 Hz.
And 1% error at 1Hz.
And 0.1% error, or 10 bits, at 0.1 Hz. |
416,108 | For an ideal OpAmp the voltages at the inputs are said to be of equal value and the currents 0, however, for we also know that $$V\_\text{out}=A(V\_p-V\_n)$$ but if the voltages are the same the output should always be 0!
I know that what I'm saying is wrong, but I don't know where the loophole is, and I can't find it anywhere.
[![enter image description here](https://i.stack.imgur.com/5dXFM.png)](https://i.stack.imgur.com/5dXFM.png) | 2019/01/09 | [
"https://electronics.stackexchange.com/questions/416108",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/201757/"
] | >
> For an ideal op-amp the voltages at the inputs are said to be of equal value ...
>
>
>
No. If negative feedback is applied and the output is not driven into saturation then the inputs will be very, very close to equal.
>
> ... and the currents 0, ...
>
>
>
Yes, due to the high and sometimes very, very high input impedance.
>
> ... however, for we also know that \$ V\_{out}=A(V\_p−V\_n) \$
> but if the voltages are the same the output should always be 0!
>
>
>
Correct. And that is why the voltages are not the same (but very, very close). The difference in voltages can be worked out by rearranging your formula to $$ V\_p - V\_n = \frac {V\_{out}}{A} $$ and since A is very large the difference in inputs is very small - so small that it's *almost* zero.
![schematic](https://i.stack.imgur.com/JnKk7.png)
[simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fJnKk7.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/)
*Figure 1. Non-inverting amplifier with a gain of 2.*
---
From the comments:
>
> When analyzing an op-amp circuit with negative feedback assuming it is ideal we make the assumptions (almost in this order):
>
>
> 1. Input voltages are the same;
>
>
>
Yes, but we know deep down that they are slightly different.
>
> 2. The gain of the op-amp goes to infinity;
>
>
>
The gain of the op-amp is fixed as specified in the datasheet. 1M to 10M would be typical.
>
> 3. Work out the output voltage and find out that the gain is finite and dependent of the circuit around the op-amp.
>
>
>
The gain of **the complete circuit** is "finite" (a modest value, say, of 1 to 1k) rather than the open-loop gain of 1M to 10M which hasn't changed, no matter what the feedback arrangement is.
>
> If in a circuit the only thing that causes a gain is the op-amp then the gain of the circuit is the gain of the op-amp, so our reasoning appears to be flawed.
>
>
>
Nope. You're forgetting the negative feedback. This *controls* the overall circuit gain and corrects any variations and non-linearities in the op-amp itself.
---
>
> I think I just got it, my problem now lies in "How" does the negative feedback controls the circuit gain, ...
>
>
>
Let's look at Figure 1 again.
* Initially Vp is at 0 V so the output and Vn are at 0 V too.
* VP is suddenly and instantly switched from 0 to +1 V.
* VP - Vn = 1 V so (since the open-loop gain of the op-amp itself is 1M) the output starts to swing towards +1,000,000 V at a rate limited by the slew rate of the op-amp.
* As it does, VP - Vn is decreasing and by the time Vout reaches 0.5 V, VP - Vn = 0.75 V so the output is now trying to swing to 750,000 V (but is still only at 0.5 V). Remember that the feedback is dividing by 2.
* This process continues so that as the output gets approaches 2.0 V the difference between the inputs is getting close to zero and so the target output voltage is falling too. The feedback is reducing the output drive and bringing it under control.
* Very quickly the output reaches 2.0 V and at this point Vn is just a millionth or two below 1 V and the circuit is stable, balanced, happy and under control. | The assumption that the input voltages are always the same only applies when the op amp is used with **negative feedback**. It is the feedback that causes the input voltages to be the same (or nearly so, in the real world). Of course, we also assume that the output voltage is within the operating limits of the amplifier.
When operated without feedback, or with positive feedback, then the input voltages may be much different. In this case it is reasonable to say that
$$V\_{OUT} = A\_{OL}(V\_P - V\_N)$$
where \$A\_{OL}\$ is the open loop gain of the op amp itself. |
416,108 | For an ideal OpAmp the voltages at the inputs are said to be of equal value and the currents 0, however, for we also know that $$V\_\text{out}=A(V\_p-V\_n)$$ but if the voltages are the same the output should always be 0!
I know that what I'm saying is wrong, but I don't know where the loophole is, and I can't find it anywhere.
[![enter image description here](https://i.stack.imgur.com/5dXFM.png)](https://i.stack.imgur.com/5dXFM.png) | 2019/01/09 | [
"https://electronics.stackexchange.com/questions/416108",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/201757/"
] | The assumption that the input voltages are always the same only applies when the op amp is used with **negative feedback**. It is the feedback that causes the input voltages to be the same (or nearly so, in the real world). Of course, we also assume that the output voltage is within the operating limits of the amplifier.
When operated without feedback, or with positive feedback, then the input voltages may be much different. In this case it is reasonable to say that
$$V\_{OUT} = A\_{OL}(V\_P - V\_N)$$
where \$A\_{OL}\$ is the open loop gain of the op amp itself. | One formula often used in thinking about opamp behavior is
Closed Loop Gain = G /(1 + G \* H)
where G = the open-loop-gain and H is the feedback-factor.
Suppose the G rolls off with frequency, and suppose the H is 0.0001 (purpose is to produce a precision gain of 10,000x).
What happens in a real opamp?
[![enter image description here](https://i.stack.imgur.com/cprw5.png)](https://i.stack.imgur.com/cprw5.png)
Look at the right side axis, where linear-error is plotted,
Notice the error is 10%, at 10 Hz.
And 1% error at 1Hz.
And 0.1% error, or 10 bits, at 0.1 Hz. |
416,108 | For an ideal OpAmp the voltages at the inputs are said to be of equal value and the currents 0, however, for we also know that $$V\_\text{out}=A(V\_p-V\_n)$$ but if the voltages are the same the output should always be 0!
I know that what I'm saying is wrong, but I don't know where the loophole is, and I can't find it anywhere.
[![enter image description here](https://i.stack.imgur.com/5dXFM.png)](https://i.stack.imgur.com/5dXFM.png) | 2019/01/09 | [
"https://electronics.stackexchange.com/questions/416108",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/201757/"
] | >
> For an ideal op-amp the voltages at the inputs are said to be of equal value ...
>
>
>
No. If negative feedback is applied and the output is not driven into saturation then the inputs will be very, very close to equal.
>
> ... and the currents 0, ...
>
>
>
Yes, due to the high and sometimes very, very high input impedance.
>
> ... however, for we also know that \$ V\_{out}=A(V\_p−V\_n) \$
> but if the voltages are the same the output should always be 0!
>
>
>
Correct. And that is why the voltages are not the same (but very, very close). The difference in voltages can be worked out by rearranging your formula to $$ V\_p - V\_n = \frac {V\_{out}}{A} $$ and since A is very large the difference in inputs is very small - so small that it's *almost* zero.
![schematic](https://i.stack.imgur.com/JnKk7.png)
[simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fJnKk7.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/)
*Figure 1. Non-inverting amplifier with a gain of 2.*
---
From the comments:
>
> When analyzing an op-amp circuit with negative feedback assuming it is ideal we make the assumptions (almost in this order):
>
>
> 1. Input voltages are the same;
>
>
>
Yes, but we know deep down that they are slightly different.
>
> 2. The gain of the op-amp goes to infinity;
>
>
>
The gain of the op-amp is fixed as specified in the datasheet. 1M to 10M would be typical.
>
> 3. Work out the output voltage and find out that the gain is finite and dependent of the circuit around the op-amp.
>
>
>
The gain of **the complete circuit** is "finite" (a modest value, say, of 1 to 1k) rather than the open-loop gain of 1M to 10M which hasn't changed, no matter what the feedback arrangement is.
>
> If in a circuit the only thing that causes a gain is the op-amp then the gain of the circuit is the gain of the op-amp, so our reasoning appears to be flawed.
>
>
>
Nope. You're forgetting the negative feedback. This *controls* the overall circuit gain and corrects any variations and non-linearities in the op-amp itself.
---
>
> I think I just got it, my problem now lies in "How" does the negative feedback controls the circuit gain, ...
>
>
>
Let's look at Figure 1 again.
* Initially Vp is at 0 V so the output and Vn are at 0 V too.
* VP is suddenly and instantly switched from 0 to +1 V.
* VP - Vn = 1 V so (since the open-loop gain of the op-amp itself is 1M) the output starts to swing towards +1,000,000 V at a rate limited by the slew rate of the op-amp.
* As it does, VP - Vn is decreasing and by the time Vout reaches 0.5 V, VP - Vn = 0.75 V so the output is now trying to swing to 750,000 V (but is still only at 0.5 V). Remember that the feedback is dividing by 2.
* This process continues so that as the output gets approaches 2.0 V the difference between the inputs is getting close to zero and so the target output voltage is falling too. The feedback is reducing the output drive and bringing it under control.
* Very quickly the output reaches 2.0 V and at this point Vn is just a millionth or two below 1 V and the circuit is stable, balanced, happy and under control. | One formula often used in thinking about opamp behavior is
Closed Loop Gain = G /(1 + G \* H)
where G = the open-loop-gain and H is the feedback-factor.
Suppose the G rolls off with frequency, and suppose the H is 0.0001 (purpose is to produce a precision gain of 10,000x).
What happens in a real opamp?
[![enter image description here](https://i.stack.imgur.com/cprw5.png)](https://i.stack.imgur.com/cprw5.png)
Look at the right side axis, where linear-error is plotted,
Notice the error is 10%, at 10 Hz.
And 1% error at 1Hz.
And 0.1% error, or 10 bits, at 0.1 Hz. |
828,931 | I have been trying to configure Postfix to use SMTP authentication. When I telnet on port 587, I appear to be authenticating correctly, but the mail fails to reach its destination and instead comes back as 553 rejected by Spamhaus because my IP is on the PBL. When I read the documentation on Spamhaus, I am told that being on the PBL is not a block, I just need to ensure that I authenticate correctly (<https://www.spamhaus.org/faq/section/Spamhaus%20PBL#253>).
I have searched extensively, but have not found a way to ensure mail is delivered successfully from this server.
Would anyone know what I might be missing here?
Here is the result of my telnet test:
```
ubuntu@dev-server:~$ telnet api.mijnvitalefuncties.com 587
Trying 192.168.0.11...
Connected to api.mijnvitalefuncties.com.
Escape character is '^]'.
220 dev-server ESMTP Postfix (Ubuntu)
ehlo api.mijnvitalefuncties.com
250-dev-server
250-PIPELINING
250-SIZE 10240000
250-VRFY
250-ETRN
250-STARTTLS
250-AUTH PLAIN LOGIN
250-AUTH=PLAIN LOGIN
250-ENHANCEDSTATUSCODES
250-8BITMIME
250 DSN
AUTH LOGIN
334 VXNlcm5hbWU6
***
334 UGFzc3dvcmQ6
***
235 2.7.0 Authentication successful
MAIL FROM:<someone@api.mijnvitalefuncties.com>
250 2.1.0 Ok
RCPT TO:<someone@example.com>
250 2.1.5 Ok
DATA
354 End data with <CR><LF>.<CR><LF>
.
250 2.0.0 Ok: queued as B70A764235
quit
221 2.0.0 Bye
Connection closed by foreign host.
```
Here is the email I receive informing me that the mail cannot be delivered:
```
This is the mail system at host dev-server.
I'm sorry to have to inform you that your message could not
be delivered to one or more recipients. It's attached below.
For further assistance, please send mail to postmaster.
If you do so, please include this problem report. You can
delete your own text from the attached returned message.
The mail system
<someone@example.com>: host cluster5.eu.messagelabs.com[193.109.255.99]
said: 553-mail rejected because your IP is in the PBL. See 553
http://www.spamhaus.org/pbl (in reply to RCPT TO command)
```
Here is the error I get when I try to disable port 25 so as to force mail through submission (port 587).
```
Jan 27 11:53:26 dev-server postfix/qmgr[16821]: warning: connect to transport private/smtp: Connection refused
Jan 27 11:53:26 dev-server postfix/error[16841]: 5137E64232: to=<peter.heylin@ie.fujitsu.com>, relay=none, delay=19, delays=19/0/0/0.01, dsn=4.3.0, status=deferred (mail transport unavailable)
``` | 2017/01/27 | [
"https://serverfault.com/questions/828931",
"https://serverfault.com",
"https://serverfault.com/users/395531/"
] | The log shows that authentication is properly configured and working
```
235 2.7.0 Authentication successful
```
but the reply says you are getting blocked
```
553-mail rejected because your IP is in the PBL. See 553 http://www.spamhaus.org/pbl (in reply to RCPT TO command)
```
Go to spamhaus web site and follow the link to get unblocked
>
> Blocked? To check, get info and resolve listings go to [Blocklist
> Removal Center](https://www.spamhaus.org/lookup/)
>
>
> | Proving that authentication is working is not the same thing as proving that unauthenticated requests are blocked. However that's not relevant to the problem you are having (unable to deliver email to remote systems).
>
> when I try to disable port 25
>
>
>
It's rather worrying that you think this has any part in a solution to your problem. You've also not provided any details of how your MTA is configured.(a diff of the main.cf and any other config files you have modified are pretty essential to understanding what's going on here).
>
> When I read the documentation on Spamhaus, I am told that being on the PBL is not a block, I just need to ensure that I authenticate correctly
>
>
>
You seem to have the drawn the wrong conclusions from the information provided there. Here authentication solves the problem where *your* MTA is rejecting messages from *your* MUA. While your problem is that the messagelabs MTA is not accepting mail from your MTA.
If you have a formal arrangement with messagelabs whereby they provide you with a login to their MTA, and you configure your MTA to use that account when passing mail to their servers then you would be able to get your email forwarded by them. But such an approach is just silly - messagelabs are not interested in maintaining such relationships with all the people who might want to send their customers email.
Read "[What if I want to run a mail server on dynamic IPs listed in the PBL?](https://www.spamhaus.org/faq/section/Spamhaus%20PBL#219)" carefully.
You need to get a static IP address (in a static range) or use a smart relay which already has such a IP. |
22,052,258 | I am building an authentication system using Passport.js using [Easy Node Authentication: Setup and Local tutorial](https://scotch.io/tutorials/easy-node-authentication-setup-and-local).
I am confused about what `passport.session()` does.
After playing around with the different middleware I came to understand that `express.session()` is what sends a session ID over cookies to the client, but I'm confused about what `passport.session()` does and why it is required in addition to `express.session()`.
Here is how I set up my application:
// Server.js configures the application and sets up the webserver
```
//importing our modules
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');
var configDB = require('./config/database.js');
//Configuration of Databse and App
mongoose.connect(configDB.url); //connect to our database
require('./config/passport')(passport); //pass passport for configuration
app.configure(function() {
//set up our express application
app.use(express.logger('dev')); //log every request to the console
app.use(express.cookieParser()); //read cookies (needed for auth)
app.use(express.bodyParser()); //get info from html forms
app.set('view engine', 'ejs'); //set up ejs for templating
//configuration for passport
app.use(express.session({ secret: 'olhosvermelhoseasenhaclassica', maxAge:null })); //session secret
app.use(passport.initialize());
app.use(passport.session()); //persistent login session
app.use(flash()); //use connect-flash for flash messages stored in session
});
//Set up routes
require('./app/routes.js')(app, passport);
//launch
app.listen(port);
console.log("Server listening on port" + port);
``` | 2014/02/26 | [
"https://Stackoverflow.com/questions/22052258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1835903/"
] | `passport.session()` acts as a middleware to alter the req object and change the 'user' value that is currently the session id (from the client cookie) into the true deserialized user object.
Whilst the other answers make some good points I thought that some more specific detail could be provided.
```
app.use(passport.session());
```
is equivalent to
```
app.use(passport.authenticate('session'));
```
Where 'session' refers to the following strategy that is bundled with passportJS.
Here's a link to the file:
<https://github.com/jaredhanson/passport/blob/master/lib/strategies/session.js>
And a [permalink](https://github.com/jaredhanson/passport/blob/b220766870cdbb98cc7570764cd3ced93da8945e/lib/strategies/session.js#L66) pointing to the following lines at the time of this writing:
```
var property = req._passport.instance._userProperty || 'user';
req[property] = user;
```
Where it essentially acts as a middleware and alters the value of the 'user' property in the req object to contain the deserialized identity of the user. To allow this to work correctly you must include `serializeUser` and `deserializeUser` functions in your custom code.
```
passport.serializeUser(function (user, done) {
done(null, user.id);
});
passport.deserializeUser(function (user, done) {
//If using Mongoose with MongoDB; if other you will need JS specific to that schema.
User.findById(user.id, function (err, user) {
done(err, user);
});
});
```
This will find the correct user from the database and pass it as a closure variable into the callback `done(err,user);` so the above code in the `passport.session()` can replace the 'user' value in the req object and pass on to the next middleware in the pile. | From the [documentation](http://passportjs.org/guide/configure/)
>
> In a Connect or Express-based application, passport.initialize()
> middleware is required to initialize Passport. If your application
> uses persistent login sessions, passport.session() middleware must
> also be used.
>
>
>
and
>
> Sessions
>
>
> In a typical web application, the credentials used to authenticate a
> user will only be transmitted during the login request. If
> authentication succeeds, a session will be established and maintained
> via a cookie set in the user's browser.
>
>
> Each subsequent request will not contain credentials, but rather the
> unique cookie that identifies the session. In order to support login
> sessions, Passport will serialize and deserialize user instances to
> and from the session.
>
>
>
and
>
> Note that enabling session support is entirely optional, though it is
> recommended for most applications. If enabled, be sure to use
> express.session() before passport.session() to ensure that the login
> session is restored in the correct order.
>
>
> |
22,052,258 | I am building an authentication system using Passport.js using [Easy Node Authentication: Setup and Local tutorial](https://scotch.io/tutorials/easy-node-authentication-setup-and-local).
I am confused about what `passport.session()` does.
After playing around with the different middleware I came to understand that `express.session()` is what sends a session ID over cookies to the client, but I'm confused about what `passport.session()` does and why it is required in addition to `express.session()`.
Here is how I set up my application:
// Server.js configures the application and sets up the webserver
```
//importing our modules
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');
var configDB = require('./config/database.js');
//Configuration of Databse and App
mongoose.connect(configDB.url); //connect to our database
require('./config/passport')(passport); //pass passport for configuration
app.configure(function() {
//set up our express application
app.use(express.logger('dev')); //log every request to the console
app.use(express.cookieParser()); //read cookies (needed for auth)
app.use(express.bodyParser()); //get info from html forms
app.set('view engine', 'ejs'); //set up ejs for templating
//configuration for passport
app.use(express.session({ secret: 'olhosvermelhoseasenhaclassica', maxAge:null })); //session secret
app.use(passport.initialize());
app.use(passport.session()); //persistent login session
app.use(flash()); //use connect-flash for flash messages stored in session
});
//Set up routes
require('./app/routes.js')(app, passport);
//launch
app.listen(port);
console.log("Server listening on port" + port);
``` | 2014/02/26 | [
"https://Stackoverflow.com/questions/22052258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1835903/"
] | `passport.session()` acts as a middleware to alter the req object and change the 'user' value that is currently the session id (from the client cookie) into the true deserialized user object.
Whilst the other answers make some good points I thought that some more specific detail could be provided.
```
app.use(passport.session());
```
is equivalent to
```
app.use(passport.authenticate('session'));
```
Where 'session' refers to the following strategy that is bundled with passportJS.
Here's a link to the file:
<https://github.com/jaredhanson/passport/blob/master/lib/strategies/session.js>
And a [permalink](https://github.com/jaredhanson/passport/blob/b220766870cdbb98cc7570764cd3ced93da8945e/lib/strategies/session.js#L66) pointing to the following lines at the time of this writing:
```
var property = req._passport.instance._userProperty || 'user';
req[property] = user;
```
Where it essentially acts as a middleware and alters the value of the 'user' property in the req object to contain the deserialized identity of the user. To allow this to work correctly you must include `serializeUser` and `deserializeUser` functions in your custom code.
```
passport.serializeUser(function (user, done) {
done(null, user.id);
});
passport.deserializeUser(function (user, done) {
//If using Mongoose with MongoDB; if other you will need JS specific to that schema.
User.findById(user.id, function (err, user) {
done(err, user);
});
});
```
This will find the correct user from the database and pass it as a closure variable into the callback `done(err,user);` so the above code in the `passport.session()` can replace the 'user' value in the req object and pass on to the next middleware in the pile. | It simply authenticates the session (which is populated by `express.session()`). It is equivalent to:
```
passport.authenticate('session');
```
as can be seen in the code here:
<https://github.com/jaredhanson/passport/blob/42ff63c/lib/authenticator.js#L233> |
22,052,258 | I am building an authentication system using Passport.js using [Easy Node Authentication: Setup and Local tutorial](https://scotch.io/tutorials/easy-node-authentication-setup-and-local).
I am confused about what `passport.session()` does.
After playing around with the different middleware I came to understand that `express.session()` is what sends a session ID over cookies to the client, but I'm confused about what `passport.session()` does and why it is required in addition to `express.session()`.
Here is how I set up my application:
// Server.js configures the application and sets up the webserver
```
//importing our modules
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');
var configDB = require('./config/database.js');
//Configuration of Databse and App
mongoose.connect(configDB.url); //connect to our database
require('./config/passport')(passport); //pass passport for configuration
app.configure(function() {
//set up our express application
app.use(express.logger('dev')); //log every request to the console
app.use(express.cookieParser()); //read cookies (needed for auth)
app.use(express.bodyParser()); //get info from html forms
app.set('view engine', 'ejs'); //set up ejs for templating
//configuration for passport
app.use(express.session({ secret: 'olhosvermelhoseasenhaclassica', maxAge:null })); //session secret
app.use(passport.initialize());
app.use(passport.session()); //persistent login session
app.use(flash()); //use connect-flash for flash messages stored in session
});
//Set up routes
require('./app/routes.js')(app, passport);
//launch
app.listen(port);
console.log("Server listening on port" + port);
``` | 2014/02/26 | [
"https://Stackoverflow.com/questions/22052258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1835903/"
] | `passport.session()` acts as a middleware to alter the req object and change the 'user' value that is currently the session id (from the client cookie) into the true deserialized user object.
Whilst the other answers make some good points I thought that some more specific detail could be provided.
```
app.use(passport.session());
```
is equivalent to
```
app.use(passport.authenticate('session'));
```
Where 'session' refers to the following strategy that is bundled with passportJS.
Here's a link to the file:
<https://github.com/jaredhanson/passport/blob/master/lib/strategies/session.js>
And a [permalink](https://github.com/jaredhanson/passport/blob/b220766870cdbb98cc7570764cd3ced93da8945e/lib/strategies/session.js#L66) pointing to the following lines at the time of this writing:
```
var property = req._passport.instance._userProperty || 'user';
req[property] = user;
```
Where it essentially acts as a middleware and alters the value of the 'user' property in the req object to contain the deserialized identity of the user. To allow this to work correctly you must include `serializeUser` and `deserializeUser` functions in your custom code.
```
passport.serializeUser(function (user, done) {
done(null, user.id);
});
passport.deserializeUser(function (user, done) {
//If using Mongoose with MongoDB; if other you will need JS specific to that schema.
User.findById(user.id, function (err, user) {
done(err, user);
});
});
```
This will find the correct user from the database and pass it as a closure variable into the callback `done(err,user);` so the above code in the `passport.session()` can replace the 'user' value in the req object and pass on to the next middleware in the pile. | While you will be using `PassportJs` for validating the user as part of your login URL, you still need some mechanism to store this user information in the session and retrieve it with every subsequent request (i.e. serialize/deserialize the user).
So in effect, you are authenticating the user with every request, even though this authentication needn't look up a database or oauth as in the login response. So passport will treat session authentication also as yet another authentication strategy.
And to use this strategy - which is named `session`, just use a simple shortcut - `app.use(passport.session())`. Also note that this particular strategy will want you to implement serialize and deserialize functions for obvious reasons. |
5,590,203 | So I'm coming down to release-time for my application. We plan on releasing two versions, a free ad-based play-to-unlock version, and a paid fully unlocked version. I have the code set up that I can simply set a flag on startup to enable/disable ads and lock/unlock all the features. So literally only one line of code will execute differently between these versions.
In order to release two separate applications, they require different package names, so my question is this: Is there an easy way to refactor my application's package name? Eclipse's refactoring tool doesn't resolve the generated R file, or any XML references in layout and manifest files. I've attempted to make a new project using the original as source, but I can't reference the assets and resources, and I'm looking to avoid duplicating any of my code and assets. It's not a huge pain to refactor it manually, but I feel there must be a better way to do it. Anybody have an elegant solution to this?
Edit/Answered:
For my situation I find it perfectly acceptable to just use Project -> Android Tools -> Rename Application Package. I wasn't aware this existed, and I feel like an idiot for posting this now. Thanks for everyone's answers and comments, feel free to vote this closed. | 2011/04/08 | [
"https://Stackoverflow.com/questions/5590203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/615779/"
] | Possibly a duplicate of [Bulk Publishing of Android Apps](https://stackoverflow.com/questions/4740319/bulk-publishing-of-android-apps/4740728#4740728).
Android Library projects will do this for you nicely. You'll end up with 1 library project and then a project for each edition (free/full) with those really just containing different resources like app icons and different manifests, which is where the package name will be varied.
Hope that helps. It has worked well for me. | Gradle allows to use generated BuildConfig.java to pass some data to code.
```
productFlavors {
paid {
packageName "com.simple.paid"
buildConfigField 'boolean', 'PAID', 'true'
buildConfigField "int", "THING_ONE", "1"
}
free {
packageName "com.simple.free"
buildConfigField 'boolean', 'PAID', 'false'
buildConfigField "int", "THING_ONE", "0"
}
``` |
5,590,203 | So I'm coming down to release-time for my application. We plan on releasing two versions, a free ad-based play-to-unlock version, and a paid fully unlocked version. I have the code set up that I can simply set a flag on startup to enable/disable ads and lock/unlock all the features. So literally only one line of code will execute differently between these versions.
In order to release two separate applications, they require different package names, so my question is this: Is there an easy way to refactor my application's package name? Eclipse's refactoring tool doesn't resolve the generated R file, or any XML references in layout and manifest files. I've attempted to make a new project using the original as source, but I can't reference the assets and resources, and I'm looking to avoid duplicating any of my code and assets. It's not a huge pain to refactor it manually, but I feel there must be a better way to do it. Anybody have an elegant solution to this?
Edit/Answered:
For my situation I find it perfectly acceptable to just use Project -> Android Tools -> Rename Application Package. I wasn't aware this existed, and I feel like an idiot for posting this now. Thanks for everyone's answers and comments, feel free to vote this closed. | 2011/04/08 | [
"https://Stackoverflow.com/questions/5590203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/615779/"
] | The best way is to use "Android Studio" -> gradle.build -> [productFlavors + generate manifest file from template]. This combination allows to build free/paid versions and bunch of editions for different app markets from one source.
---
This is a part of templated manifest file:
---
```
<manifest android:versionCode="1" android:versionName="1" package="com.example.product" xmlns:android="http://schemas.android.com/apk/res/android">
<application android:allowBackup="true" android:icon="@drawable/ic_launcher"
android:label="@string/{f:FREE}app_name_free{/f}{f:PAID}app_name_paid{/f}"
android:name=".ApplicationMain" android:theme="@style/AppTheme">
<activity android:label="@string/{f:FREE}app_name_free{/f}{f:PAID}app_name_paid{/f}" android:name=".ActivityMain">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
```
---
This is template "ProductInfo.template" for java file: ProductInfo.java
---
```
package com.packagename.generated;
import com.packagename.R;
public class ProductInfo {
public static final boolean mIsPaidVersion = {f:PAID}true{/f}{f:FREE}false{/f};
public static final int mAppNameId = R.string.app_name_{f:PAID}paid{/f}{f:FREE}free{/f};
public static final boolean mIsDebug = {$DEBUG};
}
```
---
This manifest is processed by gradle.build script with **productFlavors** and **processManifest** task hook:
---
```
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.TaskAction
...
android {
...
productFlavors {
free {
packageName 'com.example.product.free'
}
paid {
packageName 'com.example.product.paid'
}
}
...
}
afterEvaluate { project ->
android.applicationVariants.each { variant ->
def flavor = variant.productFlavors[0].name
tasks['prepare' + variant.name + 'Dependencies'].doLast {
println "Generate java files..."
//Copy templated and processed by build system manifest file to filtered_manifests forder
def productInfoPath = "${projectDir}/some_sourcs_path/generated/"
copy {
from(productInfoPath)
into(productInfoPath)
include('ProductInfo.template')
rename('ProductInfo.template', 'ProductInfo.java')
}
tasks.create(name: variant.name + 'ProcessProductInfoJavaFile', type: processTemplateFile) {
templateFilePath = productInfoPath + "ProductInfo.java"
flavorName = flavor
buildTypeName = variant.buildType.name
}
tasks[variant.name + 'ProcessProductInfoJavaFile'].execute()
}
variant.processManifest.doLast {
println "Customization manifest file..."
// Copy templated and processed by build system manifest file to filtered_manifests forder
copy {
from("${buildDir}/manifests") {
include "${variant.dirName}/AndroidManifest.xml"
}
into("${buildDir}/filtered_manifests")
}
tasks.create(name: variant.name + 'ProcessManifestFile', type: processTemplateFile) {
templateFilePath = "${buildDir}/filtered_manifests/${variant.dirName}/AndroidManifest.xml"
flavorName = flavor
buildTypeName = variant.buildType.name
}
tasks[variant.name + 'ProcessManifestFile'].execute()
}
variant.processResources.manifestFile = file("${buildDir}/filtered_manifests/${variant.dirName}/AndroidManifest.xml")
}
}
```
---
This is separated task to process file
---
```
class processTemplateFile extends DefaultTask {
def String templateFilePath = ""
def String flavorName = ""
def String buildTypeName = ""
@TaskAction
void run() {
println templateFilePath
// Load file to memory
def fileObj = project.file(templateFilePath)
def content = fileObj.getText()
// Flavor. Find "{f:<flavor_name>}...{/f}" pattern and leave only "<flavor_name>==flavor"
def patternAttribute = Pattern.compile("\\{f:((?!${flavorName.toUpperCase()})).*?\\{/f\\}",Pattern.DOTALL);
content = patternAttribute.matcher(content).replaceAll("");
def pattern = Pattern.compile("\\{f:.*?\\}");
content = pattern.matcher(content).replaceAll("");
pattern = Pattern.compile("\\{/f\\}");
content = pattern.matcher(content).replaceAll("");
// Build. Find "{$DEBUG}" pattern and replace with "true"/"false"
pattern = Pattern.compile("\\{\\\$DEBUG\\}", Pattern.DOTALL);
if (buildTypeName == "debug"){
content = pattern.matcher(content).replaceAll("true");
}
else{
content = pattern.matcher(content).replaceAll("false");
}
// Save processed manifest file
fileObj.write(content)
}
}
```
**Updated:** processTemplateFile created for code reusing purposes. | If you want another application name, depending of the flavor, you can also add this:
```
productFlavors {
lite {
applicationId = 'com.project.test.app'
resValue "string", "app_name", "test lite"
versionCode 1
versionName '1.0.0'
}
pro {
applicationId = 'com.project.testpro.app'
resValue "string", "app_name", "test pro"
versionCode 1
versionName '1.0.0'
}
}
``` |
5,590,203 | So I'm coming down to release-time for my application. We plan on releasing two versions, a free ad-based play-to-unlock version, and a paid fully unlocked version. I have the code set up that I can simply set a flag on startup to enable/disable ads and lock/unlock all the features. So literally only one line of code will execute differently between these versions.
In order to release two separate applications, they require different package names, so my question is this: Is there an easy way to refactor my application's package name? Eclipse's refactoring tool doesn't resolve the generated R file, or any XML references in layout and manifest files. I've attempted to make a new project using the original as source, but I can't reference the assets and resources, and I'm looking to avoid duplicating any of my code and assets. It's not a huge pain to refactor it manually, but I feel there must be a better way to do it. Anybody have an elegant solution to this?
Edit/Answered:
For my situation I find it perfectly acceptable to just use Project -> Android Tools -> Rename Application Package. I wasn't aware this existed, and I feel like an idiot for posting this now. Thanks for everyone's answers and comments, feel free to vote this closed. | 2011/04/08 | [
"https://Stackoverflow.com/questions/5590203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/615779/"
] | Possibly a duplicate of [Bulk Publishing of Android Apps](https://stackoverflow.com/questions/4740319/bulk-publishing-of-android-apps/4740728#4740728).
Android Library projects will do this for you nicely. You'll end up with 1 library project and then a project for each edition (free/full) with those really just containing different resources like app icons and different manifests, which is where the package name will be varied.
Hope that helps. It has worked well for me. | If you want another application name, depending of the flavor, you can also add this:
```
productFlavors {
lite {
applicationId = 'com.project.test.app'
resValue "string", "app_name", "test lite"
versionCode 1
versionName '1.0.0'
}
pro {
applicationId = 'com.project.testpro.app'
resValue "string", "app_name", "test pro"
versionCode 1
versionName '1.0.0'
}
}
``` |
5,590,203 | So I'm coming down to release-time for my application. We plan on releasing two versions, a free ad-based play-to-unlock version, and a paid fully unlocked version. I have the code set up that I can simply set a flag on startup to enable/disable ads and lock/unlock all the features. So literally only one line of code will execute differently between these versions.
In order to release two separate applications, they require different package names, so my question is this: Is there an easy way to refactor my application's package name? Eclipse's refactoring tool doesn't resolve the generated R file, or any XML references in layout and manifest files. I've attempted to make a new project using the original as source, but I can't reference the assets and resources, and I'm looking to avoid duplicating any of my code and assets. It's not a huge pain to refactor it manually, but I feel there must be a better way to do it. Anybody have an elegant solution to this?
Edit/Answered:
For my situation I find it perfectly acceptable to just use Project -> Android Tools -> Rename Application Package. I wasn't aware this existed, and I feel like an idiot for posting this now. Thanks for everyone's answers and comments, feel free to vote this closed. | 2011/04/08 | [
"https://Stackoverflow.com/questions/5590203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/615779/"
] | Gradle allows to use generated BuildConfig.java to pass some data to code.
```
productFlavors {
paid {
packageName "com.simple.paid"
buildConfigField 'boolean', 'PAID', 'true'
buildConfigField "int", "THING_ONE", "1"
}
free {
packageName "com.simple.free"
buildConfigField 'boolean', 'PAID', 'false'
buildConfigField "int", "THING_ONE", "0"
}
``` | For everyone who want to use the solution by Denis:
In the new gradle version `packageName` is now `applicationId` and don't forget to put `productFlavors { ... }` in `android { ... }`
```
productFlavors {
lite {
applicationId = 'com.project.test.app'
versionCode 1
versionName '1.0.0'
}
pro {
applicationId = 'com.project.testpro.app'
versionCode 1
versionName '1.0.0'
}
}
``` |
5,590,203 | So I'm coming down to release-time for my application. We plan on releasing two versions, a free ad-based play-to-unlock version, and a paid fully unlocked version. I have the code set up that I can simply set a flag on startup to enable/disable ads and lock/unlock all the features. So literally only one line of code will execute differently between these versions.
In order to release two separate applications, they require different package names, so my question is this: Is there an easy way to refactor my application's package name? Eclipse's refactoring tool doesn't resolve the generated R file, or any XML references in layout and manifest files. I've attempted to make a new project using the original as source, but I can't reference the assets and resources, and I'm looking to avoid duplicating any of my code and assets. It's not a huge pain to refactor it manually, but I feel there must be a better way to do it. Anybody have an elegant solution to this?
Edit/Answered:
For my situation I find it perfectly acceptable to just use Project -> Android Tools -> Rename Application Package. I wasn't aware this existed, and I feel like an idiot for posting this now. Thanks for everyone's answers and comments, feel free to vote this closed. | 2011/04/08 | [
"https://Stackoverflow.com/questions/5590203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/615779/"
] | It's very simple by using build.gradle in Android Studio. Read about [productFlavors](http://tools.android.com/tech-docs/new-build-system/user-guide). It is a very usefull feature. Just simply add following lines in build.gradle:
```
productFlavors {
lite {
packageName = 'com.project.test.app'
versionCode 1
versionName '1.0.0'
}
pro {
packageName = 'com.project.testpro.app'
versionCode 1
versionName '1.0.0'
}
}
```
In this example I add two product flavors: first for lite version and second for full version. Each version has his own versionCode and versionName (for Google Play publication).
In code just check BuildConfig.FLAVOR:
```
if (BuildConfig.FLAVOR == "lite") {
// add some ads or restrict functionallity
}
```
For running and testing on device use "Build Variants" tab in Android Studio to switch between versions:
![enter image description here](https://i.stack.imgur.com/C4f2A.jpg) | The best way is to use "Android Studio" -> gradle.build -> [productFlavors + generate manifest file from template]. This combination allows to build free/paid versions and bunch of editions for different app markets from one source.
---
This is a part of templated manifest file:
---
```
<manifest android:versionCode="1" android:versionName="1" package="com.example.product" xmlns:android="http://schemas.android.com/apk/res/android">
<application android:allowBackup="true" android:icon="@drawable/ic_launcher"
android:label="@string/{f:FREE}app_name_free{/f}{f:PAID}app_name_paid{/f}"
android:name=".ApplicationMain" android:theme="@style/AppTheme">
<activity android:label="@string/{f:FREE}app_name_free{/f}{f:PAID}app_name_paid{/f}" android:name=".ActivityMain">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
```
---
This is template "ProductInfo.template" for java file: ProductInfo.java
---
```
package com.packagename.generated;
import com.packagename.R;
public class ProductInfo {
public static final boolean mIsPaidVersion = {f:PAID}true{/f}{f:FREE}false{/f};
public static final int mAppNameId = R.string.app_name_{f:PAID}paid{/f}{f:FREE}free{/f};
public static final boolean mIsDebug = {$DEBUG};
}
```
---
This manifest is processed by gradle.build script with **productFlavors** and **processManifest** task hook:
---
```
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.TaskAction
...
android {
...
productFlavors {
free {
packageName 'com.example.product.free'
}
paid {
packageName 'com.example.product.paid'
}
}
...
}
afterEvaluate { project ->
android.applicationVariants.each { variant ->
def flavor = variant.productFlavors[0].name
tasks['prepare' + variant.name + 'Dependencies'].doLast {
println "Generate java files..."
//Copy templated and processed by build system manifest file to filtered_manifests forder
def productInfoPath = "${projectDir}/some_sourcs_path/generated/"
copy {
from(productInfoPath)
into(productInfoPath)
include('ProductInfo.template')
rename('ProductInfo.template', 'ProductInfo.java')
}
tasks.create(name: variant.name + 'ProcessProductInfoJavaFile', type: processTemplateFile) {
templateFilePath = productInfoPath + "ProductInfo.java"
flavorName = flavor
buildTypeName = variant.buildType.name
}
tasks[variant.name + 'ProcessProductInfoJavaFile'].execute()
}
variant.processManifest.doLast {
println "Customization manifest file..."
// Copy templated and processed by build system manifest file to filtered_manifests forder
copy {
from("${buildDir}/manifests") {
include "${variant.dirName}/AndroidManifest.xml"
}
into("${buildDir}/filtered_manifests")
}
tasks.create(name: variant.name + 'ProcessManifestFile', type: processTemplateFile) {
templateFilePath = "${buildDir}/filtered_manifests/${variant.dirName}/AndroidManifest.xml"
flavorName = flavor
buildTypeName = variant.buildType.name
}
tasks[variant.name + 'ProcessManifestFile'].execute()
}
variant.processResources.manifestFile = file("${buildDir}/filtered_manifests/${variant.dirName}/AndroidManifest.xml")
}
}
```
---
This is separated task to process file
---
```
class processTemplateFile extends DefaultTask {
def String templateFilePath = ""
def String flavorName = ""
def String buildTypeName = ""
@TaskAction
void run() {
println templateFilePath
// Load file to memory
def fileObj = project.file(templateFilePath)
def content = fileObj.getText()
// Flavor. Find "{f:<flavor_name>}...{/f}" pattern and leave only "<flavor_name>==flavor"
def patternAttribute = Pattern.compile("\\{f:((?!${flavorName.toUpperCase()})).*?\\{/f\\}",Pattern.DOTALL);
content = patternAttribute.matcher(content).replaceAll("");
def pattern = Pattern.compile("\\{f:.*?\\}");
content = pattern.matcher(content).replaceAll("");
pattern = Pattern.compile("\\{/f\\}");
content = pattern.matcher(content).replaceAll("");
// Build. Find "{$DEBUG}" pattern and replace with "true"/"false"
pattern = Pattern.compile("\\{\\\$DEBUG\\}", Pattern.DOTALL);
if (buildTypeName == "debug"){
content = pattern.matcher(content).replaceAll("true");
}
else{
content = pattern.matcher(content).replaceAll("false");
}
// Save processed manifest file
fileObj.write(content)
}
}
```
**Updated:** processTemplateFile created for code reusing purposes. |
5,590,203 | So I'm coming down to release-time for my application. We plan on releasing two versions, a free ad-based play-to-unlock version, and a paid fully unlocked version. I have the code set up that I can simply set a flag on startup to enable/disable ads and lock/unlock all the features. So literally only one line of code will execute differently between these versions.
In order to release two separate applications, they require different package names, so my question is this: Is there an easy way to refactor my application's package name? Eclipse's refactoring tool doesn't resolve the generated R file, or any XML references in layout and manifest files. I've attempted to make a new project using the original as source, but I can't reference the assets and resources, and I'm looking to avoid duplicating any of my code and assets. It's not a huge pain to refactor it manually, but I feel there must be a better way to do it. Anybody have an elegant solution to this?
Edit/Answered:
For my situation I find it perfectly acceptable to just use Project -> Android Tools -> Rename Application Package. I wasn't aware this existed, and I feel like an idiot for posting this now. Thanks for everyone's answers and comments, feel free to vote this closed. | 2011/04/08 | [
"https://Stackoverflow.com/questions/5590203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/615779/"
] | For everyone who want to use the solution by Denis:
In the new gradle version `packageName` is now `applicationId` and don't forget to put `productFlavors { ... }` in `android { ... }`
```
productFlavors {
lite {
applicationId = 'com.project.test.app'
versionCode 1
versionName '1.0.0'
}
pro {
applicationId = 'com.project.testpro.app'
versionCode 1
versionName '1.0.0'
}
}
``` | One approach I'm experimenting with is using fully-qualified names for activities, and just changing the package attribute. It avoids any real refactoring (1 file copy, 1 text sub).
This almost works, but the generated R class isn't picked up, as the package for this is pulled out of AndroidManifest.xml, so ends up in the new package.
I think it should be fairly straight forward to build AndroidManifest.xml via an Ant rule (in -pre-build) that inserts the distribution package name, and then (in -pre-compile) the generated resources into the default (Java) package.
Hope this helps,
Phil Lello |
5,590,203 | So I'm coming down to release-time for my application. We plan on releasing two versions, a free ad-based play-to-unlock version, and a paid fully unlocked version. I have the code set up that I can simply set a flag on startup to enable/disable ads and lock/unlock all the features. So literally only one line of code will execute differently between these versions.
In order to release two separate applications, they require different package names, so my question is this: Is there an easy way to refactor my application's package name? Eclipse's refactoring tool doesn't resolve the generated R file, or any XML references in layout and manifest files. I've attempted to make a new project using the original as source, but I can't reference the assets and resources, and I'm looking to avoid duplicating any of my code and assets. It's not a huge pain to refactor it manually, but I feel there must be a better way to do it. Anybody have an elegant solution to this?
Edit/Answered:
For my situation I find it perfectly acceptable to just use Project -> Android Tools -> Rename Application Package. I wasn't aware this existed, and I feel like an idiot for posting this now. Thanks for everyone's answers and comments, feel free to vote this closed. | 2011/04/08 | [
"https://Stackoverflow.com/questions/5590203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/615779/"
] | For everyone who want to use the solution by Denis:
In the new gradle version `packageName` is now `applicationId` and don't forget to put `productFlavors { ... }` in `android { ... }`
```
productFlavors {
lite {
applicationId = 'com.project.test.app'
versionCode 1
versionName '1.0.0'
}
pro {
applicationId = 'com.project.testpro.app'
versionCode 1
versionName '1.0.0'
}
}
``` | If you want another application name, depending of the flavor, you can also add this:
```
productFlavors {
lite {
applicationId = 'com.project.test.app'
resValue "string", "app_name", "test lite"
versionCode 1
versionName '1.0.0'
}
pro {
applicationId = 'com.project.testpro.app'
resValue "string", "app_name", "test pro"
versionCode 1
versionName '1.0.0'
}
}
``` |
5,590,203 | So I'm coming down to release-time for my application. We plan on releasing two versions, a free ad-based play-to-unlock version, and a paid fully unlocked version. I have the code set up that I can simply set a flag on startup to enable/disable ads and lock/unlock all the features. So literally only one line of code will execute differently between these versions.
In order to release two separate applications, they require different package names, so my question is this: Is there an easy way to refactor my application's package name? Eclipse's refactoring tool doesn't resolve the generated R file, or any XML references in layout and manifest files. I've attempted to make a new project using the original as source, but I can't reference the assets and resources, and I'm looking to avoid duplicating any of my code and assets. It's not a huge pain to refactor it manually, but I feel there must be a better way to do it. Anybody have an elegant solution to this?
Edit/Answered:
For my situation I find it perfectly acceptable to just use Project -> Android Tools -> Rename Application Package. I wasn't aware this existed, and I feel like an idiot for posting this now. Thanks for everyone's answers and comments, feel free to vote this closed. | 2011/04/08 | [
"https://Stackoverflow.com/questions/5590203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/615779/"
] | The best way is to use "Android Studio" -> gradle.build -> [productFlavors + generate manifest file from template]. This combination allows to build free/paid versions and bunch of editions for different app markets from one source.
---
This is a part of templated manifest file:
---
```
<manifest android:versionCode="1" android:versionName="1" package="com.example.product" xmlns:android="http://schemas.android.com/apk/res/android">
<application android:allowBackup="true" android:icon="@drawable/ic_launcher"
android:label="@string/{f:FREE}app_name_free{/f}{f:PAID}app_name_paid{/f}"
android:name=".ApplicationMain" android:theme="@style/AppTheme">
<activity android:label="@string/{f:FREE}app_name_free{/f}{f:PAID}app_name_paid{/f}" android:name=".ActivityMain">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
```
---
This is template "ProductInfo.template" for java file: ProductInfo.java
---
```
package com.packagename.generated;
import com.packagename.R;
public class ProductInfo {
public static final boolean mIsPaidVersion = {f:PAID}true{/f}{f:FREE}false{/f};
public static final int mAppNameId = R.string.app_name_{f:PAID}paid{/f}{f:FREE}free{/f};
public static final boolean mIsDebug = {$DEBUG};
}
```
---
This manifest is processed by gradle.build script with **productFlavors** and **processManifest** task hook:
---
```
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.TaskAction
...
android {
...
productFlavors {
free {
packageName 'com.example.product.free'
}
paid {
packageName 'com.example.product.paid'
}
}
...
}
afterEvaluate { project ->
android.applicationVariants.each { variant ->
def flavor = variant.productFlavors[0].name
tasks['prepare' + variant.name + 'Dependencies'].doLast {
println "Generate java files..."
//Copy templated and processed by build system manifest file to filtered_manifests forder
def productInfoPath = "${projectDir}/some_sourcs_path/generated/"
copy {
from(productInfoPath)
into(productInfoPath)
include('ProductInfo.template')
rename('ProductInfo.template', 'ProductInfo.java')
}
tasks.create(name: variant.name + 'ProcessProductInfoJavaFile', type: processTemplateFile) {
templateFilePath = productInfoPath + "ProductInfo.java"
flavorName = flavor
buildTypeName = variant.buildType.name
}
tasks[variant.name + 'ProcessProductInfoJavaFile'].execute()
}
variant.processManifest.doLast {
println "Customization manifest file..."
// Copy templated and processed by build system manifest file to filtered_manifests forder
copy {
from("${buildDir}/manifests") {
include "${variant.dirName}/AndroidManifest.xml"
}
into("${buildDir}/filtered_manifests")
}
tasks.create(name: variant.name + 'ProcessManifestFile', type: processTemplateFile) {
templateFilePath = "${buildDir}/filtered_manifests/${variant.dirName}/AndroidManifest.xml"
flavorName = flavor
buildTypeName = variant.buildType.name
}
tasks[variant.name + 'ProcessManifestFile'].execute()
}
variant.processResources.manifestFile = file("${buildDir}/filtered_manifests/${variant.dirName}/AndroidManifest.xml")
}
}
```
---
This is separated task to process file
---
```
class processTemplateFile extends DefaultTask {
def String templateFilePath = ""
def String flavorName = ""
def String buildTypeName = ""
@TaskAction
void run() {
println templateFilePath
// Load file to memory
def fileObj = project.file(templateFilePath)
def content = fileObj.getText()
// Flavor. Find "{f:<flavor_name>}...{/f}" pattern and leave only "<flavor_name>==flavor"
def patternAttribute = Pattern.compile("\\{f:((?!${flavorName.toUpperCase()})).*?\\{/f\\}",Pattern.DOTALL);
content = patternAttribute.matcher(content).replaceAll("");
def pattern = Pattern.compile("\\{f:.*?\\}");
content = pattern.matcher(content).replaceAll("");
pattern = Pattern.compile("\\{/f\\}");
content = pattern.matcher(content).replaceAll("");
// Build. Find "{$DEBUG}" pattern and replace with "true"/"false"
pattern = Pattern.compile("\\{\\\$DEBUG\\}", Pattern.DOTALL);
if (buildTypeName == "debug"){
content = pattern.matcher(content).replaceAll("true");
}
else{
content = pattern.matcher(content).replaceAll("false");
}
// Save processed manifest file
fileObj.write(content)
}
}
```
**Updated:** processTemplateFile created for code reusing purposes. | For everyone who want to use the solution by Denis:
In the new gradle version `packageName` is now `applicationId` and don't forget to put `productFlavors { ... }` in `android { ... }`
```
productFlavors {
lite {
applicationId = 'com.project.test.app'
versionCode 1
versionName '1.0.0'
}
pro {
applicationId = 'com.project.testpro.app'
versionCode 1
versionName '1.0.0'
}
}
``` |
5,590,203 | So I'm coming down to release-time for my application. We plan on releasing two versions, a free ad-based play-to-unlock version, and a paid fully unlocked version. I have the code set up that I can simply set a flag on startup to enable/disable ads and lock/unlock all the features. So literally only one line of code will execute differently between these versions.
In order to release two separate applications, they require different package names, so my question is this: Is there an easy way to refactor my application's package name? Eclipse's refactoring tool doesn't resolve the generated R file, or any XML references in layout and manifest files. I've attempted to make a new project using the original as source, but I can't reference the assets and resources, and I'm looking to avoid duplicating any of my code and assets. It's not a huge pain to refactor it manually, but I feel there must be a better way to do it. Anybody have an elegant solution to this?
Edit/Answered:
For my situation I find it perfectly acceptable to just use Project -> Android Tools -> Rename Application Package. I wasn't aware this existed, and I feel like an idiot for posting this now. Thanks for everyone's answers and comments, feel free to vote this closed. | 2011/04/08 | [
"https://Stackoverflow.com/questions/5590203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/615779/"
] | Possibly a duplicate of [Bulk Publishing of Android Apps](https://stackoverflow.com/questions/4740319/bulk-publishing-of-android-apps/4740728#4740728).
Android Library projects will do this for you nicely. You'll end up with 1 library project and then a project for each edition (free/full) with those really just containing different resources like app icons and different manifests, which is where the package name will be varied.
Hope that helps. It has worked well for me. | One approach I'm experimenting with is using fully-qualified names for activities, and just changing the package attribute. It avoids any real refactoring (1 file copy, 1 text sub).
This almost works, but the generated R class isn't picked up, as the package for this is pulled out of AndroidManifest.xml, so ends up in the new package.
I think it should be fairly straight forward to build AndroidManifest.xml via an Ant rule (in -pre-build) that inserts the distribution package name, and then (in -pre-compile) the generated resources into the default (Java) package.
Hope this helps,
Phil Lello |
5,590,203 | So I'm coming down to release-time for my application. We plan on releasing two versions, a free ad-based play-to-unlock version, and a paid fully unlocked version. I have the code set up that I can simply set a flag on startup to enable/disable ads and lock/unlock all the features. So literally only one line of code will execute differently between these versions.
In order to release two separate applications, they require different package names, so my question is this: Is there an easy way to refactor my application's package name? Eclipse's refactoring tool doesn't resolve the generated R file, or any XML references in layout and manifest files. I've attempted to make a new project using the original as source, but I can't reference the assets and resources, and I'm looking to avoid duplicating any of my code and assets. It's not a huge pain to refactor it manually, but I feel there must be a better way to do it. Anybody have an elegant solution to this?
Edit/Answered:
For my situation I find it perfectly acceptable to just use Project -> Android Tools -> Rename Application Package. I wasn't aware this existed, and I feel like an idiot for posting this now. Thanks for everyone's answers and comments, feel free to vote this closed. | 2011/04/08 | [
"https://Stackoverflow.com/questions/5590203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/615779/"
] | Gradle allows to use generated BuildConfig.java to pass some data to code.
```
productFlavors {
paid {
packageName "com.simple.paid"
buildConfigField 'boolean', 'PAID', 'true'
buildConfigField "int", "THING_ONE", "1"
}
free {
packageName "com.simple.free"
buildConfigField 'boolean', 'PAID', 'false'
buildConfigField "int", "THING_ONE", "0"
}
``` | If you want another application name, depending of the flavor, you can also add this:
```
productFlavors {
lite {
applicationId = 'com.project.test.app'
resValue "string", "app_name", "test lite"
versionCode 1
versionName '1.0.0'
}
pro {
applicationId = 'com.project.testpro.app'
resValue "string", "app_name", "test pro"
versionCode 1
versionName '1.0.0'
}
}
``` |
1,439,686 | Prove that $|a^2-b^2| < 2|a| + 1$ given that $|a-b|<1$
I understand that a variant of the triangle inequality is used in the solution: $|b| - |a| \le |a-b|$
I'm confused as to how it's derived, can anybody help me understand
Thank you for your time | 2015/09/17 | [
"https://math.stackexchange.com/questions/1439686",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/189897/"
] | $$|a^2-b^2|=|a-b||a+b|<1.|a+b|\leq|a|+|b|<|a|+|a|+1=2|a|+1$$ where we used $|b|\leq |a|+|a-b|<|a|+1$. The last one follows from triangle inequality again:
Substitute in $|x+y|\leq |x|+|y|$ $x=b-a$ and $y=a$ to get $|b-a+a|\leq |b-a|+|a|$ | $$2|a|+1>|a^2-b^2|\ge|b^2|-|a^2|$$
$$\iff(|a|+1)^2\ge|b^2|\iff |a|+1\ge |b|$$
$$1\ge |b|-|a|\ge|b-a|$$ |
1,439,686 | Prove that $|a^2-b^2| < 2|a| + 1$ given that $|a-b|<1$
I understand that a variant of the triangle inequality is used in the solution: $|b| - |a| \le |a-b|$
I'm confused as to how it's derived, can anybody help me understand
Thank you for your time | 2015/09/17 | [
"https://math.stackexchange.com/questions/1439686",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/189897/"
] | $$|a^2-b^2|=|a-b||a+b|<1.|a+b|\leq|a|+|b|<|a|+|a|+1=2|a|+1$$ where we used $|b|\leq |a|+|a-b|<|a|+1$. The last one follows from triangle inequality again:
Substitute in $|x+y|\leq |x|+|y|$ $x=b-a$ and $y=a$ to get $|b-a+a|\leq |b-a|+|a|$ | We have
$$|a^2-b^2|=|a-b|\cdot|a+b|<|a+b|\le |a|+|b|\tag1$$
moreover,
$$|b|-|a|\le|a-b|<1\implies |b|<|a|+1\tag2$$
We deduce the desired result from $(1)$ and $(2)$. |
43,752,286 | A bit tricky situation. For the code below, I have added `(keydown.enter)="false"` to ignore the break line/enter button in textarea
This is causing a user issue and would like the existing behaviour where Pressing enter should automatically trigger the "Save button"
Any idea how to trigger the Save button when still focusing in textArea but ignore the breakline?
```
<textarea #textArea
style="overflow:hidden; height:auto; resize:none;"
rows="1"
class="form-control"
[attr.placeholder]="placeholder"
[attr.maxlength]="maxlength"
[attr.autofocus]="autofocus"
[name]="name"
[attr.readonly]="readonly ? true : null"
[attr.required]="required ? true : null"
(input)="onUpdated($event)"
[tabindex]="skipTab ? -1 : ''"
(keydown.enter)="false"
[(ngModel)]="value">
</textarea >
``` | 2017/05/03 | [
"https://Stackoverflow.com/questions/43752286",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/485445/"
] | you can bind the same function of `Save` button to `keydown.enter` of texterea, and call `$event.preventDefault` to avoid the newline.
sample [plunker](https://plnkr.co/edit/J2DwmYBcD2D0evSGcQMX?p=preview). | You can create a service which can send a notification to other components that will handle the command. The service could look like this:
```
import { Injectable } from "@angular/core";
import { Subject } from "rxjs/Subject";
@Injectable()
export class DataSavingService {
private dataSavingRequested = new Subject<void>();
public dataSavingRequested$ = this.dataSavingRequested.asObservable();
public requestDataSaving(): void {
this.dataSavingRequested.next();
}
}
```
... and should be registered in the `providers` section of the module. Note: if data must be passed in the notification, you can declare a non-void parameter type for the `dataSavingRequested` Subject (e.g. `string`).
The service would be injected in the component with the textarea element and called in the handler of the `Enter` keypress event:
```
import { DataSavingService } from "./services/data-saving.service";
...
@Component({
template: `
<textarea (keypress.enter)="handleEnterKeyPress($event)" ...></textarea>
`
})
export class ComponentWithTextarea {
constructor(private dataSavingService: DataSavingService, ...) {
...
}
public handleEnterKeyPress(event: KeyboardEvent): void {
event.preventDefault(); // Prevent the insertion of a new line
this.dataSavingService.requestDataSaving();
}
...
}
```
The component with the Save button would subscribe to the `dataSavingRequested$` notification of the service and save the data when notified:
```
import { Component, OnDestroy, ... } from "@angular/core";
import { Subscription } from "rxjs/Subscription";
import { DataSavingService } from "../services/data-saving.service";
...
@Component({
...
})
export class ComponentWithSaveButton implements OnDestroy {
private subscription: Subscription;
constructor(private dataSavingService: DataSavingService, ...) {
this.subscription = this.dataSavingService.dataSavingRequested$.subscribe(() => {
this.saveData();
});
}
public ngOnDestroy(): void {
this.subscription.unsubscribe();
}
private saveData(): void {
// Perform data saving here
// Note: this method should also be called by the Save button
...
}
}
```
---
The code above assumes that the saving must be performed in the component with the Save button. An alternative would be to move that logic into the service, which would expose a `saveData` method that could be called by the components. The service would need to gather the data to save, however. It could be obtained with a Subject/Observable mechanism, or supplied directly by the components as a parameter to `saveData` or by calling another method of the service. |
43,752,286 | A bit tricky situation. For the code below, I have added `(keydown.enter)="false"` to ignore the break line/enter button in textarea
This is causing a user issue and would like the existing behaviour where Pressing enter should automatically trigger the "Save button"
Any idea how to trigger the Save button when still focusing in textArea but ignore the breakline?
```
<textarea #textArea
style="overflow:hidden; height:auto; resize:none;"
rows="1"
class="form-control"
[attr.placeholder]="placeholder"
[attr.maxlength]="maxlength"
[attr.autofocus]="autofocus"
[name]="name"
[attr.readonly]="readonly ? true : null"
[attr.required]="required ? true : null"
(input)="onUpdated($event)"
[tabindex]="skipTab ? -1 : ''"
(keydown.enter)="false"
[(ngModel)]="value">
</textarea >
``` | 2017/05/03 | [
"https://Stackoverflow.com/questions/43752286",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/485445/"
] | Extending the answer by @Pengyy
You can bind the bind the enter key to a pseudoSave function, and preventDefault inside of that, thus preventing both the Save function and the newline. Then you can either call the save function from there(assuming it is accessible such as a service) or you can emit an EventEmitter, and have that emit get caught to trigger the Save function. | you can bind the same function of `Save` button to `keydown.enter` of texterea, and call `$event.preventDefault` to avoid the newline.
sample [plunker](https://plnkr.co/edit/J2DwmYBcD2D0evSGcQMX?p=preview). |
43,752,286 | A bit tricky situation. For the code below, I have added `(keydown.enter)="false"` to ignore the break line/enter button in textarea
This is causing a user issue and would like the existing behaviour where Pressing enter should automatically trigger the "Save button"
Any idea how to trigger the Save button when still focusing in textArea but ignore the breakline?
```
<textarea #textArea
style="overflow:hidden; height:auto; resize:none;"
rows="1"
class="form-control"
[attr.placeholder]="placeholder"
[attr.maxlength]="maxlength"
[attr.autofocus]="autofocus"
[name]="name"
[attr.readonly]="readonly ? true : null"
[attr.required]="required ? true : null"
(input)="onUpdated($event)"
[tabindex]="skipTab ? -1 : ''"
(keydown.enter)="false"
[(ngModel)]="value">
</textarea >
``` | 2017/05/03 | [
"https://Stackoverflow.com/questions/43752286",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/485445/"
] | you can bind the same function of `Save` button to `keydown.enter` of texterea, and call `$event.preventDefault` to avoid the newline.
sample [plunker](https://plnkr.co/edit/J2DwmYBcD2D0evSGcQMX?p=preview). | it could be 2 solutions:
1. Use javascript to handle enter event and trigger Save function in it
or
2. Use Same thing from Angular side as describe in [this](https://stackoverflow.com/questions/17470790/how-to-use-a-keypress-event-in-angularjs).
[This](https://stackoverflow.com/questions/2099661/enter-key-in-textarea) may also help you |
43,752,286 | A bit tricky situation. For the code below, I have added `(keydown.enter)="false"` to ignore the break line/enter button in textarea
This is causing a user issue and would like the existing behaviour where Pressing enter should automatically trigger the "Save button"
Any idea how to trigger the Save button when still focusing in textArea but ignore the breakline?
```
<textarea #textArea
style="overflow:hidden; height:auto; resize:none;"
rows="1"
class="form-control"
[attr.placeholder]="placeholder"
[attr.maxlength]="maxlength"
[attr.autofocus]="autofocus"
[name]="name"
[attr.readonly]="readonly ? true : null"
[attr.required]="required ? true : null"
(input)="onUpdated($event)"
[tabindex]="skipTab ? -1 : ''"
(keydown.enter)="false"
[(ngModel)]="value">
</textarea >
``` | 2017/05/03 | [
"https://Stackoverflow.com/questions/43752286",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/485445/"
] | Assuming that your `textarea` is inside a `form` element.
[**{Plunker Demo}**](https://plnkr.co/edit/0ojy8fQdP2abzfQZNZud?p=preview)
You can achieve it by using a **hidden submit** input, like this
```
@Component({
selector: 'my-app',
template: `
<form (submit)="formSubmitted($event)">
<input #proxySubmitBtn type="submit" [hidden]="true"/>
<textarea #textArea (keydown.enter)="$event.preventDefault(); proxySubmitBtn.click()">
</textarea>
</form>
`,
})
export class App {
formSubmitted(e) {
e.preventDefault();
alert('Form is submitted!');
}
}
``` | You can create a service which can send a notification to other components that will handle the command. The service could look like this:
```
import { Injectable } from "@angular/core";
import { Subject } from "rxjs/Subject";
@Injectable()
export class DataSavingService {
private dataSavingRequested = new Subject<void>();
public dataSavingRequested$ = this.dataSavingRequested.asObservable();
public requestDataSaving(): void {
this.dataSavingRequested.next();
}
}
```
... and should be registered in the `providers` section of the module. Note: if data must be passed in the notification, you can declare a non-void parameter type for the `dataSavingRequested` Subject (e.g. `string`).
The service would be injected in the component with the textarea element and called in the handler of the `Enter` keypress event:
```
import { DataSavingService } from "./services/data-saving.service";
...
@Component({
template: `
<textarea (keypress.enter)="handleEnterKeyPress($event)" ...></textarea>
`
})
export class ComponentWithTextarea {
constructor(private dataSavingService: DataSavingService, ...) {
...
}
public handleEnterKeyPress(event: KeyboardEvent): void {
event.preventDefault(); // Prevent the insertion of a new line
this.dataSavingService.requestDataSaving();
}
...
}
```
The component with the Save button would subscribe to the `dataSavingRequested$` notification of the service and save the data when notified:
```
import { Component, OnDestroy, ... } from "@angular/core";
import { Subscription } from "rxjs/Subscription";
import { DataSavingService } from "../services/data-saving.service";
...
@Component({
...
})
export class ComponentWithSaveButton implements OnDestroy {
private subscription: Subscription;
constructor(private dataSavingService: DataSavingService, ...) {
this.subscription = this.dataSavingService.dataSavingRequested$.subscribe(() => {
this.saveData();
});
}
public ngOnDestroy(): void {
this.subscription.unsubscribe();
}
private saveData(): void {
// Perform data saving here
// Note: this method should also be called by the Save button
...
}
}
```
---
The code above assumes that the saving must be performed in the component with the Save button. An alternative would be to move that logic into the service, which would expose a `saveData` method that could be called by the components. The service would need to gather the data to save, however. It could be obtained with a Subject/Observable mechanism, or supplied directly by the components as a parameter to `saveData` or by calling another method of the service. |
43,752,286 | A bit tricky situation. For the code below, I have added `(keydown.enter)="false"` to ignore the break line/enter button in textarea
This is causing a user issue and would like the existing behaviour where Pressing enter should automatically trigger the "Save button"
Any idea how to trigger the Save button when still focusing in textArea but ignore the breakline?
```
<textarea #textArea
style="overflow:hidden; height:auto; resize:none;"
rows="1"
class="form-control"
[attr.placeholder]="placeholder"
[attr.maxlength]="maxlength"
[attr.autofocus]="autofocus"
[name]="name"
[attr.readonly]="readonly ? true : null"
[attr.required]="required ? true : null"
(input)="onUpdated($event)"
[tabindex]="skipTab ? -1 : ''"
(keydown.enter)="false"
[(ngModel)]="value">
</textarea >
``` | 2017/05/03 | [
"https://Stackoverflow.com/questions/43752286",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/485445/"
] | Extending the answer by @Pengyy
You can bind the bind the enter key to a pseudoSave function, and preventDefault inside of that, thus preventing both the Save function and the newline. Then you can either call the save function from there(assuming it is accessible such as a service) or you can emit an EventEmitter, and have that emit get caught to trigger the Save function. | You can create a service which can send a notification to other components that will handle the command. The service could look like this:
```
import { Injectable } from "@angular/core";
import { Subject } from "rxjs/Subject";
@Injectable()
export class DataSavingService {
private dataSavingRequested = new Subject<void>();
public dataSavingRequested$ = this.dataSavingRequested.asObservable();
public requestDataSaving(): void {
this.dataSavingRequested.next();
}
}
```
... and should be registered in the `providers` section of the module. Note: if data must be passed in the notification, you can declare a non-void parameter type for the `dataSavingRequested` Subject (e.g. `string`).
The service would be injected in the component with the textarea element and called in the handler of the `Enter` keypress event:
```
import { DataSavingService } from "./services/data-saving.service";
...
@Component({
template: `
<textarea (keypress.enter)="handleEnterKeyPress($event)" ...></textarea>
`
})
export class ComponentWithTextarea {
constructor(private dataSavingService: DataSavingService, ...) {
...
}
public handleEnterKeyPress(event: KeyboardEvent): void {
event.preventDefault(); // Prevent the insertion of a new line
this.dataSavingService.requestDataSaving();
}
...
}
```
The component with the Save button would subscribe to the `dataSavingRequested$` notification of the service and save the data when notified:
```
import { Component, OnDestroy, ... } from "@angular/core";
import { Subscription } from "rxjs/Subscription";
import { DataSavingService } from "../services/data-saving.service";
...
@Component({
...
})
export class ComponentWithSaveButton implements OnDestroy {
private subscription: Subscription;
constructor(private dataSavingService: DataSavingService, ...) {
this.subscription = this.dataSavingService.dataSavingRequested$.subscribe(() => {
this.saveData();
});
}
public ngOnDestroy(): void {
this.subscription.unsubscribe();
}
private saveData(): void {
// Perform data saving here
// Note: this method should also be called by the Save button
...
}
}
```
---
The code above assumes that the saving must be performed in the component with the Save button. An alternative would be to move that logic into the service, which would expose a `saveData` method that could be called by the components. The service would need to gather the data to save, however. It could be obtained with a Subject/Observable mechanism, or supplied directly by the components as a parameter to `saveData` or by calling another method of the service. |
43,752,286 | A bit tricky situation. For the code below, I have added `(keydown.enter)="false"` to ignore the break line/enter button in textarea
This is causing a user issue and would like the existing behaviour where Pressing enter should automatically trigger the "Save button"
Any idea how to trigger the Save button when still focusing in textArea but ignore the breakline?
```
<textarea #textArea
style="overflow:hidden; height:auto; resize:none;"
rows="1"
class="form-control"
[attr.placeholder]="placeholder"
[attr.maxlength]="maxlength"
[attr.autofocus]="autofocus"
[name]="name"
[attr.readonly]="readonly ? true : null"
[attr.required]="required ? true : null"
(input)="onUpdated($event)"
[tabindex]="skipTab ? -1 : ''"
(keydown.enter)="false"
[(ngModel)]="value">
</textarea >
``` | 2017/05/03 | [
"https://Stackoverflow.com/questions/43752286",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/485445/"
] | Extending the answer by @Pengyy
You can bind the bind the enter key to a pseudoSave function, and preventDefault inside of that, thus preventing both the Save function and the newline. Then you can either call the save function from there(assuming it is accessible such as a service) or you can emit an EventEmitter, and have that emit get caught to trigger the Save function. | Assuming that your `textarea` is inside a `form` element.
[**{Plunker Demo}**](https://plnkr.co/edit/0ojy8fQdP2abzfQZNZud?p=preview)
You can achieve it by using a **hidden submit** input, like this
```
@Component({
selector: 'my-app',
template: `
<form (submit)="formSubmitted($event)">
<input #proxySubmitBtn type="submit" [hidden]="true"/>
<textarea #textArea (keydown.enter)="$event.preventDefault(); proxySubmitBtn.click()">
</textarea>
</form>
`,
})
export class App {
formSubmitted(e) {
e.preventDefault();
alert('Form is submitted!');
}
}
``` |
43,752,286 | A bit tricky situation. For the code below, I have added `(keydown.enter)="false"` to ignore the break line/enter button in textarea
This is causing a user issue and would like the existing behaviour where Pressing enter should automatically trigger the "Save button"
Any idea how to trigger the Save button when still focusing in textArea but ignore the breakline?
```
<textarea #textArea
style="overflow:hidden; height:auto; resize:none;"
rows="1"
class="form-control"
[attr.placeholder]="placeholder"
[attr.maxlength]="maxlength"
[attr.autofocus]="autofocus"
[name]="name"
[attr.readonly]="readonly ? true : null"
[attr.required]="required ? true : null"
(input)="onUpdated($event)"
[tabindex]="skipTab ? -1 : ''"
(keydown.enter)="false"
[(ngModel)]="value">
</textarea >
``` | 2017/05/03 | [
"https://Stackoverflow.com/questions/43752286",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/485445/"
] | Assuming that your `textarea` is inside a `form` element.
[**{Plunker Demo}**](https://plnkr.co/edit/0ojy8fQdP2abzfQZNZud?p=preview)
You can achieve it by using a **hidden submit** input, like this
```
@Component({
selector: 'my-app',
template: `
<form (submit)="formSubmitted($event)">
<input #proxySubmitBtn type="submit" [hidden]="true"/>
<textarea #textArea (keydown.enter)="$event.preventDefault(); proxySubmitBtn.click()">
</textarea>
</form>
`,
})
export class App {
formSubmitted(e) {
e.preventDefault();
alert('Form is submitted!');
}
}
``` | it could be 2 solutions:
1. Use javascript to handle enter event and trigger Save function in it
or
2. Use Same thing from Angular side as describe in [this](https://stackoverflow.com/questions/17470790/how-to-use-a-keypress-event-in-angularjs).
[This](https://stackoverflow.com/questions/2099661/enter-key-in-textarea) may also help you |
43,752,286 | A bit tricky situation. For the code below, I have added `(keydown.enter)="false"` to ignore the break line/enter button in textarea
This is causing a user issue and would like the existing behaviour where Pressing enter should automatically trigger the "Save button"
Any idea how to trigger the Save button when still focusing in textArea but ignore the breakline?
```
<textarea #textArea
style="overflow:hidden; height:auto; resize:none;"
rows="1"
class="form-control"
[attr.placeholder]="placeholder"
[attr.maxlength]="maxlength"
[attr.autofocus]="autofocus"
[name]="name"
[attr.readonly]="readonly ? true : null"
[attr.required]="required ? true : null"
(input)="onUpdated($event)"
[tabindex]="skipTab ? -1 : ''"
(keydown.enter)="false"
[(ngModel)]="value">
</textarea >
``` | 2017/05/03 | [
"https://Stackoverflow.com/questions/43752286",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/485445/"
] | Extending the answer by @Pengyy
You can bind the bind the enter key to a pseudoSave function, and preventDefault inside of that, thus preventing both the Save function and the newline. Then you can either call the save function from there(assuming it is accessible such as a service) or you can emit an EventEmitter, and have that emit get caught to trigger the Save function. | it could be 2 solutions:
1. Use javascript to handle enter event and trigger Save function in it
or
2. Use Same thing from Angular side as describe in [this](https://stackoverflow.com/questions/17470790/how-to-use-a-keypress-event-in-angularjs).
[This](https://stackoverflow.com/questions/2099661/enter-key-in-textarea) may also help you |
6,979,796 | I am a little bit confused about the use of [`Thread.yield()`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Thread.html#yield()) method in Java, specifically in the example code below. I've also read that yield() is 'used to prevent execution of a thread'.
My questions are:
1. I believe the code below result in the same output both when using `yield()` and when not using it. Is this correct?
2. What are, in fact, the main uses of `yield()`?
3. In what ways is `yield()` different from the `join()` and `interrupt()` methods?
The code example:
```
public class MyRunnable implements Runnable {
public static void main(String[] args) {
Thread t = new Thread(new MyRunnable());
t.start();
for(int i=0; i<5; i++) {
System.out.println("Inside main");
}
}
public void run() {
for(int i=0; i<5; i++) {
System.out.println("Inside run");
Thread.yield();
}
}
}
```
I obtain the same output using the code above both with and without using `yield()`:
```
Inside main
Inside main
Inside main
Inside main
Inside main
Inside run
Inside run
Inside run
Inside run
Inside run
``` | 2011/08/08 | [
"https://Stackoverflow.com/questions/6979796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/827583/"
] | >
> The current answer(s) are out-of-date and require revision given recent changes.
>
>
>
There is no *practical* difference of `Thread.yield()` between Java versions since 6 to 9.
**TL;DR;**
Conclusions based on OpenJDK source code (<http://hg.openjdk.java.net/>).
If not to take into account HotSpot support of USDT probes (system tracing information is described in [dtrace guide](https://docs.oracle.com/javase/8/docs/technotes/guides/vm/dtrace.html)) and JVM property `ConvertYieldToSleep` then source code of `yield()` is almost the same. See explanation below.
**Java 9**:
`Thread.yield()` calls OS-specific method `os::naked_yield()`:
On Linux:
```
void os::naked_yield() {
sched_yield();
}
```
On Windows:
```
void os::naked_yield() {
SwitchToThread();
}
```
**Java 8 and earlier:**
`Thread.yield()` calls OS-specific method `os::yield()`:
On Linux:
```
void os::yield() {
sched_yield();
}
```
On Windows:
```
void os::yield() { os::NakedYield(); }
```
As you can see, `Thread.yeald()` on Linux is identical for all Java versions.
Let's see Windows's `os::NakedYield()` from JDK 8:
```
os::YieldResult os::NakedYield() {
// Use either SwitchToThread() or Sleep(0)
// Consider passing back the return value from SwitchToThread().
if (os::Kernel32Dll::SwitchToThreadAvailable()) {
return SwitchToThread() ? os::YIELD_SWITCHED : os::YIELD_NONEREADY ;
} else {
Sleep(0);
}
return os::YIELD_UNKNOWN ;
}
```
The difference between Java 9 and Java 8 in the additional check of the existence of the Win32 API's `SwitchToThread()` method. The same code is present for Java 6.
Source code of `os::NakedYield()` in JDK 7 is slightly different but it has the same behavior:
```
os::YieldResult os::NakedYield() {
// Use either SwitchToThread() or Sleep(0)
// Consider passing back the return value from SwitchToThread().
// We use GetProcAddress() as ancient Win9X versions of windows doen't support SwitchToThread.
// In that case we revert to Sleep(0).
static volatile STTSignature stt = (STTSignature) 1 ;
if (stt == ((STTSignature) 1)) {
stt = (STTSignature) ::GetProcAddress (LoadLibrary ("Kernel32.dll"), "SwitchToThread") ;
// It's OK if threads race during initialization as the operation above is idempotent.
}
if (stt != NULL) {
return (*stt)() ? os::YIELD_SWITCHED : os::YIELD_NONEREADY ;
} else {
Sleep (0) ;
}
return os::YIELD_UNKNOWN ;
}
```
The additional check has been dropped due to `SwitchToThread()` method are available since Windows XP and Windows Server 2003 (see [msdn notes](https://msdn.microsoft.com/ru-ru/en-en/library/windows/desktop/ms686352(v=vs.85).aspx)). | yield() main use is for putting a multi-threading application on hold.
all these methods differences are yield() puts thread on hold while executing another thread and returning back after the completion of that thread, join() will bring the beginning of threads together executing until the end and of another thread to run after that thread has ended, interrupt() will stop the execution of a thread for a while. |
6,979,796 | I am a little bit confused about the use of [`Thread.yield()`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Thread.html#yield()) method in Java, specifically in the example code below. I've also read that yield() is 'used to prevent execution of a thread'.
My questions are:
1. I believe the code below result in the same output both when using `yield()` and when not using it. Is this correct?
2. What are, in fact, the main uses of `yield()`?
3. In what ways is `yield()` different from the `join()` and `interrupt()` methods?
The code example:
```
public class MyRunnable implements Runnable {
public static void main(String[] args) {
Thread t = new Thread(new MyRunnable());
t.start();
for(int i=0; i<5; i++) {
System.out.println("Inside main");
}
}
public void run() {
for(int i=0; i<5; i++) {
System.out.println("Inside run");
Thread.yield();
}
}
}
```
I obtain the same output using the code above both with and without using `yield()`:
```
Inside main
Inside main
Inside main
Inside main
Inside main
Inside run
Inside run
Inside run
Inside run
Inside run
``` | 2011/08/08 | [
"https://Stackoverflow.com/questions/6979796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/827583/"
] | **Source: <http://www.javamex.com/tutorials/threads/yield.shtml>**
>
> ### Windows
>
>
> In the Hotspot implementation, the way that `Thread.yield()` works has
> changed between Java 5 and Java 6.
>
>
> In Java 5, `Thread.yield()` calls the Windows API call `Sleep(0)`. This
> has the special effect of **clearing the current thread's quantum** and
> putting it to the **end of the queue for its *priority level***. In other
> words, all runnable threads of the same priority (and those of greater
> priority) will get a chance to run before the yielded thread is next
> given CPU time. When it is eventually re-scheduled, it will come back
> with a full [full quantum](http://www.javamex.com/tutorials/threads/thread_scheduling.shtml#quantum), but doesn't "carry over" any of the
> remaining quantum from the time of yielding. This behaviour is a
> little different from a non-zero sleep where the sleeping thread
> generally loses 1 quantum value (in effect, 1/3 of a 10 or 15ms tick).
>
>
> In Java 6, this behaviour was changed. The Hotspot VM now implements
> `Thread.yield()` using the Windows `SwitchToThread()` API call. This call
> makes the current thread **give up its *current timeslice***, but not its
> entire quantum. This means that depending on the priorities of other
> threads, the yielding thread can be **scheduled back in one interrupt
> period later**. (See the section on [thread scheduling](http://www.javamex.com/tutorials/threads/thread_scheduling.shtml) for more
> information on timeslices.)
>
>
> ### Linux
>
>
> Under Linux, Hotspot simply calls `sched_yield()`. The consequences of
> this call are a little different, and possibly more severe than under
> Windows:
>
>
> * a yielded thread will not get another slice of CPU **until *all* other threads have had a slice of CPU**;
> * (at least in kernel 2.6.8 onwards), the fact that the thread has yielded is implicitly taken into account by the scheduler's heuristics
> on its recent CPU allocation— thus, implicitly, a thread that has
> yielded could be given more CPU when scheduled in the future.
>
>
> (See the section on [thread scheduling](http://www.javamex.com/tutorials/threads/thread_scheduling.shtml) for more details on priorities
> and scheduling algorithms.)
>
>
> ### When to use `yield()`?
>
>
> I would say **practically never**. Its behaviour isn't standardly defined
> and there are generally better ways to perform the tasks that you
> might want to perform with yield():
>
>
> * if you're trying to **use only a portion of the CPU**, you can do this in a more controllable way by estimating how much CPU the thread
> has used in its last chunk of processing, then **sleeping** for some
> amount of time to compensate: see the [sleep()](http://www.javamex.com/tutorials/threads/sleep.shtml) method;
> * if you're **waiting for a process or resource** to complete or become available, there are more efficient ways to accomplish this,
> such as by using [join()](http://www.javamex.com/tutorials/threads/yield.shtml#join) to wait for another thread to complete, using
> the [wait/notify](http://www.javamex.com/tutorials/synchronization_wait_notify.shtml) mechanism to allow one thread to signal to another
> that a task is complete, or ideally by using one of the Java 5
> concurrency constructs such as a [Semaphore](http://www.javamex.com/tutorials/synchronization_concurrency_semaphore.shtml) or [blocking queue](http://www.javamex.com/tutorials/synchronization_concurrency_8_queues.shtml).
>
>
> | I see the question has been reactivated with a bounty, now asking what the practical uses for `yield` are. I'll give an example from my experience.
As we know, `yield` forces the calling thread to give up the processor that it's running on so that another thread can be scheduled to run. This is useful when the current thread has finished its work for now but wants to quickly return to the front of the queue and check whether some condition has changed. How is this different from a condition variable? `yield` enables the thread to return much quicker to a running state. When waiting on a condition variable the thread is suspended and needs to wait for a different thread to signal that it should continue. `yield` basically says "allow a different thread to run, but allow me to get back to work very soon as I expect something to change in my state very very quickly". This hints towards busy spinning, where a condition can change rapidly but suspending the thread would incur a large performance hit.
But enough babbling, here's a concrete example: the wavefront parallel pattern. A basic instance of this problem is computing the individual "islands" of 1s in a bidimensional array filled with 0s and 1s. An "island" is a group of cells that are adjacent to eachother either vertically or horizontally:
```
1 0 0 0
1 1 0 0
0 0 0 1
0 0 1 1
0 0 1 1
```
Here we have two islands of 1s: top-left and bottom-right.
A simple solution is to make a first pass over the entire array and replace the 1 values with an incrementing counter such that by the end each 1 was replaced with its sequence number in row major order:
```
1 0 0 0
2 3 0 0
0 0 0 4
0 0 5 6
0 0 7 8
```
In the next step, each value is replaced by the minimum between itself and its neighbours' values:
```
1 0 0 0
1 1 0 0
0 0 0 4
0 0 4 4
0 0 4 4
```
We can now easily determine that we have two islands.
The part we want to run in parallel is the the step where we compute the minimums. Without going into too much detail, each thread gets rows in an interleaved manner and relies on the values computed by the thread processing the row above. Thus, each thread needs to slightly lag behind the thread processing the previous line, but must also keep up within reasonable time. More details and an implementation are presented by myself in [this document](https://drive.google.com/file/d/0BwHrufT_K__FNWYzMDIzOTctZDQyNC00NTEwLWI1YzMtNTdhMTc4NmNkYTdk/edit?usp=sharing). Note the usage of `sleep(0)` which is more or less the C equivalent of `yield`.
In this case `yield` was used in order to force each thread in turn to pause, but since the thread processing the adjacent row would advance very quickly in the meantime, a condition variable would prove a disastrous choice.
As you can see, `yield` is quite a fine-grain optimization. Using it in the wrong place e.g. waiting on a condition that changes seldomly, will cause excessive use of the CPU.
Sorry for the long babble, hope I made myself clear. |
6,979,796 | I am a little bit confused about the use of [`Thread.yield()`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Thread.html#yield()) method in Java, specifically in the example code below. I've also read that yield() is 'used to prevent execution of a thread'.
My questions are:
1. I believe the code below result in the same output both when using `yield()` and when not using it. Is this correct?
2. What are, in fact, the main uses of `yield()`?
3. In what ways is `yield()` different from the `join()` and `interrupt()` methods?
The code example:
```
public class MyRunnable implements Runnable {
public static void main(String[] args) {
Thread t = new Thread(new MyRunnable());
t.start();
for(int i=0; i<5; i++) {
System.out.println("Inside main");
}
}
public void run() {
for(int i=0; i<5; i++) {
System.out.println("Inside run");
Thread.yield();
}
}
}
```
I obtain the same output using the code above both with and without using `yield()`:
```
Inside main
Inside main
Inside main
Inside main
Inside main
Inside run
Inside run
Inside run
Inside run
Inside run
``` | 2011/08/08 | [
"https://Stackoverflow.com/questions/6979796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/827583/"
] | >
> The current answer(s) are out-of-date and require revision given recent changes.
>
>
>
There is no *practical* difference of `Thread.yield()` between Java versions since 6 to 9.
**TL;DR;**
Conclusions based on OpenJDK source code (<http://hg.openjdk.java.net/>).
If not to take into account HotSpot support of USDT probes (system tracing information is described in [dtrace guide](https://docs.oracle.com/javase/8/docs/technotes/guides/vm/dtrace.html)) and JVM property `ConvertYieldToSleep` then source code of `yield()` is almost the same. See explanation below.
**Java 9**:
`Thread.yield()` calls OS-specific method `os::naked_yield()`:
On Linux:
```
void os::naked_yield() {
sched_yield();
}
```
On Windows:
```
void os::naked_yield() {
SwitchToThread();
}
```
**Java 8 and earlier:**
`Thread.yield()` calls OS-specific method `os::yield()`:
On Linux:
```
void os::yield() {
sched_yield();
}
```
On Windows:
```
void os::yield() { os::NakedYield(); }
```
As you can see, `Thread.yeald()` on Linux is identical for all Java versions.
Let's see Windows's `os::NakedYield()` from JDK 8:
```
os::YieldResult os::NakedYield() {
// Use either SwitchToThread() or Sleep(0)
// Consider passing back the return value from SwitchToThread().
if (os::Kernel32Dll::SwitchToThreadAvailable()) {
return SwitchToThread() ? os::YIELD_SWITCHED : os::YIELD_NONEREADY ;
} else {
Sleep(0);
}
return os::YIELD_UNKNOWN ;
}
```
The difference between Java 9 and Java 8 in the additional check of the existence of the Win32 API's `SwitchToThread()` method. The same code is present for Java 6.
Source code of `os::NakedYield()` in JDK 7 is slightly different but it has the same behavior:
```
os::YieldResult os::NakedYield() {
// Use either SwitchToThread() or Sleep(0)
// Consider passing back the return value from SwitchToThread().
// We use GetProcAddress() as ancient Win9X versions of windows doen't support SwitchToThread.
// In that case we revert to Sleep(0).
static volatile STTSignature stt = (STTSignature) 1 ;
if (stt == ((STTSignature) 1)) {
stt = (STTSignature) ::GetProcAddress (LoadLibrary ("Kernel32.dll"), "SwitchToThread") ;
// It's OK if threads race during initialization as the operation above is idempotent.
}
if (stt != NULL) {
return (*stt)() ? os::YIELD_SWITCHED : os::YIELD_NONEREADY ;
} else {
Sleep (0) ;
}
return os::YIELD_UNKNOWN ;
}
```
The additional check has been dropped due to `SwitchToThread()` method are available since Windows XP and Windows Server 2003 (see [msdn notes](https://msdn.microsoft.com/ru-ru/en-en/library/windows/desktop/ms686352(v=vs.85).aspx)). | `Thread.yield();` frees the bottom thread.
`Thread` is using OS threads, so `Thread.yield();` might free the hardware thread.
Bad implementation for `sleep(millis)`
```
public class MySleep {
public static void sleep(long millis) throws InterruptedException {
long start = System.currentTimeMillis();
do {
Thread.yield();
if (Thread.interrupted()) {
throw new InterruptedException();
}
} while (System.currentTimeMillis() - start < millis);
}
}
```
and `join()`
```
public class MyJoin {
public static void join(Thread t) throws InterruptedException {
while (t.getState() != Thread.State.TERMINATED) {
Thread.yield();
if (Thread.interrupted()) {
throw new InterruptedException();
}
}
}
public static void main(String[] args) {
Thread thread = new Thread(()-> {
try {
Thread.sleep(2000);
} catch (Exception e) {
}
});
thread.start();
System.out.println("before");
try {
join(thread);
} catch (Exception e) {
}
System.out.println("after");
}
}
```
This should work even if there is only one hardware thread, unless `Thread.yield();` is removed. |
6,979,796 | I am a little bit confused about the use of [`Thread.yield()`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Thread.html#yield()) method in Java, specifically in the example code below. I've also read that yield() is 'used to prevent execution of a thread'.
My questions are:
1. I believe the code below result in the same output both when using `yield()` and when not using it. Is this correct?
2. What are, in fact, the main uses of `yield()`?
3. In what ways is `yield()` different from the `join()` and `interrupt()` methods?
The code example:
```
public class MyRunnable implements Runnable {
public static void main(String[] args) {
Thread t = new Thread(new MyRunnable());
t.start();
for(int i=0; i<5; i++) {
System.out.println("Inside main");
}
}
public void run() {
for(int i=0; i<5; i++) {
System.out.println("Inside run");
Thread.yield();
}
}
}
```
I obtain the same output using the code above both with and without using `yield()`:
```
Inside main
Inside main
Inside main
Inside main
Inside main
Inside run
Inside run
Inside run
Inside run
Inside run
``` | 2011/08/08 | [
"https://Stackoverflow.com/questions/6979796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/827583/"
] | `Thread.yield();` frees the bottom thread.
`Thread` is using OS threads, so `Thread.yield();` might free the hardware thread.
Bad implementation for `sleep(millis)`
```
public class MySleep {
public static void sleep(long millis) throws InterruptedException {
long start = System.currentTimeMillis();
do {
Thread.yield();
if (Thread.interrupted()) {
throw new InterruptedException();
}
} while (System.currentTimeMillis() - start < millis);
}
}
```
and `join()`
```
public class MyJoin {
public static void join(Thread t) throws InterruptedException {
while (t.getState() != Thread.State.TERMINATED) {
Thread.yield();
if (Thread.interrupted()) {
throw new InterruptedException();
}
}
}
public static void main(String[] args) {
Thread thread = new Thread(()-> {
try {
Thread.sleep(2000);
} catch (Exception e) {
}
});
thread.start();
System.out.println("before");
try {
join(thread);
} catch (Exception e) {
}
System.out.println("after");
}
}
```
This should work even if there is only one hardware thread, unless `Thread.yield();` is removed. | yield() main use is for putting a multi-threading application on hold.
all these methods differences are yield() puts thread on hold while executing another thread and returning back after the completion of that thread, join() will bring the beginning of threads together executing until the end and of another thread to run after that thread has ended, interrupt() will stop the execution of a thread for a while. |
6,979,796 | I am a little bit confused about the use of [`Thread.yield()`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Thread.html#yield()) method in Java, specifically in the example code below. I've also read that yield() is 'used to prevent execution of a thread'.
My questions are:
1. I believe the code below result in the same output both when using `yield()` and when not using it. Is this correct?
2. What are, in fact, the main uses of `yield()`?
3. In what ways is `yield()` different from the `join()` and `interrupt()` methods?
The code example:
```
public class MyRunnable implements Runnable {
public static void main(String[] args) {
Thread t = new Thread(new MyRunnable());
t.start();
for(int i=0; i<5; i++) {
System.out.println("Inside main");
}
}
public void run() {
for(int i=0; i<5; i++) {
System.out.println("Inside run");
Thread.yield();
}
}
}
```
I obtain the same output using the code above both with and without using `yield()`:
```
Inside main
Inside main
Inside main
Inside main
Inside main
Inside run
Inside run
Inside run
Inside run
Inside run
``` | 2011/08/08 | [
"https://Stackoverflow.com/questions/6979796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/827583/"
] | About the differences between `yield()`, `interrupt()` and `join()` - in general, not just in Java:
1. **yielding**: Literally, to 'yield' means to let go, to give up, to surrender. A yielding thread tells the operating system (or the virtual machine, or what not) it's willing to let other threads be scheduled in its stead. This indicates it's not doing something too critical. It's only a hint, though, and not guaranteed to have any effect.
2. **joining**: When multiple threads 'join' on some handle, or token, or entity, all of them wait until all other relevant threads have completed execution (entirely or upto their own corresponding join). That means a bunch of threads have all completed their tasks. Then each one of these threads can be scheduled to continue other work, being able to assume all those tasks are indeed complete. (Not to be confused with SQL Joins!)
3. **interruption**: Used by one thread to 'poke' another thread which is sleeping, or waiting, or joining - so that it is scheduled to continue running again, perhaps with an indication it has been interrupted. (Not to be confused with hardware interrupts!)
For Java specifically, see
1. Joining:
[How to use Thread.join?](https://stackoverflow.com/questions/1908515/java-how-to-use-thread-join) (here on StackOverflow)
[When to join threads?](http://javahowto.blogspot.co.il/2007/05/when-to-join-threads.html)
2. Yielding:
3. Interrupting:
[Is Thread.interrupt() evil?](https://stackoverflow.com/q/2020992/1593077) (here on StackOverflow) | First, the actual description is
>
> Causes the currently executing thread object to temporarily pause and
> allow other threads to execute.
>
>
>
Now, it is very likely that your main thread will execute the loop five times before the `run` method of the new thread is being executed, so all the calls to `yield` will happen only after the loop in the main thread is executed.
`join` will stop the current thread until the thread being called with `join()` is done executing.
`interrupt` will interrupt the thread it is being called on, causing [InterruptedException](http://download.oracle.com/javase/1.4.2/docs/api/java/lang/InterruptedException.html).
`yield` allows a context switch to other threads, so this thread will not consume the entire CPU usage of the process. |
6,979,796 | I am a little bit confused about the use of [`Thread.yield()`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Thread.html#yield()) method in Java, specifically in the example code below. I've also read that yield() is 'used to prevent execution of a thread'.
My questions are:
1. I believe the code below result in the same output both when using `yield()` and when not using it. Is this correct?
2. What are, in fact, the main uses of `yield()`?
3. In what ways is `yield()` different from the `join()` and `interrupt()` methods?
The code example:
```
public class MyRunnable implements Runnable {
public static void main(String[] args) {
Thread t = new Thread(new MyRunnable());
t.start();
for(int i=0; i<5; i++) {
System.out.println("Inside main");
}
}
public void run() {
for(int i=0; i<5; i++) {
System.out.println("Inside run");
Thread.yield();
}
}
}
```
I obtain the same output using the code above both with and without using `yield()`:
```
Inside main
Inside main
Inside main
Inside main
Inside main
Inside run
Inside run
Inside run
Inside run
Inside run
``` | 2011/08/08 | [
"https://Stackoverflow.com/questions/6979796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/827583/"
] | >
> What are, in fact, the main uses of yield()?
>
>
>
Yield suggests to the CPU that you may stop the current thread and start executing threads with higher priority. In other words, assigning a low priority value to the current thread to leave room for more critical threads.
>
> I believe the code below result in the same output both when using yield() and when not using it. Is this correct?
>
>
>
NO, the two will produce different results. Without a yield(), once the thread gets control it will execute the 'Inside run' loop in one go. However, with a yield(), once the thread gets control it will print the 'Inside run' once and then will hand over control to other thread if any. If no thread in pending, this thread will be resumed again. So every time "Inside run' is executed it will look for other threads to execute and if no thread is available, the current thread will keep on executing.
>
> In what ways is yield() different from the join() and interrupt() methods?
>
>
>
yield() is for giving room to other important threads, join() is for waiting for another thread to complete its execution, and interrupt() is for interrupting a currently executing thread to do something else. | `Thread.yield()` causes thread to go from "Running" state to "Runnable" state.
Note: It doesn't cause thread to go "Waiting" state. |
6,979,796 | I am a little bit confused about the use of [`Thread.yield()`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Thread.html#yield()) method in Java, specifically in the example code below. I've also read that yield() is 'used to prevent execution of a thread'.
My questions are:
1. I believe the code below result in the same output both when using `yield()` and when not using it. Is this correct?
2. What are, in fact, the main uses of `yield()`?
3. In what ways is `yield()` different from the `join()` and `interrupt()` methods?
The code example:
```
public class MyRunnable implements Runnable {
public static void main(String[] args) {
Thread t = new Thread(new MyRunnable());
t.start();
for(int i=0; i<5; i++) {
System.out.println("Inside main");
}
}
public void run() {
for(int i=0; i<5; i++) {
System.out.println("Inside run");
Thread.yield();
}
}
}
```
I obtain the same output using the code above both with and without using `yield()`:
```
Inside main
Inside main
Inside main
Inside main
Inside main
Inside run
Inside run
Inside run
Inside run
Inside run
``` | 2011/08/08 | [
"https://Stackoverflow.com/questions/6979796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/827583/"
] | `Thread.yield()` causes thread to go from "Running" state to "Runnable" state.
Note: It doesn't cause thread to go "Waiting" state. | Thread.yield()
>
> When we invoke Thread.yield() method, the thread scheduler keep the currently running thread to Runnable state and picks another thread of equal priority or higher priority. If there is no equal and higher priority thread then it reschedule the calling yield() thread. Remember yield method does not make the thread to go to Wait or Blocked state. It can only make a thread from Running State to Runnable State.
>
>
>
join()
>
> When join is invoked by a thread instance, this thread will tell currently executing thread to wait till the Joining thread completes. Join is used in the situations when a task which should be completed before the current task is going to finish.
>
>
> |
6,979,796 | I am a little bit confused about the use of [`Thread.yield()`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Thread.html#yield()) method in Java, specifically in the example code below. I've also read that yield() is 'used to prevent execution of a thread'.
My questions are:
1. I believe the code below result in the same output both when using `yield()` and when not using it. Is this correct?
2. What are, in fact, the main uses of `yield()`?
3. In what ways is `yield()` different from the `join()` and `interrupt()` methods?
The code example:
```
public class MyRunnable implements Runnable {
public static void main(String[] args) {
Thread t = new Thread(new MyRunnable());
t.start();
for(int i=0; i<5; i++) {
System.out.println("Inside main");
}
}
public void run() {
for(int i=0; i<5; i++) {
System.out.println("Inside run");
Thread.yield();
}
}
}
```
I obtain the same output using the code above both with and without using `yield()`:
```
Inside main
Inside main
Inside main
Inside main
Inside main
Inside run
Inside run
Inside run
Inside run
Inside run
``` | 2011/08/08 | [
"https://Stackoverflow.com/questions/6979796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/827583/"
] | >
> What are, in fact, the main uses of yield()?
>
>
>
Yield suggests to the CPU that you may stop the current thread and start executing threads with higher priority. In other words, assigning a low priority value to the current thread to leave room for more critical threads.
>
> I believe the code below result in the same output both when using yield() and when not using it. Is this correct?
>
>
>
NO, the two will produce different results. Without a yield(), once the thread gets control it will execute the 'Inside run' loop in one go. However, with a yield(), once the thread gets control it will print the 'Inside run' once and then will hand over control to other thread if any. If no thread in pending, this thread will be resumed again. So every time "Inside run' is executed it will look for other threads to execute and if no thread is available, the current thread will keep on executing.
>
> In what ways is yield() different from the join() and interrupt() methods?
>
>
>
yield() is for giving room to other important threads, join() is for waiting for another thread to complete its execution, and interrupt() is for interrupting a currently executing thread to do something else. | `Thread.yield();` frees the bottom thread.
`Thread` is using OS threads, so `Thread.yield();` might free the hardware thread.
Bad implementation for `sleep(millis)`
```
public class MySleep {
public static void sleep(long millis) throws InterruptedException {
long start = System.currentTimeMillis();
do {
Thread.yield();
if (Thread.interrupted()) {
throw new InterruptedException();
}
} while (System.currentTimeMillis() - start < millis);
}
}
```
and `join()`
```
public class MyJoin {
public static void join(Thread t) throws InterruptedException {
while (t.getState() != Thread.State.TERMINATED) {
Thread.yield();
if (Thread.interrupted()) {
throw new InterruptedException();
}
}
}
public static void main(String[] args) {
Thread thread = new Thread(()-> {
try {
Thread.sleep(2000);
} catch (Exception e) {
}
});
thread.start();
System.out.println("before");
try {
join(thread);
} catch (Exception e) {
}
System.out.println("after");
}
}
```
This should work even if there is only one hardware thread, unless `Thread.yield();` is removed. |
6,979,796 | I am a little bit confused about the use of [`Thread.yield()`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Thread.html#yield()) method in Java, specifically in the example code below. I've also read that yield() is 'used to prevent execution of a thread'.
My questions are:
1. I believe the code below result in the same output both when using `yield()` and when not using it. Is this correct?
2. What are, in fact, the main uses of `yield()`?
3. In what ways is `yield()` different from the `join()` and `interrupt()` methods?
The code example:
```
public class MyRunnable implements Runnable {
public static void main(String[] args) {
Thread t = new Thread(new MyRunnable());
t.start();
for(int i=0; i<5; i++) {
System.out.println("Inside main");
}
}
public void run() {
for(int i=0; i<5; i++) {
System.out.println("Inside run");
Thread.yield();
}
}
}
```
I obtain the same output using the code above both with and without using `yield()`:
```
Inside main
Inside main
Inside main
Inside main
Inside main
Inside run
Inside run
Inside run
Inside run
Inside run
``` | 2011/08/08 | [
"https://Stackoverflow.com/questions/6979796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/827583/"
] | >
> What are, in fact, the main uses of yield()?
>
>
>
Yield suggests to the CPU that you may stop the current thread and start executing threads with higher priority. In other words, assigning a low priority value to the current thread to leave room for more critical threads.
>
> I believe the code below result in the same output both when using yield() and when not using it. Is this correct?
>
>
>
NO, the two will produce different results. Without a yield(), once the thread gets control it will execute the 'Inside run' loop in one go. However, with a yield(), once the thread gets control it will print the 'Inside run' once and then will hand over control to other thread if any. If no thread in pending, this thread will be resumed again. So every time "Inside run' is executed it will look for other threads to execute and if no thread is available, the current thread will keep on executing.
>
> In what ways is yield() different from the join() and interrupt() methods?
>
>
>
yield() is for giving room to other important threads, join() is for waiting for another thread to complete its execution, and interrupt() is for interrupting a currently executing thread to do something else. | Thread.yield()
>
> When we invoke Thread.yield() method, the thread scheduler keep the currently running thread to Runnable state and picks another thread of equal priority or higher priority. If there is no equal and higher priority thread then it reschedule the calling yield() thread. Remember yield method does not make the thread to go to Wait or Blocked state. It can only make a thread from Running State to Runnable State.
>
>
>
join()
>
> When join is invoked by a thread instance, this thread will tell currently executing thread to wait till the Joining thread completes. Join is used in the situations when a task which should be completed before the current task is going to finish.
>
>
> |
6,979,796 | I am a little bit confused about the use of [`Thread.yield()`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Thread.html#yield()) method in Java, specifically in the example code below. I've also read that yield() is 'used to prevent execution of a thread'.
My questions are:
1. I believe the code below result in the same output both when using `yield()` and when not using it. Is this correct?
2. What are, in fact, the main uses of `yield()`?
3. In what ways is `yield()` different from the `join()` and `interrupt()` methods?
The code example:
```
public class MyRunnable implements Runnable {
public static void main(String[] args) {
Thread t = new Thread(new MyRunnable());
t.start();
for(int i=0; i<5; i++) {
System.out.println("Inside main");
}
}
public void run() {
for(int i=0; i<5; i++) {
System.out.println("Inside run");
Thread.yield();
}
}
}
```
I obtain the same output using the code above both with and without using `yield()`:
```
Inside main
Inside main
Inside main
Inside main
Inside main
Inside run
Inside run
Inside run
Inside run
Inside run
``` | 2011/08/08 | [
"https://Stackoverflow.com/questions/6979796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/827583/"
] | About the differences between `yield()`, `interrupt()` and `join()` - in general, not just in Java:
1. **yielding**: Literally, to 'yield' means to let go, to give up, to surrender. A yielding thread tells the operating system (or the virtual machine, or what not) it's willing to let other threads be scheduled in its stead. This indicates it's not doing something too critical. It's only a hint, though, and not guaranteed to have any effect.
2. **joining**: When multiple threads 'join' on some handle, or token, or entity, all of them wait until all other relevant threads have completed execution (entirely or upto their own corresponding join). That means a bunch of threads have all completed their tasks. Then each one of these threads can be scheduled to continue other work, being able to assume all those tasks are indeed complete. (Not to be confused with SQL Joins!)
3. **interruption**: Used by one thread to 'poke' another thread which is sleeping, or waiting, or joining - so that it is scheduled to continue running again, perhaps with an indication it has been interrupted. (Not to be confused with hardware interrupts!)
For Java specifically, see
1. Joining:
[How to use Thread.join?](https://stackoverflow.com/questions/1908515/java-how-to-use-thread-join) (here on StackOverflow)
[When to join threads?](http://javahowto.blogspot.co.il/2007/05/when-to-join-threads.html)
2. Yielding:
3. Interrupting:
[Is Thread.interrupt() evil?](https://stackoverflow.com/q/2020992/1593077) (here on StackOverflow) | >
> What are, in fact, the main uses of yield()?
>
>
>
Yield suggests to the CPU that you may stop the current thread and start executing threads with higher priority. In other words, assigning a low priority value to the current thread to leave room for more critical threads.
>
> I believe the code below result in the same output both when using yield() and when not using it. Is this correct?
>
>
>
NO, the two will produce different results. Without a yield(), once the thread gets control it will execute the 'Inside run' loop in one go. However, with a yield(), once the thread gets control it will print the 'Inside run' once and then will hand over control to other thread if any. If no thread in pending, this thread will be resumed again. So every time "Inside run' is executed it will look for other threads to execute and if no thread is available, the current thread will keep on executing.
>
> In what ways is yield() different from the join() and interrupt() methods?
>
>
>
yield() is for giving room to other important threads, join() is for waiting for another thread to complete its execution, and interrupt() is for interrupting a currently executing thread to do something else. |
30,435,317 | I have single polyline on my map. I add dblclick event to it. It is working but also map is zooming. How to disable zooming when double click on polyline? (Or anything else with dblclick event);
Any event propagation, event stop or something?
I know and I can use `map.setOptions({disableDoubleClickZoom: true });` but it is not what i really want to do.
EDIT: STUPID HACK
In polyline `'dblclick'` event just added at start : `map.setZoom(map.getZoom-1);` | 2015/05/25 | [
"https://Stackoverflow.com/questions/30435317",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4554009/"
] | This is the way to do this through the api:
```
google.maps.event.addListener(polygonObject,'dblclick',function(e){e.stop();})
```
[Disabling zoom when double click on polygon](https://stackoverflow.com/questions/11278409/disabling-zoom-when-double-click-on-polygon) | **STUPID HACK**
In polyline 'dblclick' event just added at start : map.setZoom(map.getZoom-1);
So first u deacrease zoom and then increase. |
25,730,046 | I have a controller that outputs data from the database in raw JSON format.
I want this to function as an API and allow anyone to make views with any technology that can consume the JSON i.e. Angular, Jquery/Ajax.
However I also want to make a view in Laravel.
So what's the best practice for creating a view from Laravel that uses data from a controller while still allowing the controller to output raw JSON?
The options I'm thinking of are to call the controller from the view(not good?) or to create extra routes. | 2014/09/08 | [
"https://Stackoverflow.com/questions/25730046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1821450/"
] | You are probably using NTFS or FAT32 on Windows, and those filesystems do not support the *executable* permission. Instead, [cygwin looks at the file name and contents to determine whether it's executable](https://cygwin.com/cygwin-ug-net/using-filemodes.html):
>
> Files are considered to be executable if the filename ends with .bat, .com or .exe, or if its content starts with #!.
>
>
>
So you should make sure that the bash file starts with a [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)) (e.g. `#!/bin/bash`). Then, you should be able to just execute the file, disregarding the permission output of `ls`. | If you're updating scripts in a windows environment that are being deployed to a linux filesystem, even though they are permitted to run locally, you may still find yourself needing to grant execute before pushing.
From this article on [Change file permissions when working with git repo's on windows](https://medium.com/@akash1233/change-file-permissions-when-working-with-git-repos-on-windows-ea22e34d5cee):
1. Open up a bash terminal like git-bash on Windows
2. Navigate to the `.sh` file where you want to grant execute permissions
3. Check the existing permissions with the following command:
```sh
git ls-files --stage
```
Which should return something like *100644*
4. Update the permissions with the following command
```sh
git update-index --chmod=+x 'name-of-shell-script'
```
5. Check the file permission again
```sh
git ls-files --stage
```
Which should return something like *100755*
6. Commit changes and push!
[![git bash on windows](https://i.stack.imgur.com/9oUd2.jpg)](https://i.stack.imgur.com/9oUd2.jpg) |
25,730,046 | I have a controller that outputs data from the database in raw JSON format.
I want this to function as an API and allow anyone to make views with any technology that can consume the JSON i.e. Angular, Jquery/Ajax.
However I also want to make a view in Laravel.
So what's the best practice for creating a view from Laravel that uses data from a controller while still allowing the controller to output raw JSON?
The options I'm thinking of are to call the controller from the view(not good?) or to create extra routes. | 2014/09/08 | [
"https://Stackoverflow.com/questions/25730046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1821450/"
] | You are probably using NTFS or FAT32 on Windows, and those filesystems do not support the *executable* permission. Instead, [cygwin looks at the file name and contents to determine whether it's executable](https://cygwin.com/cygwin-ug-net/using-filemodes.html):
>
> Files are considered to be executable if the filename ends with .bat, .com or .exe, or if its content starts with #!.
>
>
>
So you should make sure that the bash file starts with a [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)) (e.g. `#!/bin/bash`). Then, you should be able to just execute the file, disregarding the permission output of `ls`. | Very likely you do not have "shebang" at the beginning of your script. So Windows does not know which binary should be used to run the script. Thus the permissions gets silently ignored.
For example:
```
#!/usr/bin/sh
```
or
```
#!/usr/bin/bash
```
It looks like git-bash detects it automaticly, because the executable attribute gets set even without chmod command. Moreover it is not possible to disable it by using chmod. |
25,730,046 | I have a controller that outputs data from the database in raw JSON format.
I want this to function as an API and allow anyone to make views with any technology that can consume the JSON i.e. Angular, Jquery/Ajax.
However I also want to make a view in Laravel.
So what's the best practice for creating a view from Laravel that uses data from a controller while still allowing the controller to output raw JSON?
The options I'm thinking of are to call the controller from the view(not good?) or to create extra routes. | 2014/09/08 | [
"https://Stackoverflow.com/questions/25730046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1821450/"
] | If you're updating scripts in a windows environment that are being deployed to a linux filesystem, even though they are permitted to run locally, you may still find yourself needing to grant execute before pushing.
From this article on [Change file permissions when working with git repo's on windows](https://medium.com/@akash1233/change-file-permissions-when-working-with-git-repos-on-windows-ea22e34d5cee):
1. Open up a bash terminal like git-bash on Windows
2. Navigate to the `.sh` file where you want to grant execute permissions
3. Check the existing permissions with the following command:
```sh
git ls-files --stage
```
Which should return something like *100644*
4. Update the permissions with the following command
```sh
git update-index --chmod=+x 'name-of-shell-script'
```
5. Check the file permission again
```sh
git ls-files --stage
```
Which should return something like *100755*
6. Commit changes and push!
[![git bash on windows](https://i.stack.imgur.com/9oUd2.jpg)](https://i.stack.imgur.com/9oUd2.jpg) | Very likely you do not have "shebang" at the beginning of your script. So Windows does not know which binary should be used to run the script. Thus the permissions gets silently ignored.
For example:
```
#!/usr/bin/sh
```
or
```
#!/usr/bin/bash
```
It looks like git-bash detects it automaticly, because the executable attribute gets set even without chmod command. Moreover it is not possible to disable it by using chmod. |
49,585,618 | **Task:**
```
id | title | description |
---------------------------------------------------------------------
1 | Task1 | Descr1 |
2 | Task2 | Descr1 |
3 | Task2 | Descr1 |
4 | Task2 | Descr1 |
5 | Task2 | Descr1 |
```
**Message:**
```
id | task_id | message | status |
---------------------------------------------------------------------
1 | 1 | Message1 | HOLD
2 | 1 | Message2 | OK
3 | 1 | Message3 | ERROR
4 | 1 | Message4 | ERROR
5 | 2 | Message5 | HOLD
6 | 2 | Message6 | OK
7 | 2 | Message7 | OK
8 | 2 | Message7 | OK
9 | 3 | Message7 | OK
```
I want to show as here:
```
id | title | description | count(HOLD) | count(OK) | count(ERROR)
---------------------------------------------------------------------
1 | Task1 | Descr1 | 1 | 1 | 2
2 | Task2 | Descr1 | 1 | 3 | 0
3 | Task2 | Descr1 | 0 | 1 | 0
4 | Task2 | Descr1 | 0 | 0 | 0
5 | Task2 | Descr1 | 0 | 0 | 0
``` | 2018/03/31 | [
"https://Stackoverflow.com/questions/49585618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2100323/"
] | You could use a selective aggregation baded on sum and CASE when
```
select task.id
, task.title
, task.description
, sum(case when Message.status = 1 then 1 else 0 end ) status1
, sum(case when Message.status = 2 then 1 else 0 end ) status2
, sum(case when Message.status = 3 then 1 else 0 end ) status3
from Task
INNER JOIN Message ON Task.id = Message.task_id
group by task.id
, task.title
, task.description
``` | Another way
```
SELECT task.id, task.title, task.description,
SUM(DECODE (status, 'HOLD',1,0 end)) AS "HOLD_COUNT"
SUM(DECODE (status, OK,1, 0 end)) AS "OK_COUNT"
SUM(DECODE (status, ERROR,1, 0 end ) AS "ERROUR_COUNT"
FROM task
JOIN Message ON Task.id = Message.task_id
group by task.id, task.title , task.description
``` |
49,585,618 | **Task:**
```
id | title | description |
---------------------------------------------------------------------
1 | Task1 | Descr1 |
2 | Task2 | Descr1 |
3 | Task2 | Descr1 |
4 | Task2 | Descr1 |
5 | Task2 | Descr1 |
```
**Message:**
```
id | task_id | message | status |
---------------------------------------------------------------------
1 | 1 | Message1 | HOLD
2 | 1 | Message2 | OK
3 | 1 | Message3 | ERROR
4 | 1 | Message4 | ERROR
5 | 2 | Message5 | HOLD
6 | 2 | Message6 | OK
7 | 2 | Message7 | OK
8 | 2 | Message7 | OK
9 | 3 | Message7 | OK
```
I want to show as here:
```
id | title | description | count(HOLD) | count(OK) | count(ERROR)
---------------------------------------------------------------------
1 | Task1 | Descr1 | 1 | 1 | 2
2 | Task2 | Descr1 | 1 | 3 | 0
3 | Task2 | Descr1 | 0 | 1 | 0
4 | Task2 | Descr1 | 0 | 0 | 0
5 | Task2 | Descr1 | 0 | 0 | 0
``` | 2018/03/31 | [
"https://Stackoverflow.com/questions/49585618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2100323/"
] | You could use a selective aggregation baded on sum and CASE when
```
select task.id
, task.title
, task.description
, sum(case when Message.status = 1 then 1 else 0 end ) status1
, sum(case when Message.status = 2 then 1 else 0 end ) status2
, sum(case when Message.status = 3 then 1 else 0 end ) status3
from Task
INNER JOIN Message ON Task.id = Message.task_id
group by task.id
, task.title
, task.description
``` | I believe the correct solution is:
```
select t.id, t.title, t.description,
coalesce(sum( m.status = 'Hold' ), 0) as num_hold,
coalesce(sum( m.status = 'OK' ), 0) as num_ok,
coalesce(sum( m.status = 'Error' ), 0) as num_error
from task t left join
message m
on m.task_id = t.id
group by t.id, t.title, t.description;
``` |
51,984 | I observed the below behavior of echo
```
#!/bin/bash
x=" hello"
echo $x
echo "$x"
```
Now when I run the above code I get
```
ronnie@ronnie:~$ bash test.sh
hello
hello
ronnie@ronnie:~$
```
So, can someone explain to me why `whitespace` in first case is not present in output and also points me to the documentation where this behavior is defined. | 2012/10/16 | [
"https://unix.stackexchange.com/questions/51984",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/24545/"
] | It is not the `echo` behavior. It is a bash behavior. When you use `echo $x` form the bash get the following command to process (treat `␣` as space):
```
echo␣␣hello
```
Then this command is tokenized and bash get two tokens: `echo` and `hello` thus the output is just `hello`
When you use the `echo "$x"` form then the bash has the following at the input of tokenizer:
```
echo␣"␣hello"
```
thus it has two tokens `echo` and `␣hello`, so the output is different. | The reason you see different output is because the `echo[1 space]Hello` line is syntactically equal
to `echo[5 spaces]Hello`. The whitespace is ignored, and the word 'Hello' is treated as the argument to `echo`. The first line, in it's simplest form, is much the same as if you had said `echo "Hello"`. In the second line, you have explicitly included a leading space as part of the argument to `echo`, with `echo " Hello"`.
In the first line, you are passing a 5 character string to `echo`, and in the second line you are passing a 6 character string to `echo`.
So, in fact, the behavior of `echo` is the same in both instances, it's just the string being passed to `echo` that changes. |
95,587 | I need to get every UTC day stamp in yyyy-MM-dd format (e.g. "2015-07-02") between any two arbitrary Date fields.
My first attempt is this:
```
public static Set<String> getUTCDayStringsBetween(Date startDt, Date endDt) {
if (!startDt.before(endDt)) {
throw new IllegalArgumentException("Start date (" + startDt + ") must be before end date (" + endDt + ")");
}
final TimeZone UTC = TimeZone.getTimeZone("UTC");
final Calendar c = Calendar.getInstance();
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
sdf.setTimeZone(UTC);
final Set<String> dayStrings = new LinkedHashSet<>();
c.setTime(startDt);
while (true) {
dayStrings.add(sdf.format(c.getTime()));
c.add(Calendar.DATE, 1);//add 1 day
if (c.getTime().after(endDt)) {
//reached the end of our range. set time to the endDt and get the final day string
c.setTime(endDt);
dayStrings.add(sdf.format(c.getTime()));
break;
}
}
return dayStrings;
}
```
It seems to work, but I'm wondering if there is a more efficient way to do it (aside from using external time libraries like Joda.).
Also, is there anything I'm glossing over in terms of handling time zones and day-light-savings changes appropriately. | 2015/07/02 | [
"https://codereview.stackexchange.com/questions/95587",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/52425/"
] | >
> *No, but I welcome answers that use Java8 features* - [bradvido](https://codereview.stackexchange.com/questions/95587/getting-all-the-utc-day-stamps-between-2-dates#comment174428_95587)
>
>
>
In Java 8, the new [`Instant`](https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html) class is analogous to the old `Date` class, in the sense that both represent a single point on a time-line. Therefore, if this was to be given a Java 8 makeover, I'll suggest modifying your method to become a wrapper-method over one that takes in two `Instant` objects:
```
public static Set<String> getUTCDayStringsBetween(Date startDt, Date endDt) {
return getUTCDayStringsBetween(startDt.toInstant(), endDt.toInstant());
}
public static Set<String> getUTCDayStringsBetween(Instant startInstant,
Instant endInstant) {
// ...
}
```
One nice thing about the new Java 8 Time APIs, which are largely (almost completely? wholly?) based on Joda-Time, is that the new classes come with a wealth of methods, letting us easily manipulate dates, times and time zones. For starters, let's convert our `Instant` objects to the desired `UTC` time zone:
```
// declared as class field
public static final ZoneId UTC = ZoneId.of("Z");
// inside the method
ZonedDateTime start = startInstant.atZone(UTC);
ZonedDateTime end = endInstant.atZone(UTC).with(start.toLocalTime());
```
`start` and `end` now represents the UTC date-time, and crucially `end` is now at the same time defined in `start` as well (will be explained below).
Now, we just need to:
1. count the number of **whole** days between `start` and `end`,
2. add each of the days to `start`,
3. format to desired `String` representation, and
4. collect to the desired `Set`.
Putting it all together (note the comments indicating the above points):
```
public static Set<String> getUTCDayStringsBetween(Instant startInstant,
Instant endInstant) {
if (endInstant.isBefore(startInstant)) {
throw new IllegalArgumentException("Start date (" + startInstant +
") must be before end date (" + endInstant + ")");
}
ZonedDateTime start = startInstant.atZone(UTC);
ZonedDateTime end = endInstant.atZone(UTC).with(start.toLocalTime());
return LongStream.rangeClosed(0, start.until(end, ChronoUnit.DAYS)) // 1
.mapToObj(start::plusDays) // 2
.map(DateTimeFormatter.ISO_LOCAL_DATE::format) // 3
.collect(Collectors.toCollection(LinkedHashSet::new)); // 4
}
```
[`start.until(end, ChronoUnit.DAYS)`](https://docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime.html#until-java.time.temporal.Temporal-java.time.temporal.TemporalUnit-) only counts the *complete days* between the two arguments, hence the necessity to set the time of `end` to be the same as `start`. Effectively, we are doing a form of 'rounding up' here.
Having generated a `Stream` of days to add, we do so using (the [method reference](https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html)) [`start::plusDays`](https://docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime.html#plusDays-long-). Next we use the predefined `DateTimeFormatter` instance [`ISO_LOCAL_DATE`](https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#ISO_LOCAL_DATE) to get our desired results. Finally, I use a `LinkedHashSet` as the backing `Set` implementation since I thought it may make more sense to have a defined ordering (by insertion) as the result.
**Don't forget your unit tests too!** If you have yet to do so, unit testing allows you to easily and quickly verify whether the implementation is correct. For example, I have tested with the following two cases, although I will suggest testing for different time zones or even the exceptional cases:
```
ZonedDateTime test = ZonedDateTime.of(2015, 7, 1, 19, 59, 59, 0, ZoneId.of("US/Eastern"));
getUTCDayStringsBetween(test.toInstant(), test.plusSeconds(1).toInstant())
.forEach(System.out::println);
getUTCDayStringsBetween(test.toInstant(), test.plusDays(7).toInstant())
.forEach(System.out::println);
```
The test output I get is:
```
2015-07-01
2015-07-02
2015-07-01
2015-07-02
2015-07-03
2015-07-04
2015-07-05
2015-07-06
2015-07-07
2015-07-08
```
In the first case, since we ended on UTC midnight, two dates are printed. In the second case, we include the eighth day itself (the seventh day after `test`), hence there are eight dates.
---
>
> Also, is there anything I'm glossing over in terms of handling time zones and day-light-savings changes appropriately.
>
>
>
Since `Date` objects do not have the concept of time zones (besides the fact that they are 'zero-ed' to UTC), and **therefore unaffected by daylight savings**, my take is that you don't have to worry about both. | Instead of an infinite `while` loop + an `if` to break out, it would be more natural to convert this to a do-while loop.
The comment "//reached the end of our range. set time to the endDt and get the final day string" is pointless, it just says the same thing with words that the code already tells us perfectly clearly.
`c` is not a great name for a `Calendar`. How about `cal`, or even `calendar` ? Instead of `startDt` and `endDt`, I would just also them out.
It's a bit smelly about the interface that the method requires the date parameters in a specific order, but this is not obvious from the name. And if the caller uses the wrong order, the runtime exception is a heavy penalty, crashing the application. It's not great to have rules that cannot be enforced at compile time, but I don't have a good counter proposal for you. |
288,935 | I know this is a very basic question but I cant seem to find the answer with Google. What is the difference between a hotfix and a bugfix? | 2015/07/07 | [
"https://softwareengineering.stackexchange.com/questions/288935",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/134708/"
] | The term hotfix is generally used when client has found an issue within the current release of the product and can not wait to be fixed until the next big release. Hence a hotfix issue is created to fix it and is released as a part of update to the current release usually called Cumulative Update(CU). CUs are nothing but a bunch of hotfixes together.
Bugfix - We usually use this when an issue is found during the development and testing phase internally. | A bugfix is just that: a fix for a bug. This could happen at almost any time in a product's lifetime: during development, during testing, or after release.
A hotfix can be one or more bugfixes. The important part is the hot, which refers to when it is applied. Originally, it referred to patching an actively running system (aka, 'hot'). It's grown to more generally refer to bugfixes provided after the product is released to the public (this could be during public beta testing, too), but outside of the regular update schedule. |
288,935 | I know this is a very basic question but I cant seem to find the answer with Google. What is the difference between a hotfix and a bugfix? | 2015/07/07 | [
"https://softwareengineering.stackexchange.com/questions/288935",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/134708/"
] | The term hotfix is generally used when client has found an issue within the current release of the product and can not wait to be fixed until the next big release. Hence a hotfix issue is created to fix it and is released as a part of update to the current release usually called Cumulative Update(CU). CUs are nothing but a bunch of hotfixes together.
Bugfix - We usually use this when an issue is found during the development and testing phase internally. | From my experience in support at a large software company the two terms are unrelated.
`Bug fix` is an action on the source code, it is a code change or set of changes to address a reported code defect (a bug.)
A `hotfix` is generally a patch or update for clients / deployed systems but more specifically they are patches which are:-
* not released to a schedule.
* intended to address either 'niche' situations or 'emergency' responses.
* only relevant to the specific issue documented in the release notes.
* poorly tested. If at all.
* a potential source for the (re)introduction of bugs.
* intended for small audiences.
* likely to affect automated patching systems and require additional monitoring. Hotfixes may deploy a file/library with unusually high version number to prevent the hotfix from being patched over.
* supplied by the software maker directly to named contacts, not publically available. Customers are often expected to contact technical support to request hotfixes for example.
* frequently branched from the 'last known good' source tree. As a 'quick fix' the code used in the hotfix may never make it back into the main build (it may be that as a temporary fix a better solution requires more time/resources.) |
288,935 | I know this is a very basic question but I cant seem to find the answer with Google. What is the difference between a hotfix and a bugfix? | 2015/07/07 | [
"https://softwareengineering.stackexchange.com/questions/288935",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/134708/"
] | From my experience in support at a large software company the two terms are unrelated.
`Bug fix` is an action on the source code, it is a code change or set of changes to address a reported code defect (a bug.)
A `hotfix` is generally a patch or update for clients / deployed systems but more specifically they are patches which are:-
* not released to a schedule.
* intended to address either 'niche' situations or 'emergency' responses.
* only relevant to the specific issue documented in the release notes.
* poorly tested. If at all.
* a potential source for the (re)introduction of bugs.
* intended for small audiences.
* likely to affect automated patching systems and require additional monitoring. Hotfixes may deploy a file/library with unusually high version number to prevent the hotfix from being patched over.
* supplied by the software maker directly to named contacts, not publically available. Customers are often expected to contact technical support to request hotfixes for example.
* frequently branched from the 'last known good' source tree. As a 'quick fix' the code used in the hotfix may never make it back into the main build (it may be that as a temporary fix a better solution requires more time/resources.) | A bugfix is just that: a fix for a bug. This could happen at almost any time in a product's lifetime: during development, during testing, or after release.
A hotfix can be one or more bugfixes. The important part is the hot, which refers to when it is applied. Originally, it referred to patching an actively running system (aka, 'hot'). It's grown to more generally refer to bugfixes provided after the product is released to the public (this could be during public beta testing, too), but outside of the regular update schedule. |
54,624 | sorry if I'm asking stupid questions but I really spent days trying to figure out how to add functionality to my map so that when user clicks on some map object he gets the attribute table on the side with the attribute data of that object. Is it even possible? I don't speak about popups, I speak about actual table.
This is how my map looks now:
![map](https://i.stack.imgur.com/6Liqu.png)
I would like that space on the east side of monitor populate with that attribute table when users click. I'm not saying that's the best solution but that's how I imagined that. But I'm open for suggestions.
As you can see I use geoext, openlayers and extjs and honestly, I don't know lot about php or some other frameworks so I would be happy if the solution could be solved using geoext or smilair. I was looking around but nothing what I found is what I'm actually looking for.
One more time, sorry if my question is unprofessional or something but I'm really kind of desperate :) | 2013/03/15 | [
"https://gis.stackexchange.com/questions/54624",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/-1/"
] | You could use the FeatureGrid :
<http://api.geoext.org/1.1/examples/feature-grid.html> | You can try this code, this will display a pop-up containing attribute information of layers on that particular point.
```
controls.push(new OpenLayers.Control.WMSGetFeatureInfo({
autoActivate: true,
infoFormat: "application/vnd.ogc.gml",
maxFeatures: 10,
eventListeners: {
"getfeatureinfo": function(e) {
var items = [];
Ext.each(e.features, function(feature) {
items.push({
xtype: "propertygrid",
title: feature.fid,
source: feature.attributes,
editable: false
});
});
new GeoExt.Popup({
title: "Feature Info",
width: 300,
height: 500,
layout: "accordion",
map: app.mapPanel,
location: e.xy,
items: items
}).show();
}
}
}));
```
Ref: <http://workshops.boundlessgeo.com/geoext/stores/getfeatureinfo.html> |
46,634,279 | I'm new to clojure and want to accomplish the following:
I have some functions with a one letter name, a string "commands"
and an argument arg
```
(defn A [x] ...)
(defn B [x] ...)
(defn C [x] ...)
```
I want to have a function (let's call it `apply-fns`) that, given the string with the names of the functions, applies the function to the given argument in order:
```
; commands = "ACCBB"
(apply-fns commands arg)
;should have the same effect as
(B (B (C (C (A arg)))))
```
Any help appreciated | 2017/10/08 | [
"https://Stackoverflow.com/questions/46634279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8741941/"
] | Being a literal genie, I'll give you exactly what you're asking:
```
(defn A [x])
(defn B [x])
(defn C [x])
(def commands "AACCBB")
(defmacro string-fns [arg]
(let [cs (map (comp symbol str) commands)]
`(-> ~arg ~@cs)))
(comment
(macroexpand
'(string-fns :foo)) ;;=> (B (B (C (C (A (A :foo))))))
)
```
Without any context, however, this makes no sense. What are you trying to do? | Your aim is to apply a series of functions (in order), so that the following function is applied to the result of the previous one. The result should be the same as nesting the forms (i.e., function calls), like in your example: `(B (B (C (C (A arg)))))`
If you can use a sequence of the commands (or can extract the sequence from the string representation `"ACCBB"`), you can accomplish this by reducing over the functions, which are named as *commands* in the example.
```
(def commands [A C C B B])
(defn apply-all [initial commands]
(reduce #(%2 %1) initial commands))
```
A fuller example:
```
(defn A [x]
(str x "A"))
(defn B [x]
(str x "B"))
(defn C [x]
(str x "C"))
(def commands [A C C B B])
(defn apply-all [initial commands]
(reduce #(%2 %1) initial commands))
user=> (apply-all "" commands)
; => "ACCBB"
``` |
70,832,568 | I'm trying to get data from the database using ajax to insert it in other element but the post data not passing to **get-data.php**
so what the reason can be and the solution
[![enter image description here](https://i.stack.imgur.com/RTCbi.png)](https://i.stack.imgur.com/RTCbi.png)
[![passed data shown here but no resposns](https://i.stack.imgur.com/VibUZ.png)](https://i.stack.imgur.com/VibUZ.png)
**addBuilding.php**
```
<?php
require_once("./dbConfig.php");
$selectIL = "SELECT * FROM iller ";
$selectIL = $db->prepare($selectIL);
$selectIL->execute();
$res = $selectIL->get_result();
?>
<form action="" method="post">
<select name="pp" id="cites">
<option value="">-select state-</option>
<?php
while ($row = $res->fetch_assoc()) {
?>
<option value="<?= $row['id'] ?>"><?= $row['il_adi'] ?></option>
<?php
}
?>
</select>
<select name="district" id="district">
<option value="">-select district-</option>
</select>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="getdata.js"></script>
```
**getdata.js**
```
$(document).ready(function() {
$("#cites").change(function() {
if ( $("#cites").val()!="") {
$("#district").prop("disabled",false);
}else {
$("#district").prop("disabled",true);
}
var city = $("#cites").val();
$.ajax({
type: "POST",
url:"get-data.php",
data:$(city).serialize(),
success: function(result) {
$("#district").append(result);
}
});
});
});
```
**get-data.php**
I can see the form data in network inspection put no data passing to **get-data.php**
```
<?php
require_once("./dbConfig.php");
if (isset($_POST['pp'])) {
$cites = $_POST['cites'];
$selectIlce = "SELECT * FROM ilceler where il_id=? ";
$selectIlce = $db->prepare($selectIlce);
$selectIlce->bind_param("i", $cites);
$selectIlce->execute();
$res = $selectIlce->get_result();
?>
<?php
while ($row = $res->fetch_assoc()) {
?>
<option value="<?= $row['id'] ?>"><?= $row['ilce_adi'] ?></option>
<?php
}
}
?>
``` | 2022/01/24 | [
"https://Stackoverflow.com/questions/70832568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13661132/"
] | You need to echo the results in get-data.php
```
<?php
while ($row = $res->fetch_assoc()) {
?>
echo "<option value='". $row["id"]."'>".$row['ilce_adi']."</option>";
<?php
}
}
?>
``` | 1- Get data by serialize from form:
```
$("form").serialize()
```
2- Add dataType: "json" to ajax option:
```
$.ajax({
type: "POST",
url:"get-data.php",
data:$(city).serialize(),
dataType: "json",
success: function(result) {
$("#district").append(result);
}
});
``` |
34,717,787 | We are having a Analytics product. For each of our customer we give one JavaScript code, they put that in their web sites. If a user visit our customer site the java script code hit our server so that we store this page visit on behalf of this customer. Each customer contains unique domain name.
we are storing this page visits in MySql table.
Following is the table schema.
```
CREATE TABLE `page_visits` (
`domain` varchar(50) DEFAULT NULL,
`guid` varchar(100) DEFAULT NULL,
`sid` varchar(100) DEFAULT NULL,
`url` varchar(2500) DEFAULT NULL,
`ip` varchar(20) DEFAULT NULL,
`is_new` varchar(20) DEFAULT NULL,
`ref` varchar(2500) DEFAULT NULL,
`user_agent` varchar(255) DEFAULT NULL,
`stats_time` datetime DEFAULT NULL,
`country` varchar(50) DEFAULT NULL,
`region` varchar(50) DEFAULT NULL,
`city` varchar(50) DEFAULT NULL,
`city_lat_long` varchar(50) DEFAULT NULL,
`email` varchar(100) DEFAULT NULL,
KEY `sid_index` (`sid`) USING BTREE,
KEY `domain_index` (`domain`),
KEY `email_index` (`email`),
KEY `stats_time_index` (`stats_time`),
KEY `domain_statstime` (`domain`,`stats_time`),
KEY `domain_email` (`domain`,`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
```
We don't have primary key for this table.
MySql server details
It is Google cloud MySql (version is 5.6) and storage capacity is 10TB.
As of now we are having 350 million rows in our table and table size is 300 GB. We are storing all of our customer details in the same table even though there is no relation between one customer to another.
**Problem 1**: For few of our customers having huge number of rows in table, so performance of queries against these customers are very slow.
Example Query 1:
```
SELECT count(DISTINCT sid) AS count,count(sid) AS total FROM page_views WHERE domain = 'aaa' AND stats_time BETWEEN CONVERT_TZ('2015-02-05 00:00:00','+05:30','+00:00') AND CONVERT_TZ('2016-01-01 23:59:59','+05:30','+00:00');
+---------+---------+
| count | total |
+---------+---------+
| 1056546 | 2713729 |
+---------+---------+
1 row in set (13 min 19.71 sec)
```
I will update more queries here. We need results in below 5-10 seconds, will it be possible?
**Problem 2**: The table size is rapidly increasing, we might hit table size 5 TB by this year end so we want to shard our table. We want to keep all records related to one customer in one machine. What are the best practises for this sharding.
We are thinking following approaches for above issues, please suggest us best practices to overcome these issues.
Create separate table for each customer
1) What are the advantages and disadvantages if we create separate table for each customer. As of now we are having 30k customers we might hit 100k by this year end that means 100k tables in DB. We access all tables simultaneously for Read and Write.
2) We will go with same table and will create partitions based on date range
**UPDATE** : Is a "customer" determined by the domain? **Answer is Yes**
Thanks | 2016/01/11 | [
"https://Stackoverflow.com/questions/34717787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/619097/"
] | First, a critique if the **excessively large datatypes**:
```
`domain` varchar(50) DEFAULT NULL, -- normalize to MEDIUMINT UNSIGNED (3 bytes)
`guid` varchar(100) DEFAULT NULL, -- what is this for?
`sid` varchar(100) DEFAULT NULL, -- varchar?
`url` varchar(2500) DEFAULT NULL,
`ip` varchar(20) DEFAULT NULL, -- too big for IPv4, too small for IPv6; see below
`is_new` varchar(20) DEFAULT NULL, -- flag? Consider `TINYINT` or `ENUM`
`ref` varchar(2500) DEFAULT NULL,
`user_agent` varchar(255) DEFAULT NULL, -- normalize! (add new rows as new agents are created)
`stats_time` datetime DEFAULT NULL,
`country` varchar(50) DEFAULT NULL, -- use standard 2-letter code (see below)
`region` varchar(50) DEFAULT NULL, -- see below
`city` varchar(50) DEFAULT NULL, -- see below
`city_lat_long` varchar(50) DEFAULT NULL, -- unusable in current format; toss?
`email` varchar(100) DEFAULT NULL,
```
For IP addresses, use `inet6_aton()`, then store in `BINARY(16)`.
For `country`, use `CHAR(2) CHARACTER SET ascii` -- only 2 bytes.
country + region + city + (maybe) latlng -- normalize this to a "location".
All these changes may cut the disk footprint in half. Smaller --> more cacheable --> less I/O --> faster.
**Other issues**...
To greatly speed up your `sid` counter, change
```
KEY `domain_statstime` (`domain`,`stats_time`),
```
to
```
KEY dss (domain_id,`stats_time`, sid),
```
That will be a "covering index", hence won't have to bounce between the index and the data 2713729 times -- the bouncing is what cost 13 minutes. (`domain_id` is discussed below.)
This is redundant with the above index, `DROP` it:
KEY `domain_index` (`domain`)
Is a "customer" determined by the `domain`?
Every InnoDB table must have a `PRIMARY KEY`. There are 3 ways to get a PK; you picked the 'worst' one -- a hidden 6-byte integer fabricated by the engine. I assume there is no 'natural' PK available from some combination of columns? Then, an explicit `BIGINT UNSIGNED` is called for. (Yes that would be 8 bytes, but various forms of maintenance need an *explicit* PK.)
If *most* queries include `WHERE domain = '...'`, then I recommend the following. (And this will greatly improve all such queries.)
```
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
domain_id MEDIUMINT UNSIGNED NOT NULL, -- normalized to `Domains`
PRIMARY KEY(domain_id, id), -- clustering on customer gives you the speedup
INDEX(id) -- this keeps AUTO_INCREMENT happy
```
Recommend you look into `pt-online-schema-change` for making all these changes. However, I don't know if it can work without an explicit `PRIMARY KEY`.
"Separate table for each customer"? *No*. This is a common question; the resounding answer is No. I won't repeat all the reasons for not having 100K tables.
**Sharding**
"Sharding" is splitting the data across multiple *machines*.
To do sharding, you need to have code somewhere that looks at `domain` and decides which server will handle the query, then hands it off. Sharding is advisable when you have *write scaling* problems. You did not mention such, so it is unclear whether sharding is advisable.
When sharding on something like `domain` (or `domain_id`), you could use (1) a hash to pick the server, (2) a dictionary lookup (of 100K rows), or (3) a hybrid.
I like the hybrid -- hash to, say, 1024 values, then look up into a 1024-row table to see which machine has the data. Since adding a new shard and migrating a user to a different shard are major undertakings, I feel that the hybrid is a reasonable compromise. The lookup table needs to be distributed to all clients that redirect actions to shards.
If your 'writing' is running out of steam, see [*high speed ingestion*](http://mysql.rjweb.org/doc.php/staging_table) for possible ways to speed that up.
**PARTITIONing**
`PARTITIONing` is splitting the data across multiple "sub-tables".
There are only a [*limited number of use cases*](http://mysql.rjweb.org/doc.php/partitionmaint) where partitioning buys you any performance. You not indicated that any apply to your use case. Read that blog and see if you think that partitioning might be useful.
You mentioned "partition by date range". Will most of the queries include a date range? If so, such partitioning *may* be advisable. (See the link above for best practices.) Some other options come to mind:
Plan A: `PRIMARY KEY(domain_id, stats_time, id)` But that is bulky and requires even more overhead on each secondary index. (Each secondary index silently includes all the columns of the PK.)
Plan B: Have stats\_time include microseconds, then tweak the values to avoid having dups. Then use `stats_time` instead of `id`. But this requires some added complexity, especially if there are multiple clients inserting data. (I can elaborate if needed.)
Plan C: Have a table that maps stats\_time values to ids. Look up the id range before doing the real query, then use both `WHERE id BETWEEN ... AND stats_time ...`. (Again, messy code.)
**Summary tables**
Are many of the queries of the form of counting things over date ranges? Suggest having Summary Tables based perhaps on per-hour. [*More discussion*](http://mysql.rjweb.org/doc.php/summarytables).
`COUNT(DISTINCT sid)` is especially difficult to fold into summary tables. For example, the unique counts for each hour cannot be added together to get the unique count for the day. But I have a [*technique*](http://mysql.rjweb.org/doc.php/uniques) for that, too. | I wouldn't do this if i were you. First thing that come to mind would be, on receive a pageview message, i send the message to a queue so that a worker can pickup and insert to database later (in bulk maybe); also i increase the counter of `siteid:date` in redis (for example). Doing `count` in sql is just a bad idea for this scenario. |
23,629,204 | I'm using KineticJS in my MVC application.
In order to retrieve data from database, I'm making some ajax calls to web services in the API controller. There is an API that returns an id, which I want to assign to the current `Kinetic.Group` id attribute on success.
After drag and drop, a popup `PopUpAddRoom(FloorId)` appears and calls the AddRoom function.
my code:
```
function AddRoom(FloorId, RoomName, TypeID) {
$.ajax({
beforeSend: function (xhr) { // verify session },
url: "/api/someurl", //url for adding the room, that returns room's id
type: "Post",
dataType: 'json',
success: function (data) {
//data is the room id
var r = rightLayer.find("#" + data)[0];
console.log(r.getType()); // here I don't even get the type, I get "Object []"
var rec = r.find("Rect"); //rec is a rectangle inside the group
rec.setId(data);
rightLayer.draw();
}
});
}
```
The problem is that `r = rightLayer.find("#" + data)[0];` is empty. It returns *undefined*.
When I call `console.log(data);` to see if data's content is empty, it returns the correct id !
I initialized the id like this: `id: ''` and want it to change as it gets the data from database. But this failed. Is there something wrong with this code?
**EDIT :**
After figuring out that `id: ''` is really dumb idea (with the help of markE), I tried initializing id to an empty variable ident which gets its value from a web service (this ws increments the id when a new instance is added successfully).
But the problem doesn't come from `r = rightLayer.find("#" + data)[0];`. It's the fact of assigning the id to a node (location of the instruction)
```
var ident;
var group = new Kinetic.Group({
...
id: ident
...
});
```
I added then this line: `ident = data;` after success of the ajax call, still the same error. It seems like this instruction isn't doing nothing. The value of ident isn't changing after that I call `PopUpAddRoom` function. | 2014/05/13 | [
"https://Stackoverflow.com/questions/23629204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3365233/"
] | No, they are not supported. You should use separate struct declarations and regular fields:
```
struct Foo {}
struct Test {
foo: Foo,
}
``` | They are not supported by Rust.
But you can write yourself a proc macro that emulates them. I [have](https://lib.rs/structstruck), it turns
```rust
structstruck::strike!{
struct Test {
foo: struct {}
}
}
```
into
```
struct Foo {}
struct Test {
foo: Foo,
}
```
You haven't explicitly said so, but I suspect that your goal for using nested structs is not more easily readable data structure declarations, but namespacing?
You can't actually have a struct named `Test` and access `Foo` as `Test::Foo`, but you could make yourself a proc macro that at least automatically creates a `mod test { Foo {} }`. |
23,629,204 | I'm using KineticJS in my MVC application.
In order to retrieve data from database, I'm making some ajax calls to web services in the API controller. There is an API that returns an id, which I want to assign to the current `Kinetic.Group` id attribute on success.
After drag and drop, a popup `PopUpAddRoom(FloorId)` appears and calls the AddRoom function.
my code:
```
function AddRoom(FloorId, RoomName, TypeID) {
$.ajax({
beforeSend: function (xhr) { // verify session },
url: "/api/someurl", //url for adding the room, that returns room's id
type: "Post",
dataType: 'json',
success: function (data) {
//data is the room id
var r = rightLayer.find("#" + data)[0];
console.log(r.getType()); // here I don't even get the type, I get "Object []"
var rec = r.find("Rect"); //rec is a rectangle inside the group
rec.setId(data);
rightLayer.draw();
}
});
}
```
The problem is that `r = rightLayer.find("#" + data)[0];` is empty. It returns *undefined*.
When I call `console.log(data);` to see if data's content is empty, it returns the correct id !
I initialized the id like this: `id: ''` and want it to change as it gets the data from database. But this failed. Is there something wrong with this code?
**EDIT :**
After figuring out that `id: ''` is really dumb idea (with the help of markE), I tried initializing id to an empty variable ident which gets its value from a web service (this ws increments the id when a new instance is added successfully).
But the problem doesn't come from `r = rightLayer.find("#" + data)[0];`. It's the fact of assigning the id to a node (location of the instruction)
```
var ident;
var group = new Kinetic.Group({
...
id: ident
...
});
```
I added then this line: `ident = data;` after success of the ajax call, still the same error. It seems like this instruction isn't doing nothing. The value of ident isn't changing after that I call `PopUpAddRoom` function. | 2014/05/13 | [
"https://Stackoverflow.com/questions/23629204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3365233/"
] | No, they are not supported. You should use separate struct declarations and regular fields:
```
struct Foo {}
struct Test {
foo: Foo,
}
``` | I found the optional answer for your request.
Maybe it can help you:
<https://internals.rust-lang.org/t/nested-struct-declaration/13314/4>
[Structural records](https://github.com/rust-lang/rfcs/pull/2584) 592 would give you the nesting (without the privacy controls or naming).
```
// From the RFC
struct RectangleTidy {
dimensions: {
width: u64,
height: u64,
},
color: {
red: u8,
green: u8,
blue: u8,
},
}
```
Below is my old answer, please ignore.
Build using the Stable version: 1.65.0.
Here's a example for you.
[rust playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=4d52faab01bb63bc2ee47c2fc545392c)
codes:
```
#[derive(Debug)]
struct Inner {
i: i32,
}
#[derive(Debug)]
struct Outer {
o: i32,
inner: Inner,
}
pub fn test() {
// add your code here
let obj = Outer {
o: 10,
inner: Inner { i: 9 },
};
assert!(10i32 == obj.o);
assert!(9i32 == obj.inner.i);
println!("{}", obj.o);
println!("{}", obj.inner.i);
println!("{:?}", obj);
}
fn main() {
test();
}
``` |
23,629,204 | I'm using KineticJS in my MVC application.
In order to retrieve data from database, I'm making some ajax calls to web services in the API controller. There is an API that returns an id, which I want to assign to the current `Kinetic.Group` id attribute on success.
After drag and drop, a popup `PopUpAddRoom(FloorId)` appears and calls the AddRoom function.
my code:
```
function AddRoom(FloorId, RoomName, TypeID) {
$.ajax({
beforeSend: function (xhr) { // verify session },
url: "/api/someurl", //url for adding the room, that returns room's id
type: "Post",
dataType: 'json',
success: function (data) {
//data is the room id
var r = rightLayer.find("#" + data)[0];
console.log(r.getType()); // here I don't even get the type, I get "Object []"
var rec = r.find("Rect"); //rec is a rectangle inside the group
rec.setId(data);
rightLayer.draw();
}
});
}
```
The problem is that `r = rightLayer.find("#" + data)[0];` is empty. It returns *undefined*.
When I call `console.log(data);` to see if data's content is empty, it returns the correct id !
I initialized the id like this: `id: ''` and want it to change as it gets the data from database. But this failed. Is there something wrong with this code?
**EDIT :**
After figuring out that `id: ''` is really dumb idea (with the help of markE), I tried initializing id to an empty variable ident which gets its value from a web service (this ws increments the id when a new instance is added successfully).
But the problem doesn't come from `r = rightLayer.find("#" + data)[0];`. It's the fact of assigning the id to a node (location of the instruction)
```
var ident;
var group = new Kinetic.Group({
...
id: ident
...
});
```
I added then this line: `ident = data;` after success of the ajax call, still the same error. It seems like this instruction isn't doing nothing. The value of ident isn't changing after that I call `PopUpAddRoom` function. | 2014/05/13 | [
"https://Stackoverflow.com/questions/23629204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3365233/"
] | They are not supported by Rust.
But you can write yourself a proc macro that emulates them. I [have](https://lib.rs/structstruck), it turns
```rust
structstruck::strike!{
struct Test {
foo: struct {}
}
}
```
into
```
struct Foo {}
struct Test {
foo: Foo,
}
```
You haven't explicitly said so, but I suspect that your goal for using nested structs is not more easily readable data structure declarations, but namespacing?
You can't actually have a struct named `Test` and access `Foo` as `Test::Foo`, but you could make yourself a proc macro that at least automatically creates a `mod test { Foo {} }`. | I found the optional answer for your request.
Maybe it can help you:
<https://internals.rust-lang.org/t/nested-struct-declaration/13314/4>
[Structural records](https://github.com/rust-lang/rfcs/pull/2584) 592 would give you the nesting (without the privacy controls or naming).
```
// From the RFC
struct RectangleTidy {
dimensions: {
width: u64,
height: u64,
},
color: {
red: u8,
green: u8,
blue: u8,
},
}
```
Below is my old answer, please ignore.
Build using the Stable version: 1.65.0.
Here's a example for you.
[rust playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=4d52faab01bb63bc2ee47c2fc545392c)
codes:
```
#[derive(Debug)]
struct Inner {
i: i32,
}
#[derive(Debug)]
struct Outer {
o: i32,
inner: Inner,
}
pub fn test() {
// add your code here
let obj = Outer {
o: 10,
inner: Inner { i: 9 },
};
assert!(10i32 == obj.o);
assert!(9i32 == obj.inner.i);
println!("{}", obj.o);
println!("{}", obj.inner.i);
println!("{:?}", obj);
}
fn main() {
test();
}
``` |
4,239,645 | I tried searching a bit and didn't find an answer. Does the Razor View Engine work in Mono? | 2010/11/21 | [
"https://Stackoverflow.com/questions/4239645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/69742/"
] | My guess is that you'll need to wait for the release of MVC3 (when it becomes open-source) before that can be answered perfectly.
I'm sure the Mono team will make it work, though. | It looks like we're getting there:
<http://gonzalo.name/blog/archive/2011/Jan-21.html>
Looks like it isn't in any of the published versions yet, but you can run it from source control. |
4,239,645 | I tried searching a bit and didn't find an answer. Does the Razor View Engine work in Mono? | 2010/11/21 | [
"https://Stackoverflow.com/questions/4239645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/69742/"
] | Yes, it does. I have it working with mono on Linux.
You need mono 2.10.2+ from the stable sources from
~~<http://ftp.novell.com/pub/mono/sources-stable/>~~
<http://download.mono-project.com/sources/mono/>
Then, you need to localcopy these assemblies into your app's bin directory (you take them from Visual Studio on Windows):
System.Web.Mvc.dll
System.Web.Razor.dll
System.Web.WebPages.dll
System.Web.WebPages.Deployment.dll
System.Web.WebPages.Razor.dll
Then, you might have to get rid of the following errors you might have made like this:
Error: Storage scopes cannot be created when \_AppStart is executing.
Cause: Microsoft.Web.Infrastructure.dll was localcopied to the bin
directory.
Resolution: Delete Microsoft.Web.Infrastructure.dll **and use the mono
version**.
Error: Invalid IL code in System.Web.Handlers.ScriptModule:.ctor ():
method body is empty.
Cause: System.Web.Extensions.dll somehow gets localcopied to the bin
directory.
Resolution: Delete System.Web.Extensions.dll **and use the mono version**.
Error: The classes in the module cannot be loaded. Description: HTTP
500. Error processing request.
Cause: System.Web.WebPages.Administration.dll was localcopied to the bin
directory.
Resolution: Delete System.Web.WebPages.Administration.dll **and unreference it**
Error: Could not load type
'System.Web.WebPages.Razor.RazorBuildProvider' from assembly
'System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35'. Description: HTTP 500. Error
processing request.
Cause: System.Web.Razor.dll is corrupt or missing ~~(or x64 instead of x32 or vice-versa)~~ ...
Resolution: Get an **uncorrupted** version of System.Web.Razor.dll and
localcopy to the bin directory
**Edit**
As of mono 2.12 / MonoDevelop 2.8, all of this is not necessary anymore.
Note that on 2.10 (Ubuntu 11.10), one needs to localcopy `System.Web.DynamicData.dll` as well, or else you get an error that only occurs on App\_Start (if you don't do that, you get a YSOD the first time you call a page, but ONLY the first time, because only then App\_Start is called.).
**Note**
for mono 3.0+ with ASP.NET MVC4:
There is a "bug" in the install script.
Or rather an incompleteness.
mod-mono, fastcgi-mono-server4 and xsp4 won't work correctly.
For example: fastcgi-mono-server4 gives you this debug output:
```
[error] 3384#0: *101 upstream sent unexpected FastCGI record: 3 while reading response header from upstream, client: 127.0.0.1, server: localhost, request: "GET / HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000", host: "localhost:8000"
```
This is, because after the installation of mono3, it uses framework 4.5, but xsp, fastcgi-mono-server4 and mod-mono are not in the 4.5 GAC, only the 4.0 gac.
To fix this, use this bash script:
```
#!/bin/bash
# Your mono directory
#PREFIX=/usr
PREFIX=/opt/mono/3.0.3
FILES=('mod-mono-server4'
'fastcgi-mono-server4'
'xsp4')
cd $PREFIX/lib/mono/4.0
for file in "${FILES[@]}"
do
cp "$file.exe" ../4.5
done
cd $PREFIX/bin
for file in "${FILES[@]}"
do
sed -ie 's|mono/4.0|mono/4.5|g' $file
done
```
And if you use it via FastCGI (e.g. nginx), you also need this fix for TransmitFile for the chuncked\_encoding bug
[Why do I have unwanted extra bytes at the beginning of image?](https://stackoverflow.com/questions/14662795/why-do-i-have-unwanted-extra-bytes-at-the-beginning-of-image/14671753#14671753) (fixed in mono 3.2.3)
**PS:**
You can get the .debs for 3.x from here:
<https://www.meebey.net/posts/mono_3.0_preview_debian_ubuntu_packages/>
or compile them yourselfs from github
[Installing Mono 3.x in Ubuntu/Debian](https://stackoverflow.com/questions/13365158/installing-mono-3-0)
or like this from the stable sources
<http://ubuntuforums.org/showthread.php?t=1591370>
**2015**
You can now use the [Xamarin provided packages](http://www.mono-project.com/docs/getting-started/install/linux/#debian-ubuntu-and-derivatives)
```
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF
echo "deb http://download.mono-project.com/repo/debian wheezy main" | sudo tee /etc/apt/sources.list.d/mono-xamarin.list
sudo apt-get update
```
If you need the vary latest features, you can also fetch the [CI packages (nightly builds, so to say)](http://www.mono-project.com/docs/getting-started/install/linux/ci-packages/), if you need the latest (or almost latest) version
```
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF
echo "deb http://jenkins.mono-project.com/repo/debian sid main" | sudo tee /etc/apt/sources.list.d/mono-jenkins.list
sudo apt-get update
``` | My guess is that you'll need to wait for the release of MVC3 (when it becomes open-source) before that can be answered perfectly.
I'm sure the Mono team will make it work, though. |
4,239,645 | I tried searching a bit and didn't find an answer. Does the Razor View Engine work in Mono? | 2010/11/21 | [
"https://Stackoverflow.com/questions/4239645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/69742/"
] | [Not yet.](http://lists.ximian.com/pipermail/mono-list/2010-November/046052.html) | It looks like we're getting there:
<http://gonzalo.name/blog/archive/2011/Jan-21.html>
Looks like it isn't in any of the published versions yet, but you can run it from source control. |
4,239,645 | I tried searching a bit and didn't find an answer. Does the Razor View Engine work in Mono? | 2010/11/21 | [
"https://Stackoverflow.com/questions/4239645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/69742/"
] | Yes, it does. I have it working with mono on Linux.
You need mono 2.10.2+ from the stable sources from
~~<http://ftp.novell.com/pub/mono/sources-stable/>~~
<http://download.mono-project.com/sources/mono/>
Then, you need to localcopy these assemblies into your app's bin directory (you take them from Visual Studio on Windows):
System.Web.Mvc.dll
System.Web.Razor.dll
System.Web.WebPages.dll
System.Web.WebPages.Deployment.dll
System.Web.WebPages.Razor.dll
Then, you might have to get rid of the following errors you might have made like this:
Error: Storage scopes cannot be created when \_AppStart is executing.
Cause: Microsoft.Web.Infrastructure.dll was localcopied to the bin
directory.
Resolution: Delete Microsoft.Web.Infrastructure.dll **and use the mono
version**.
Error: Invalid IL code in System.Web.Handlers.ScriptModule:.ctor ():
method body is empty.
Cause: System.Web.Extensions.dll somehow gets localcopied to the bin
directory.
Resolution: Delete System.Web.Extensions.dll **and use the mono version**.
Error: The classes in the module cannot be loaded. Description: HTTP
500. Error processing request.
Cause: System.Web.WebPages.Administration.dll was localcopied to the bin
directory.
Resolution: Delete System.Web.WebPages.Administration.dll **and unreference it**
Error: Could not load type
'System.Web.WebPages.Razor.RazorBuildProvider' from assembly
'System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35'. Description: HTTP 500. Error
processing request.
Cause: System.Web.Razor.dll is corrupt or missing ~~(or x64 instead of x32 or vice-versa)~~ ...
Resolution: Get an **uncorrupted** version of System.Web.Razor.dll and
localcopy to the bin directory
**Edit**
As of mono 2.12 / MonoDevelop 2.8, all of this is not necessary anymore.
Note that on 2.10 (Ubuntu 11.10), one needs to localcopy `System.Web.DynamicData.dll` as well, or else you get an error that only occurs on App\_Start (if you don't do that, you get a YSOD the first time you call a page, but ONLY the first time, because only then App\_Start is called.).
**Note**
for mono 3.0+ with ASP.NET MVC4:
There is a "bug" in the install script.
Or rather an incompleteness.
mod-mono, fastcgi-mono-server4 and xsp4 won't work correctly.
For example: fastcgi-mono-server4 gives you this debug output:
```
[error] 3384#0: *101 upstream sent unexpected FastCGI record: 3 while reading response header from upstream, client: 127.0.0.1, server: localhost, request: "GET / HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000", host: "localhost:8000"
```
This is, because after the installation of mono3, it uses framework 4.5, but xsp, fastcgi-mono-server4 and mod-mono are not in the 4.5 GAC, only the 4.0 gac.
To fix this, use this bash script:
```
#!/bin/bash
# Your mono directory
#PREFIX=/usr
PREFIX=/opt/mono/3.0.3
FILES=('mod-mono-server4'
'fastcgi-mono-server4'
'xsp4')
cd $PREFIX/lib/mono/4.0
for file in "${FILES[@]}"
do
cp "$file.exe" ../4.5
done
cd $PREFIX/bin
for file in "${FILES[@]}"
do
sed -ie 's|mono/4.0|mono/4.5|g' $file
done
```
And if you use it via FastCGI (e.g. nginx), you also need this fix for TransmitFile for the chuncked\_encoding bug
[Why do I have unwanted extra bytes at the beginning of image?](https://stackoverflow.com/questions/14662795/why-do-i-have-unwanted-extra-bytes-at-the-beginning-of-image/14671753#14671753) (fixed in mono 3.2.3)
**PS:**
You can get the .debs for 3.x from here:
<https://www.meebey.net/posts/mono_3.0_preview_debian_ubuntu_packages/>
or compile them yourselfs from github
[Installing Mono 3.x in Ubuntu/Debian](https://stackoverflow.com/questions/13365158/installing-mono-3-0)
or like this from the stable sources
<http://ubuntuforums.org/showthread.php?t=1591370>
**2015**
You can now use the [Xamarin provided packages](http://www.mono-project.com/docs/getting-started/install/linux/#debian-ubuntu-and-derivatives)
```
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF
echo "deb http://download.mono-project.com/repo/debian wheezy main" | sudo tee /etc/apt/sources.list.d/mono-xamarin.list
sudo apt-get update
```
If you need the vary latest features, you can also fetch the [CI packages (nightly builds, so to say)](http://www.mono-project.com/docs/getting-started/install/linux/ci-packages/), if you need the latest (or almost latest) version
```
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF
echo "deb http://jenkins.mono-project.com/repo/debian sid main" | sudo tee /etc/apt/sources.list.d/mono-jenkins.list
sudo apt-get update
``` | [Not yet.](http://lists.ximian.com/pipermail/mono-list/2010-November/046052.html) |
4,239,645 | I tried searching a bit and didn't find an answer. Does the Razor View Engine work in Mono? | 2010/11/21 | [
"https://Stackoverflow.com/questions/4239645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/69742/"
] | Mono 2.10 onwards fully supports MVC3 and Razor, albeit the Mono Project cannot currently ship Mono with an open-source implementation of the MVC3/Razor stack included (in the same way as MVC1 and MVC2 are included) just yet.
From the [Release Notes](http://www.mono-project.com/Release_Notes_Mono_2.10#ASP.NET_MVC3_Support):
>
> Although ASP.NET MVC3 is open source
> and licensed under the terms of the
> MS-PL license, it takes a few
> dependencies on new libraries that are
> not open source nor are they part of
> the Microsoft.NET Framework.
>
>
> At this point we do not have open
> source implementations of those
> libraries, so we can not ship the full
> ASP.NET MVC3 stack with Mono (We still
> ship ASP.NET MVC 1 and MVC 2 with Mono
> for your deployment enjoyment).
>
>
> This Mono release however has enough
> bug fixes and patches that you will be
> able to run ASP.NET MVC3 sites with
> it.
>
>
> | It looks like we're getting there:
<http://gonzalo.name/blog/archive/2011/Jan-21.html>
Looks like it isn't in any of the published versions yet, but you can run it from source control. |
4,239,645 | I tried searching a bit and didn't find an answer. Does the Razor View Engine work in Mono? | 2010/11/21 | [
"https://Stackoverflow.com/questions/4239645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/69742/"
] | Yes, it does. I have it working with mono on Linux.
You need mono 2.10.2+ from the stable sources from
~~<http://ftp.novell.com/pub/mono/sources-stable/>~~
<http://download.mono-project.com/sources/mono/>
Then, you need to localcopy these assemblies into your app's bin directory (you take them from Visual Studio on Windows):
System.Web.Mvc.dll
System.Web.Razor.dll
System.Web.WebPages.dll
System.Web.WebPages.Deployment.dll
System.Web.WebPages.Razor.dll
Then, you might have to get rid of the following errors you might have made like this:
Error: Storage scopes cannot be created when \_AppStart is executing.
Cause: Microsoft.Web.Infrastructure.dll was localcopied to the bin
directory.
Resolution: Delete Microsoft.Web.Infrastructure.dll **and use the mono
version**.
Error: Invalid IL code in System.Web.Handlers.ScriptModule:.ctor ():
method body is empty.
Cause: System.Web.Extensions.dll somehow gets localcopied to the bin
directory.
Resolution: Delete System.Web.Extensions.dll **and use the mono version**.
Error: The classes in the module cannot be loaded. Description: HTTP
500. Error processing request.
Cause: System.Web.WebPages.Administration.dll was localcopied to the bin
directory.
Resolution: Delete System.Web.WebPages.Administration.dll **and unreference it**
Error: Could not load type
'System.Web.WebPages.Razor.RazorBuildProvider' from assembly
'System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35'. Description: HTTP 500. Error
processing request.
Cause: System.Web.Razor.dll is corrupt or missing ~~(or x64 instead of x32 or vice-versa)~~ ...
Resolution: Get an **uncorrupted** version of System.Web.Razor.dll and
localcopy to the bin directory
**Edit**
As of mono 2.12 / MonoDevelop 2.8, all of this is not necessary anymore.
Note that on 2.10 (Ubuntu 11.10), one needs to localcopy `System.Web.DynamicData.dll` as well, or else you get an error that only occurs on App\_Start (if you don't do that, you get a YSOD the first time you call a page, but ONLY the first time, because only then App\_Start is called.).
**Note**
for mono 3.0+ with ASP.NET MVC4:
There is a "bug" in the install script.
Or rather an incompleteness.
mod-mono, fastcgi-mono-server4 and xsp4 won't work correctly.
For example: fastcgi-mono-server4 gives you this debug output:
```
[error] 3384#0: *101 upstream sent unexpected FastCGI record: 3 while reading response header from upstream, client: 127.0.0.1, server: localhost, request: "GET / HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000", host: "localhost:8000"
```
This is, because after the installation of mono3, it uses framework 4.5, but xsp, fastcgi-mono-server4 and mod-mono are not in the 4.5 GAC, only the 4.0 gac.
To fix this, use this bash script:
```
#!/bin/bash
# Your mono directory
#PREFIX=/usr
PREFIX=/opt/mono/3.0.3
FILES=('mod-mono-server4'
'fastcgi-mono-server4'
'xsp4')
cd $PREFIX/lib/mono/4.0
for file in "${FILES[@]}"
do
cp "$file.exe" ../4.5
done
cd $PREFIX/bin
for file in "${FILES[@]}"
do
sed -ie 's|mono/4.0|mono/4.5|g' $file
done
```
And if you use it via FastCGI (e.g. nginx), you also need this fix for TransmitFile for the chuncked\_encoding bug
[Why do I have unwanted extra bytes at the beginning of image?](https://stackoverflow.com/questions/14662795/why-do-i-have-unwanted-extra-bytes-at-the-beginning-of-image/14671753#14671753) (fixed in mono 3.2.3)
**PS:**
You can get the .debs for 3.x from here:
<https://www.meebey.net/posts/mono_3.0_preview_debian_ubuntu_packages/>
or compile them yourselfs from github
[Installing Mono 3.x in Ubuntu/Debian](https://stackoverflow.com/questions/13365158/installing-mono-3-0)
or like this from the stable sources
<http://ubuntuforums.org/showthread.php?t=1591370>
**2015**
You can now use the [Xamarin provided packages](http://www.mono-project.com/docs/getting-started/install/linux/#debian-ubuntu-and-derivatives)
```
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF
echo "deb http://download.mono-project.com/repo/debian wheezy main" | sudo tee /etc/apt/sources.list.d/mono-xamarin.list
sudo apt-get update
```
If you need the vary latest features, you can also fetch the [CI packages (nightly builds, so to say)](http://www.mono-project.com/docs/getting-started/install/linux/ci-packages/), if you need the latest (or almost latest) version
```
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF
echo "deb http://jenkins.mono-project.com/repo/debian sid main" | sudo tee /etc/apt/sources.list.d/mono-jenkins.list
sudo apt-get update
``` | It looks like we're getting there:
<http://gonzalo.name/blog/archive/2011/Jan-21.html>
Looks like it isn't in any of the published versions yet, but you can run it from source control. |
4,239,645 | I tried searching a bit and didn't find an answer. Does the Razor View Engine work in Mono? | 2010/11/21 | [
"https://Stackoverflow.com/questions/4239645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/69742/"
] | Yes, it does. I have it working with mono on Linux.
You need mono 2.10.2+ from the stable sources from
~~<http://ftp.novell.com/pub/mono/sources-stable/>~~
<http://download.mono-project.com/sources/mono/>
Then, you need to localcopy these assemblies into your app's bin directory (you take them from Visual Studio on Windows):
System.Web.Mvc.dll
System.Web.Razor.dll
System.Web.WebPages.dll
System.Web.WebPages.Deployment.dll
System.Web.WebPages.Razor.dll
Then, you might have to get rid of the following errors you might have made like this:
Error: Storage scopes cannot be created when \_AppStart is executing.
Cause: Microsoft.Web.Infrastructure.dll was localcopied to the bin
directory.
Resolution: Delete Microsoft.Web.Infrastructure.dll **and use the mono
version**.
Error: Invalid IL code in System.Web.Handlers.ScriptModule:.ctor ():
method body is empty.
Cause: System.Web.Extensions.dll somehow gets localcopied to the bin
directory.
Resolution: Delete System.Web.Extensions.dll **and use the mono version**.
Error: The classes in the module cannot be loaded. Description: HTTP
500. Error processing request.
Cause: System.Web.WebPages.Administration.dll was localcopied to the bin
directory.
Resolution: Delete System.Web.WebPages.Administration.dll **and unreference it**
Error: Could not load type
'System.Web.WebPages.Razor.RazorBuildProvider' from assembly
'System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35'. Description: HTTP 500. Error
processing request.
Cause: System.Web.Razor.dll is corrupt or missing ~~(or x64 instead of x32 or vice-versa)~~ ...
Resolution: Get an **uncorrupted** version of System.Web.Razor.dll and
localcopy to the bin directory
**Edit**
As of mono 2.12 / MonoDevelop 2.8, all of this is not necessary anymore.
Note that on 2.10 (Ubuntu 11.10), one needs to localcopy `System.Web.DynamicData.dll` as well, or else you get an error that only occurs on App\_Start (if you don't do that, you get a YSOD the first time you call a page, but ONLY the first time, because only then App\_Start is called.).
**Note**
for mono 3.0+ with ASP.NET MVC4:
There is a "bug" in the install script.
Or rather an incompleteness.
mod-mono, fastcgi-mono-server4 and xsp4 won't work correctly.
For example: fastcgi-mono-server4 gives you this debug output:
```
[error] 3384#0: *101 upstream sent unexpected FastCGI record: 3 while reading response header from upstream, client: 127.0.0.1, server: localhost, request: "GET / HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000", host: "localhost:8000"
```
This is, because after the installation of mono3, it uses framework 4.5, but xsp, fastcgi-mono-server4 and mod-mono are not in the 4.5 GAC, only the 4.0 gac.
To fix this, use this bash script:
```
#!/bin/bash
# Your mono directory
#PREFIX=/usr
PREFIX=/opt/mono/3.0.3
FILES=('mod-mono-server4'
'fastcgi-mono-server4'
'xsp4')
cd $PREFIX/lib/mono/4.0
for file in "${FILES[@]}"
do
cp "$file.exe" ../4.5
done
cd $PREFIX/bin
for file in "${FILES[@]}"
do
sed -ie 's|mono/4.0|mono/4.5|g' $file
done
```
And if you use it via FastCGI (e.g. nginx), you also need this fix for TransmitFile for the chuncked\_encoding bug
[Why do I have unwanted extra bytes at the beginning of image?](https://stackoverflow.com/questions/14662795/why-do-i-have-unwanted-extra-bytes-at-the-beginning-of-image/14671753#14671753) (fixed in mono 3.2.3)
**PS:**
You can get the .debs for 3.x from here:
<https://www.meebey.net/posts/mono_3.0_preview_debian_ubuntu_packages/>
or compile them yourselfs from github
[Installing Mono 3.x in Ubuntu/Debian](https://stackoverflow.com/questions/13365158/installing-mono-3-0)
or like this from the stable sources
<http://ubuntuforums.org/showthread.php?t=1591370>
**2015**
You can now use the [Xamarin provided packages](http://www.mono-project.com/docs/getting-started/install/linux/#debian-ubuntu-and-derivatives)
```
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF
echo "deb http://download.mono-project.com/repo/debian wheezy main" | sudo tee /etc/apt/sources.list.d/mono-xamarin.list
sudo apt-get update
```
If you need the vary latest features, you can also fetch the [CI packages (nightly builds, so to say)](http://www.mono-project.com/docs/getting-started/install/linux/ci-packages/), if you need the latest (or almost latest) version
```
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF
echo "deb http://jenkins.mono-project.com/repo/debian sid main" | sudo tee /etc/apt/sources.list.d/mono-jenkins.list
sudo apt-get update
``` | Mono 2.10 onwards fully supports MVC3 and Razor, albeit the Mono Project cannot currently ship Mono with an open-source implementation of the MVC3/Razor stack included (in the same way as MVC1 and MVC2 are included) just yet.
From the [Release Notes](http://www.mono-project.com/Release_Notes_Mono_2.10#ASP.NET_MVC3_Support):
>
> Although ASP.NET MVC3 is open source
> and licensed under the terms of the
> MS-PL license, it takes a few
> dependencies on new libraries that are
> not open source nor are they part of
> the Microsoft.NET Framework.
>
>
> At this point we do not have open
> source implementations of those
> libraries, so we can not ship the full
> ASP.NET MVC3 stack with Mono (We still
> ship ASP.NET MVC 1 and MVC 2 with Mono
> for your deployment enjoyment).
>
>
> This Mono release however has enough
> bug fixes and patches that you will be
> able to run ASP.NET MVC3 sites with
> it.
>
>
> |
22,104,670 | I am writing data to a table and allocating a "group-id" for each batch of data that is written. To illustrate, consider the following table.
```
GroupId Value
------- -----
1 a
1 b
1 c
2 a
2 b
3 a
3 b
3 c
3 d
```
In this example, there are three groups of data, each with similar but varying values.
How do I query this table to find a group that contains a given set of values? For instance, if I query for (a,b,c) the result should be group 1. Similarly, a query for (b,a) should result in group 2, and a query for (a, b, c, e) should result in the empty set.
I can write a stored procedure that performs the following steps:
* select distinct GroupId from Groups -- and store locally
* for each distinct GroupId: perform a set-difference (`except`) between the input and table values (for the group), and vice versa
* return the GroupId if both set-difference operations produced empty sets
This seems a bit excessive, and I hoping to leverage some other commands in SQL to simplify. Is there a simpler way to perform a set-comparison in this context, or to select the group ID that contains the exact input values for the query? | 2014/02/28 | [
"https://Stackoverflow.com/questions/22104670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/131407/"
] | This is a set-within-sets query. I like to solve it using `group by` and `having`:
```
select groupid
from GroupValues gv
group by groupid
having sum(case when value = 'a' then 1 else 0 end) > 0 and
sum(case when value = 'b' then 1 else 0 end) > 0 and
sum(case when value = 'c' then 1 else 0 end) > 0 and
sum(case when value not in ('a', 'b', 'c') then 1 else - end) = 0;
```
The first three conditions in the `having` clause check that each elements exists. The last condition checks that there are no other values. This method is quite flexible, for various exclusions and inclusion conditions on the values you are looking for.
EDIT:
If you want to pass in a list, you can use:
```
with thelist as (
select 'a' as value union all
select 'b' union all
select 'c'
)
select groupid
from GroupValues gv left outer join
thelist
on gv.value = thelist.value
group by groupid
having count(distinct gv.value) = (select count(*) from thelist) and
count(distinct (case when gv.value = thelist.value then gv.value end)) = count(distinct gv.value);
```
Here the `having` clause counts the number of matching values and makes sure that this is the same size as the list.
EDIT:
query compile failed because missing the table alias. updated with right table alias. | This is kind of ugly, but it works. On larger datasets I'm not sure what performance would look like, but the nested instances of `#GroupValues` key off `GroupID` in the main table so I think as long as you have a good index on `GroupID` it probably wouldn't be too horrible.
```
If Object_ID('tempdb..#GroupValues') Is Not Null Drop Table #GroupValues
Create Table #GroupValues (GroupID Int, Val Varchar(10));
Insert #GroupValues (GroupID, Val)
Values (1,'a'),(1,'b'),(1,'c'),(2,'a'),(2,'b'),(3,'a'),(3,'b'),(3,'c'),(3,'d');
If Object_ID('tempdb..#FindValues') Is Not Null Drop Table #FindValues
Create Table #FindValues (Val Varchar(10));
Insert #FindValues (Val)
Values ('a'),('b'),('c');
Select Distinct gv.GroupID
From (Select Distinct GroupID
From #GroupValues) gv
Where Not Exists (Select 1
From #FindValues fv2
Where Not Exists (Select 1
From #GroupValues gv2
Where gv.GroupID = gv2.GroupID
And fv2.Val = gv2.Val))
And Not Exists (Select 1
From #GroupValues gv3
Where gv3.GroupID = gv.GroupID
And Not Exists (Select 1
From #FindValues fv3
Where gv3.Val = fv3.Val))
``` |
41,283,816 | Not able to grasp the concept behind these two different terms. Can anyone please help out with an example? | 2016/12/22 | [
"https://Stackoverflow.com/questions/41283816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2739470/"
] | You can try with this code :
```
<?php $contact='[contact-form-7 id="1442" title="Service 1 "]'?>
<?php echo do_shortcode($contact);?>
``` | your method is correct but you can also try this `apply_filters('the_content','[contact-form-7 id="1442" title="Service 1"]')`
also please make sure there is a contact form 7 exists with the id, '1442' |
41,283,816 | Not able to grasp the concept behind these two different terms. Can anyone please help out with an example? | 2016/12/22 | [
"https://Stackoverflow.com/questions/41283816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2739470/"
] | I tried to insert an URL and it worked:
<a href="https://[contact-form-7 id="10742" title="Register"]">
Hope it resolves your problem | your method is correct but you can also try this `apply_filters('the_content','[contact-form-7 id="1442" title="Service 1"]')`
also please make sure there is a contact form 7 exists with the id, '1442' |
41,283,816 | Not able to grasp the concept behind these two different terms. Can anyone please help out with an example? | 2016/12/22 | [
"https://Stackoverflow.com/questions/41283816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2739470/"
] | You can try with this code :
```
<?php $contact='[contact-form-7 id="1442" title="Service 1 "]'?>
<?php echo do_shortcode($contact);?>
``` | You can't embed it into a HTML file, you need to have a .PHP file connected to a server with wordpress installed on it so the php functions and wordpress functions could work. |
41,283,816 | Not able to grasp the concept behind these two different terms. Can anyone please help out with an example? | 2016/12/22 | [
"https://Stackoverflow.com/questions/41283816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2739470/"
] | I tried to insert an URL and it worked:
<a href="https://[contact-form-7 id="10742" title="Register"]">
Hope it resolves your problem | You can't embed it into a HTML file, you need to have a .PHP file connected to a server with wordpress installed on it so the php functions and wordpress functions could work. |
41,283,816 | Not able to grasp the concept behind these two different terms. Can anyone please help out with an example? | 2016/12/22 | [
"https://Stackoverflow.com/questions/41283816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2739470/"
] | You can try with this code :
```
<?php $contact='[contact-form-7 id="1442" title="Service 1 "]'?>
<?php echo do_shortcode($contact);?>
``` | I tried to insert an URL and it worked:
<a href="https://[contact-form-7 id="10742" title="Register"]">
Hope it resolves your problem |
64,731 | Why are questions allowed to have two similar tags?
For example, the following question has two tags assigned, [.net](/questions/tagged/.net "show questions tagged '.net'") and [.net3.5](/questions/tagged/.net3.5 "show questions tagged '.net3.5'").
<https://stackoverflow.com/posts/3726446/revisions>, revision 5 or earlier. | 2010/09/16 | [
"https://meta.stackexchange.com/questions/64731",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/147192/"
] | The `.net` tag is for questions generally concerning the .NET Framework, independent of the version, while the `.net3.5` tag should indicate a question is specific to that version. In this case I guess the OP wasn't certain whether his question applies to all versions or not, someone knowing should adequately retag. | Well the tags aren't the same are they. The `.net` refers to the .NET Framework as a whole. The `.net3.5` refers specifically to version 3.5 of the Framework.
It should probably be retagged to just `.net3.5` |
64,731 | Why are questions allowed to have two similar tags?
For example, the following question has two tags assigned, [.net](/questions/tagged/.net "show questions tagged '.net'") and [.net3.5](/questions/tagged/.net3.5 "show questions tagged '.net3.5'").
<https://stackoverflow.com/posts/3726446/revisions>, revision 5 or earlier. | 2010/09/16 | [
"https://meta.stackexchange.com/questions/64731",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/147192/"
] | Contrary to the answers posted so far tagging with both tags is correct.
* The `.net3.5` tag is needed to indicate that either the question is about a specific feature of the version 3.5 of the .NET framework or to indicate that the user is using that specific version, and thus solutions that are not compatible with it are unacceptable.
* The `.net` tag is also needed for several reasons:
+ The answers qualify for the `.net` badge which indicates a knowledge about the entire .NET framework, including the specific 3.5 version
+ Many people favorite the main tag but not the version specific tag.
+ Similarly, many people ignore the main tag but not the specific tag.
+ Someone searching for a similar problem is very likely to search for `[.net] text` instead of `[.net3.5] text`. | Well the tags aren't the same are they. The `.net` refers to the .NET Framework as a whole. The `.net3.5` refers specifically to version 3.5 of the Framework.
It should probably be retagged to just `.net3.5` |
64,731 | Why are questions allowed to have two similar tags?
For example, the following question has two tags assigned, [.net](/questions/tagged/.net "show questions tagged '.net'") and [.net3.5](/questions/tagged/.net3.5 "show questions tagged '.net3.5'").
<https://stackoverflow.com/posts/3726446/revisions>, revision 5 or earlier. | 2010/09/16 | [
"https://meta.stackexchange.com/questions/64731",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/147192/"
] | Contrary to the answers posted so far tagging with both tags is correct.
* The `.net3.5` tag is needed to indicate that either the question is about a specific feature of the version 3.5 of the .NET framework or to indicate that the user is using that specific version, and thus solutions that are not compatible with it are unacceptable.
* The `.net` tag is also needed for several reasons:
+ The answers qualify for the `.net` badge which indicates a knowledge about the entire .NET framework, including the specific 3.5 version
+ Many people favorite the main tag but not the version specific tag.
+ Similarly, many people ignore the main tag but not the specific tag.
+ Someone searching for a similar problem is very likely to search for `[.net] text` instead of `[.net3.5] text`. | The `.net` tag is for questions generally concerning the .NET Framework, independent of the version, while the `.net3.5` tag should indicate a question is specific to that version. In this case I guess the OP wasn't certain whether his question applies to all versions or not, someone knowing should adequately retag. |
166,616 | Is there a word to describe the fear of never again seeing one's mother (or at least any person)?
I have already checked the list of phobias that Wikipedia offers but could not find anything that fits the specific meaning I am looking for; perhaps there is such a word, but it does not have the word *phobia* attached to it.
Thanks. | 2014/04/28 | [
"https://english.stackexchange.com/questions/166616",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/60619/"
] | Is "[separation anxiety disorder](http://en.wikipedia.org/wiki/Separation_anxiety_disorder)" the expression you're looking for?
>
> *SAD (Separation Anxiety Disorder) is a condition in which an individual experiments excessive anxiety regarding separation from home or from people to whom the individual has a strong emotional attachment, i.e. a parent, grandparents, or siblings.*
>
>
> | The ***fear of not seeing one's mother ever again*** also refers to the ***fear of death or*** ***dead things*** and is called **NECROPHOBIA**. |
7,914,579 | Say I have a table of data that looks like:
```
ItemNo | ItemCount | Proportion
------------------------------------------
1 3 0.15
2 2 0.10
3 3 0.15
4 0 0.00
5 2 0.10
6 1 0.05
7 5 0.25
8 4 0.20
```
In other words, there are a total of 20 items, and the cumulative proportion of each `ItemNo` sums to 100%. The ordering of the table rows is important here.
Is it possible to perform a SQL query ***without loops or cursors*** to return the **first** `ItemNo` which exceeds a cumulative proportion?
In other words if the 'proportion' I wanted to check was 35%, the first row which exceeds that is `ItemNo 3`, because 0.15 + 0.10 + 0.15 = 0.40
Similarly, if I wanted to find the first row which exceeded 75%, that would be `ItemNo 7`, as the sum of all `Proportion` up until that row is less than 0.75. | 2011/10/27 | [
"https://Stackoverflow.com/questions/7914579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/694652/"
] | ```
select top 1
t1.ItemNo
from
MyTable t1
where
((select sum(t2.Proportion) from MyTable t2 where t2.ItemNo <= t1.ItemNo) >= 0.35)
order by
t1.ItemNo
``` | A classic for a window function:
```
SELECT *
FROM (
SELECT ItemNo
,ItemCount
,sum(Proportion) OVER (ORDER BY ItemNo) AS running_sum
FROM tbl) y
WHERE running_sum > 0.35
LIMIT 1;
```
Works in **PostgreSQL**, among others.
Or, in **tSQL** notation (which you seem to use):
SELECT TOP 1 \*
FROM (
SELECT ItemNo
,ItemCount
,sum(Proportion) OVER (ORDER BY ItemNo) AS running\_sum
FROM tbl) y
WHERE running\_sum > 0.35;
Doesn't work in tSQL as commented below. |
16,716,474 | I'm using SonataAdminBundle and I'm triying to change the edit link of and entity by the show link.
I want to do this because I need the entity couldn't be modified but I want you can show the entity by clicking in the Identifier field of the list page.
I need to show the entity by clicking in the Identifier, and not using the show action buttom.
So I tried in the ClassAdmin:
```
protected function configureRoutes(RouteCollection $collection){
$collection->add('edit', $this->getRouterIdParameter().'/show');
}
```
Despite the url is generated with the show correctly, the Identifier in the list page redirect to the edit page. Really, wathever I change in the edit link doesn't take efect and always redirect to the edit page.
Thansk a lot! | 2013/05/23 | [
"https://Stackoverflow.com/questions/16716474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2132206/"
] | You can give the default action like this (in your admin classes):
```
protected function configureListFields(ListMapper $listMapper)
{
$listMapper
->addIdentifier('id', null, ['route' => ['name' => 'show']])
;
}
``` | Finally, it works by:
```
protected function configureRoutes(RouteCollection $collection){
$collection->remove('edit');
$collection->add('edit', $this->getRouterIdParameter().'/show');
}
```
I don't know why I have to remove the edit link first... but it works. |
4,151,589 | When I define a dictionary which use list as key
```
collections.defaultdict(list)
```
When I print it out, it shows itself is using tuple as key.
May I know why?
```
import collections
tuple_as_dict_key = collections.defaultdict(tuple)
tuple_as_dict_key['abc', 1, 2] = 999
tuple_as_dict_key['abc', 3, 4] = 999
tuple_as_dict_key['abc', 5, 6] = 888
# defaultdict(<type 'tuple'>, {('abc', 5, 6): 888, ('abc', 1, 2): 999, ('abc', 3, 4): 999})
print tuple_as_dict_key
list_as_dict_key = collections.defaultdict(list)
list_as_dict_key['abc', 1, 2] = 999
list_as_dict_key['abc', 3, 4] = 999
list_as_dict_key['abc', 5, 6] = 888
# defaultdict(<type 'list'>, {('abc', 5, 6): 888, ('abc', 1, 2): 999, ('abc', 3, 4): 999})
# Isn't it should be defaultdict(<type 'list'>, {['abc', 5, 6]: 888, ...
print list_as_dict_key
``` | 2010/11/11 | [
"https://Stackoverflow.com/questions/4151589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/72437/"
] | There's a nice article explaining the answer to why you can't use a list as key [here](http://wiki.python.org/moin/DictionaryKeys). | Dictionary keys can only be [immutable types](http://docs.python.org/tutorial/datastructures.html#tuples-and-sequences). Since a list is a mutable type it must be converted to an immutable type such as a tuple to be used as a dictionary key, and this conversion is being done automatically. |
4,151,589 | When I define a dictionary which use list as key
```
collections.defaultdict(list)
```
When I print it out, it shows itself is using tuple as key.
May I know why?
```
import collections
tuple_as_dict_key = collections.defaultdict(tuple)
tuple_as_dict_key['abc', 1, 2] = 999
tuple_as_dict_key['abc', 3, 4] = 999
tuple_as_dict_key['abc', 5, 6] = 888
# defaultdict(<type 'tuple'>, {('abc', 5, 6): 888, ('abc', 1, 2): 999, ('abc', 3, 4): 999})
print tuple_as_dict_key
list_as_dict_key = collections.defaultdict(list)
list_as_dict_key['abc', 1, 2] = 999
list_as_dict_key['abc', 3, 4] = 999
list_as_dict_key['abc', 5, 6] = 888
# defaultdict(<type 'list'>, {('abc', 5, 6): 888, ('abc', 1, 2): 999, ('abc', 3, 4): 999})
# Isn't it should be defaultdict(<type 'list'>, {['abc', 5, 6]: 888, ...
print list_as_dict_key
``` | 2010/11/11 | [
"https://Stackoverflow.com/questions/4151589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/72437/"
] | When you're adding values to your dictionary you're doing it the same way in both cases and they're treated as a tuple. What you're passing to the constructor is the default value for any keys that are not present. Your default value in this case happens to be of type "type", but that has absolutely nothing to do with how other keys are treated. | Dictionary keys can only be [immutable types](http://docs.python.org/tutorial/datastructures.html#tuples-and-sequences). Since a list is a mutable type it must be converted to an immutable type such as a tuple to be used as a dictionary key, and this conversion is being done automatically. |
4,151,589 | When I define a dictionary which use list as key
```
collections.defaultdict(list)
```
When I print it out, it shows itself is using tuple as key.
May I know why?
```
import collections
tuple_as_dict_key = collections.defaultdict(tuple)
tuple_as_dict_key['abc', 1, 2] = 999
tuple_as_dict_key['abc', 3, 4] = 999
tuple_as_dict_key['abc', 5, 6] = 888
# defaultdict(<type 'tuple'>, {('abc', 5, 6): 888, ('abc', 1, 2): 999, ('abc', 3, 4): 999})
print tuple_as_dict_key
list_as_dict_key = collections.defaultdict(list)
list_as_dict_key['abc', 1, 2] = 999
list_as_dict_key['abc', 3, 4] = 999
list_as_dict_key['abc', 5, 6] = 888
# defaultdict(<type 'list'>, {('abc', 5, 6): 888, ('abc', 1, 2): 999, ('abc', 3, 4): 999})
# Isn't it should be defaultdict(<type 'list'>, {['abc', 5, 6]: 888, ...
print list_as_dict_key
``` | 2010/11/11 | [
"https://Stackoverflow.com/questions/4151589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/72437/"
] | The parameter to `defaultdict` is not the type of the key, it is a function that creates default data. Your test cases don't exercise this because you're filling the dict with defined values and not using any defaults. If you were to try to get the value `list_as_dict_key['abc', 7, 8]` it would return an empty list, since that is what you defined as a default value and you never set the value at that index. | Dictionary keys can only be [immutable types](http://docs.python.org/tutorial/datastructures.html#tuples-and-sequences). Since a list is a mutable type it must be converted to an immutable type such as a tuple to be used as a dictionary key, and this conversion is being done automatically. |
4,151,589 | When I define a dictionary which use list as key
```
collections.defaultdict(list)
```
When I print it out, it shows itself is using tuple as key.
May I know why?
```
import collections
tuple_as_dict_key = collections.defaultdict(tuple)
tuple_as_dict_key['abc', 1, 2] = 999
tuple_as_dict_key['abc', 3, 4] = 999
tuple_as_dict_key['abc', 5, 6] = 888
# defaultdict(<type 'tuple'>, {('abc', 5, 6): 888, ('abc', 1, 2): 999, ('abc', 3, 4): 999})
print tuple_as_dict_key
list_as_dict_key = collections.defaultdict(list)
list_as_dict_key['abc', 1, 2] = 999
list_as_dict_key['abc', 3, 4] = 999
list_as_dict_key['abc', 5, 6] = 888
# defaultdict(<type 'list'>, {('abc', 5, 6): 888, ('abc', 1, 2): 999, ('abc', 3, 4): 999})
# Isn't it should be defaultdict(<type 'list'>, {['abc', 5, 6]: 888, ...
print list_as_dict_key
``` | 2010/11/11 | [
"https://Stackoverflow.com/questions/4151589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/72437/"
] | There's a nice article explaining the answer to why you can't use a list as key [here](http://wiki.python.org/moin/DictionaryKeys). | `defaultdict` is **not** setting the *key* as a list. It's setting the default *value*.
```
>>> from collections import defaultdict
>>> d1 = collections.defaultdict(list)
>>> d1['foo']
[]
>>> d1['foo'] = 37
>>> d1['foo']
37
>>> d1['bar']
[]
>>> d1['bar'].append(37)
>>> d1['bar']
[37]
```
The way that you're getting a tuple as the key type is normal dict behaviour:
```
>>> d2 = dict()
>>> d2[37, 19, 2] = [14, 19]
>>> d2
{(37, 19, 2): [14, 19]}
```
The way Python works with subscripting is that `a` is `a`, `a, b` is a tuple, `a:b` is a slice object. See how it works with a list:
```
>>> mylist = [1, 2, 3]
>>> mylist[4, 5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not tuple
```
It's taken `4, 5` as a tuple. The dict has done the same. |
4,151,589 | When I define a dictionary which use list as key
```
collections.defaultdict(list)
```
When I print it out, it shows itself is using tuple as key.
May I know why?
```
import collections
tuple_as_dict_key = collections.defaultdict(tuple)
tuple_as_dict_key['abc', 1, 2] = 999
tuple_as_dict_key['abc', 3, 4] = 999
tuple_as_dict_key['abc', 5, 6] = 888
# defaultdict(<type 'tuple'>, {('abc', 5, 6): 888, ('abc', 1, 2): 999, ('abc', 3, 4): 999})
print tuple_as_dict_key
list_as_dict_key = collections.defaultdict(list)
list_as_dict_key['abc', 1, 2] = 999
list_as_dict_key['abc', 3, 4] = 999
list_as_dict_key['abc', 5, 6] = 888
# defaultdict(<type 'list'>, {('abc', 5, 6): 888, ('abc', 1, 2): 999, ('abc', 3, 4): 999})
# Isn't it should be defaultdict(<type 'list'>, {['abc', 5, 6]: 888, ...
print list_as_dict_key
``` | 2010/11/11 | [
"https://Stackoverflow.com/questions/4151589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/72437/"
] | The parameter to `defaultdict` is not the type of the key, it is a function that creates default data. Your test cases don't exercise this because you're filling the dict with defined values and not using any defaults. If you were to try to get the value `list_as_dict_key['abc', 7, 8]` it would return an empty list, since that is what you defined as a default value and you never set the value at that index. | There's a nice article explaining the answer to why you can't use a list as key [here](http://wiki.python.org/moin/DictionaryKeys). |
4,151,589 | When I define a dictionary which use list as key
```
collections.defaultdict(list)
```
When I print it out, it shows itself is using tuple as key.
May I know why?
```
import collections
tuple_as_dict_key = collections.defaultdict(tuple)
tuple_as_dict_key['abc', 1, 2] = 999
tuple_as_dict_key['abc', 3, 4] = 999
tuple_as_dict_key['abc', 5, 6] = 888
# defaultdict(<type 'tuple'>, {('abc', 5, 6): 888, ('abc', 1, 2): 999, ('abc', 3, 4): 999})
print tuple_as_dict_key
list_as_dict_key = collections.defaultdict(list)
list_as_dict_key['abc', 1, 2] = 999
list_as_dict_key['abc', 3, 4] = 999
list_as_dict_key['abc', 5, 6] = 888
# defaultdict(<type 'list'>, {('abc', 5, 6): 888, ('abc', 1, 2): 999, ('abc', 3, 4): 999})
# Isn't it should be defaultdict(<type 'list'>, {['abc', 5, 6]: 888, ...
print list_as_dict_key
``` | 2010/11/11 | [
"https://Stackoverflow.com/questions/4151589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/72437/"
] | When you're adding values to your dictionary you're doing it the same way in both cases and they're treated as a tuple. What you're passing to the constructor is the default value for any keys that are not present. Your default value in this case happens to be of type "type", but that has absolutely nothing to do with how other keys are treated. | `defaultdict` is **not** setting the *key* as a list. It's setting the default *value*.
```
>>> from collections import defaultdict
>>> d1 = collections.defaultdict(list)
>>> d1['foo']
[]
>>> d1['foo'] = 37
>>> d1['foo']
37
>>> d1['bar']
[]
>>> d1['bar'].append(37)
>>> d1['bar']
[37]
```
The way that you're getting a tuple as the key type is normal dict behaviour:
```
>>> d2 = dict()
>>> d2[37, 19, 2] = [14, 19]
>>> d2
{(37, 19, 2): [14, 19]}
```
The way Python works with subscripting is that `a` is `a`, `a, b` is a tuple, `a:b` is a slice object. See how it works with a list:
```
>>> mylist = [1, 2, 3]
>>> mylist[4, 5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not tuple
```
It's taken `4, 5` as a tuple. The dict has done the same. |
4,151,589 | When I define a dictionary which use list as key
```
collections.defaultdict(list)
```
When I print it out, it shows itself is using tuple as key.
May I know why?
```
import collections
tuple_as_dict_key = collections.defaultdict(tuple)
tuple_as_dict_key['abc', 1, 2] = 999
tuple_as_dict_key['abc', 3, 4] = 999
tuple_as_dict_key['abc', 5, 6] = 888
# defaultdict(<type 'tuple'>, {('abc', 5, 6): 888, ('abc', 1, 2): 999, ('abc', 3, 4): 999})
print tuple_as_dict_key
list_as_dict_key = collections.defaultdict(list)
list_as_dict_key['abc', 1, 2] = 999
list_as_dict_key['abc', 3, 4] = 999
list_as_dict_key['abc', 5, 6] = 888
# defaultdict(<type 'list'>, {('abc', 5, 6): 888, ('abc', 1, 2): 999, ('abc', 3, 4): 999})
# Isn't it should be defaultdict(<type 'list'>, {['abc', 5, 6]: 888, ...
print list_as_dict_key
``` | 2010/11/11 | [
"https://Stackoverflow.com/questions/4151589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/72437/"
] | The parameter to `defaultdict` is not the type of the key, it is a function that creates default data. Your test cases don't exercise this because you're filling the dict with defined values and not using any defaults. If you were to try to get the value `list_as_dict_key['abc', 7, 8]` it would return an empty list, since that is what you defined as a default value and you never set the value at that index. | When you're adding values to your dictionary you're doing it the same way in both cases and they're treated as a tuple. What you're passing to the constructor is the default value for any keys that are not present. Your default value in this case happens to be of type "type", but that has absolutely nothing to do with how other keys are treated. |
4,151,589 | When I define a dictionary which use list as key
```
collections.defaultdict(list)
```
When I print it out, it shows itself is using tuple as key.
May I know why?
```
import collections
tuple_as_dict_key = collections.defaultdict(tuple)
tuple_as_dict_key['abc', 1, 2] = 999
tuple_as_dict_key['abc', 3, 4] = 999
tuple_as_dict_key['abc', 5, 6] = 888
# defaultdict(<type 'tuple'>, {('abc', 5, 6): 888, ('abc', 1, 2): 999, ('abc', 3, 4): 999})
print tuple_as_dict_key
list_as_dict_key = collections.defaultdict(list)
list_as_dict_key['abc', 1, 2] = 999
list_as_dict_key['abc', 3, 4] = 999
list_as_dict_key['abc', 5, 6] = 888
# defaultdict(<type 'list'>, {('abc', 5, 6): 888, ('abc', 1, 2): 999, ('abc', 3, 4): 999})
# Isn't it should be defaultdict(<type 'list'>, {['abc', 5, 6]: 888, ...
print list_as_dict_key
``` | 2010/11/11 | [
"https://Stackoverflow.com/questions/4151589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/72437/"
] | The parameter to `defaultdict` is not the type of the key, it is a function that creates default data. Your test cases don't exercise this because you're filling the dict with defined values and not using any defaults. If you were to try to get the value `list_as_dict_key['abc', 7, 8]` it would return an empty list, since that is what you defined as a default value and you never set the value at that index. | `defaultdict` is **not** setting the *key* as a list. It's setting the default *value*.
```
>>> from collections import defaultdict
>>> d1 = collections.defaultdict(list)
>>> d1['foo']
[]
>>> d1['foo'] = 37
>>> d1['foo']
37
>>> d1['bar']
[]
>>> d1['bar'].append(37)
>>> d1['bar']
[37]
```
The way that you're getting a tuple as the key type is normal dict behaviour:
```
>>> d2 = dict()
>>> d2[37, 19, 2] = [14, 19]
>>> d2
{(37, 19, 2): [14, 19]}
```
The way Python works with subscripting is that `a` is `a`, `a, b` is a tuple, `a:b` is a slice object. See how it works with a list:
```
>>> mylist = [1, 2, 3]
>>> mylist[4, 5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not tuple
```
It's taken `4, 5` as a tuple. The dict has done the same. |
601,613 | What I am attempting to do is combine all of the files within a subdirectory into a new file, and give the new combined file the same name as the subdirectory, and I have no idea how to do this in Bash. Here's how I approached it: I have a number of directories, each with a unique file name (with spaces!). Within each of these directories, there are a number of numerically named files, like thus:
```
Home/Unique name/1.pdf
Home/Unique name/2.pdf
Home/Unique name/3.pdf
Home/Unique name/4.pdf
....
Home/Other Unique name/1.pdf
Home/Other Unique name/2.pdf
Home/Other Unique name/3.pdf
Home/Other Unique name/4.pdf
```
What I would like to do is write a bash script (from the `Home` directory) to:
1. Go into each unique directory, and perform a command on each of the files within that directory (in my case, copy them all to a different directory).
2. I have then written a different script `script.sh` that will perform another command (in this case, combine all the PDFs into a single file, `temp.pdf`). I would then like to rename that `temp.pdf` file after the directory `Unique name.pdf` (with spaces).
3. I will have to follow this process for a number of subdirectories.
I have attempted a solution with a number of for loops, while loops and using the find command, but I am not comfortable enough with bash to debug comfortably or use these variables with any degree of confidence. I am also certain that there is a more efficient way to do what I am doing, but I have bootstrapped the script together over a period of time. | 2013/05/30 | [
"https://superuser.com/questions/601613",
"https://superuser.com",
"https://superuser.com/users/227856/"
] | The POSIX way is to use `print . -type d ... | while read f; do`, but unless you're obsessed with 100% portability, I wouldn't bother with that. If you have bash 4+ and `pdfunite` (installed by default on my Ubuntu 13.04), you can do this in two lines:
```
shopt -s globstar
for f in ./**/; do pdfunite "$f"/*.pdf "$f"/"$(basename "$f").pdf"; done
```
Note that `shopt -s globstar` needs to be on a separate line to the rest of it. With globstar enabled, `**` expands to all files and directories in the current directory, recursively. Since files cannot contain `/` in their names, `**/` will expand to only the directories. I use `./**/` in the unlikely event that your directories begin with a hyphen (`-`), as this can cause problems, since many programs treat anything beginning with a `-` as an option.
As written, this will not copy the PDFs to another directory, but that's pretty trivial to add in:
```
for f in ./**/; do cp "$f"/*.pdf /target/dir/; pdfunite "$f"/*.pdf "$f"/"$(basename "$f").pdf"; done
```
If you want to use your own custom pdf-combining script, then simply change the line to suit - but remember that the essence of shell scripting is putting together pre-existing commands.
Here's a somewhat more portable version:
```
print . -type d -print0 | while read -d $'\0' f; do
pdfunite "$f"/*.pdf "$f"/"$(basename "$f").pdf"
done
``` | 1. Create `for` loop with `find /home/ -type f -name "*.pdf"` as a variable
2. Copy files to where you need them to, take $VARIABLE and process it through sed/awk to remove "/".
Post your script and we can help you to improve it.
You can always run scripts with `bash -x` to debug them or you can set `!#/bin/bash -x` to always execute in debug (verbose) mode. |
1,021,338 | Is there anyway by which we can read a value from an .xls file using nant scripts.The nant scripts should ask the input from the user and based on the inputs the nant.build should search the .xls file and when it sees the match,it should copy the corresponding mail ID and echo that mail ID to some other file and that echoed value should be placed in the mail section of the cruise control.NET .
Please get back to me for any more clarifications
Thanks
GNR | 2009/06/20 | [
"https://Stackoverflow.com/questions/1021338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You should write an NAnt extension. It is relatively easy to do.
See this tutorial [here](http://www.atalasoft.com/cs/blogs/jake/archive/2008/05/07/writing-custom-nant-tasks.aspx)
As an example project see my question [here](https://stackoverflow.com/questions/851203/nant-vault-windows-integrated-authentication) and [here](http://support.sourcegear.com/viewtopic.php?f=5&t=11663). | I'll re-phrase my answer :
"Is there anyway by which we can read a value from an .xls file using nant scripts"
If you are talking about using the 'core' NAnt functionality, which is that funcationality that is provided within the basic installation of NAnt, then I would say "No" or "Not very easily".
You can however extend NAnt using .NET libraries to perform whatever function you want, as long as you can code that function in a .NET language.
So, for you to solve your problems, the steps you need to under-take in my view are :
(a) Write a .NET library with methods that undertake the function(s) you describe
(b) Use the 'extensibility' of NAnt to turn your library in (a) into a custom task you can then call directly from your NAnt script
Obviously, you need to be able to break your problem down so that you can code it for part (a). Once you have done that, part (b) is reasonably trivial, and the tutorial I supplied in the link should easily walk you through this. |
38,560,437 | I'm making an android application that will inject touch events based on motions that I make. So far, I can use instrumentations to inject events but only within my application. I want to be able to use this service in other apps as well. I've read that this is possible with root but is there a way without it? Thank you! | 2016/07/25 | [
"https://Stackoverflow.com/questions/38560437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6633432/"
] | It is possible from a platform signed application/service to inject the keys/events to other applications. But I suppose the platform signatures change for different manufacturers !! | No, it isn't. And the reason for this is security. If you could do that, you could screw up or access all sorts of data in the other apps. They try to avoid that. |
18,237,519 | I am trying to print some Information to the Console in a Symfony Console Command. Regularly you would do something like this:
```
protected function execute(InputInterface $input, OutputInterface $output)
{
$name = $input->getArgument('name');
if ($name) {
$text = 'Hello '.$name;
} else {
$text = 'Hello';
}
if ($input->getOption('yell')) {
$text = strtoupper($text);
}
$output->writeln($text);
}
```
[For the full Code of the Example - Symfony Documentation](http://symfony.com/doc/current/components/console/introduction.html#creating-a-basic-command)
Unfortunately I can't access the `OutputInterface`. Is it possible to print a Message to the Console?
Unfortunately I can't pass the `OutputInterface` to the Class where I want to print some Output. | 2013/08/14 | [
"https://Stackoverflow.com/questions/18237519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1548788/"
] | Understanding the matter of ponctual debugging, you can always print debug messages with `echo` or `var_dump`
If you plan to use a command without Symfony's application with global debug messages, here's a way to do this.
Symfony offers 3 different `OutputInterface`s
* [NullOutput](http://api.symfony.com/2.3/Symfony/Component/Console/Output/NullOutput.html) - Will result in no output at all and keep the command quiet
* [ConsoleOutput](http://api.symfony.com/2.3/Symfony/Component/Console/Output/ConsoleOutput.html) - Will result in console messages
* [StreamOutput](http://api.symfony.com/2.3/Symfony/Component/Console/Output/StreamOutput.html) - Will result in printing messages into a given stream
Debugging to a file
-------------------
Doing such, whenever you call `$output->writeln()` in your command, it will write a new line in `/path/to/debug/file.log`
```
use Symfony\Component\Console\Output\StreamOutput;
use Symfony\Component\Console\Input\ArrayInput;
use Acme\FooBundle\Command\MyCommand;
$params = array();
$input = new ArrayInput($params);
$file = '/path/to/debug/file.log';
$handle = fopen($file, 'w+');
$output = new StreamOutput($handle);
$command = new MyCommand;
$command->run($input, $output);
fclose($handle);
```
Debugging in the console
------------------------
It is quietly the same process, except that you use `ConsoleOutput` instead
```
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Console\Input\ArrayInput;
use Acme\FooBundle\Command\MyCommand;
$params = array();
$input = new ArrayInput($params);
$output = new ConsoleOutput();
$command = new MyCommand;
$command->run($input, $output);
```
No debugging
------------
No message will be printed
```
use Symfony\Component\Console\Output\NullOutput;
use Symfony\Component\Console\Input\ArrayInput;
use Acme\FooBundle\Command\MyCommand;
$params = array();
$input = new ArrayInput($params);
$output = new NullOutput();
$command = new MyCommand;
$command->run($input, $output);
``` | Look at JMSAopBundle <https://github.com/schmittjoh/JMSAopBundle> and check out this great article <http://php-and-symfony.matthiasnoback.nl/2013/07/symfony2-rich-console-command-output-using-aop/> |
140 | I have rabbits that routinely build nests in my yard. How can I get rid of the rabbits legally? I don't want some officer from the DNR knocking on my door because I improperly hunted or poisoned them.
The rabbits cause several problems:
1. Our dog goes absolutely nuts barking at them through the window, chases them when she can in the back yard, and gently removes the young from their nest to play with (or tend to as a mother) when she finds a nest.
2. The nests are basically a hole in the ground about the size of a softball. They're easily big enough to cause a twisted ankle when stepped in while walking in the yard.
3. I'd like to start planting tomatoes and other vegetables, but I'm fearful the rabbits will have their way with my crops.
I've recently started using [Liquid Fence](http://www.liquidfence.com/), but it's hard to say if that's had much of an effect. I've certainly still had some rabbits, but maybe not as often.
What's the best course of action for me? | 2011/06/08 | [
"https://gardening.stackexchange.com/questions/140",
"https://gardening.stackexchange.com",
"https://gardening.stackexchange.com/users/105/"
] | I've heard of dried blood working well as a repellent for rabbits as well as deer. If you were to plant a vegetable garden you could sprinkle some of this around the plants as a sort of combination fertilizer/pest deterrent. | To try to get rid of nature, is like living in a bubble. Try to work with it and you'll probably be surprised. Last summer I was fortunate enough to flush out 4 baby rabbits before I ran over them with the lawn mower! I got them one by one and put them over in the woods-phew! I've seen a few in the back yard, but none bother my flower garden, mostly feed on certain weeds that are out there. Another deterrent is tabasco mixed with water, spray on or around the plants. As far as moles go, I've used a store bought repellent. They were so bad I had them in my flower beds. Eventually they've gone from the front yard towards the back. Stay diligent. |
140 | I have rabbits that routinely build nests in my yard. How can I get rid of the rabbits legally? I don't want some officer from the DNR knocking on my door because I improperly hunted or poisoned them.
The rabbits cause several problems:
1. Our dog goes absolutely nuts barking at them through the window, chases them when she can in the back yard, and gently removes the young from their nest to play with (or tend to as a mother) when she finds a nest.
2. The nests are basically a hole in the ground about the size of a softball. They're easily big enough to cause a twisted ankle when stepped in while walking in the yard.
3. I'd like to start planting tomatoes and other vegetables, but I'm fearful the rabbits will have their way with my crops.
I've recently started using [Liquid Fence](http://www.liquidfence.com/), but it's hard to say if that's had much of an effect. I've certainly still had some rabbits, but maybe not as often.
What's the best course of action for me? | 2011/06/08 | [
"https://gardening.stackexchange.com/questions/140",
"https://gardening.stackexchange.com",
"https://gardening.stackexchange.com/users/105/"
] | After just reading the title, I was going to suggest get a dog. Our dog has killed a couple rabbits already this year. Perhaps you could simply leave your dog in the yard more often, letting him/her out when she's barking at them through the window. I guess this depends if your dog is fast enough to catch them. You could consider getting another dog, perhaps a bigger, faster one.
Another note: when putting in vegetables, make sure you have a sure method of keeping your dog out of them. Our dog ate quite a few of our green beans last year (didn't bother the tomatoes, though), so we had to put up a higher fence this year. | Not to sound too glib, but we had rabbits and voles in our yard when we moved in 2.5 years ago. Then the foxes and owls came, and no more rabbits and voles. Maybe you can figure out some way to make that work for you. |
140 | I have rabbits that routinely build nests in my yard. How can I get rid of the rabbits legally? I don't want some officer from the DNR knocking on my door because I improperly hunted or poisoned them.
The rabbits cause several problems:
1. Our dog goes absolutely nuts barking at them through the window, chases them when she can in the back yard, and gently removes the young from their nest to play with (or tend to as a mother) when she finds a nest.
2. The nests are basically a hole in the ground about the size of a softball. They're easily big enough to cause a twisted ankle when stepped in while walking in the yard.
3. I'd like to start planting tomatoes and other vegetables, but I'm fearful the rabbits will have their way with my crops.
I've recently started using [Liquid Fence](http://www.liquidfence.com/), but it's hard to say if that's had much of an effect. I've certainly still had some rabbits, but maybe not as often.
What's the best course of action for me? | 2011/06/08 | [
"https://gardening.stackexchange.com/questions/140",
"https://gardening.stackexchange.com",
"https://gardening.stackexchange.com/users/105/"
] | Deer and rabbits both have a very keen sense of smell. I use a mixture of garlic powder, chili powder and water to keep the deer out of the garden. I am pretty sure that would work for rabbits as well. Spray it around where they are nesting and see if they move. If they do make up a large batch and spray the whole yard.
I spray once a week on average. If it rains I spray again as soon as it's dry. | After just reading the title, I was going to suggest get a dog. Our dog has killed a couple rabbits already this year. Perhaps you could simply leave your dog in the yard more often, letting him/her out when she's barking at them through the window. I guess this depends if your dog is fast enough to catch them. You could consider getting another dog, perhaps a bigger, faster one.
Another note: when putting in vegetables, make sure you have a sure method of keeping your dog out of them. Our dog ate quite a few of our green beans last year (didn't bother the tomatoes, though), so we had to put up a higher fence this year. |
140 | I have rabbits that routinely build nests in my yard. How can I get rid of the rabbits legally? I don't want some officer from the DNR knocking on my door because I improperly hunted or poisoned them.
The rabbits cause several problems:
1. Our dog goes absolutely nuts barking at them through the window, chases them when she can in the back yard, and gently removes the young from their nest to play with (or tend to as a mother) when she finds a nest.
2. The nests are basically a hole in the ground about the size of a softball. They're easily big enough to cause a twisted ankle when stepped in while walking in the yard.
3. I'd like to start planting tomatoes and other vegetables, but I'm fearful the rabbits will have their way with my crops.
I've recently started using [Liquid Fence](http://www.liquidfence.com/), but it's hard to say if that's had much of an effect. I've certainly still had some rabbits, but maybe not as often.
What's the best course of action for me? | 2011/06/08 | [
"https://gardening.stackexchange.com/questions/140",
"https://gardening.stackexchange.com",
"https://gardening.stackexchange.com/users/105/"
] | Every product I've tried hasn't worked for long. I finally put up chicken wire. That's the only thing that worked.
What didn't work - Don't waste your money.
An owl with light up eyes, moved every couple of days to a different spot.
Many different brands of rabbit repellant, including Liquid Fence.
Crushed up egg shells.
Plastic snakes. All different colors.
Spraying the bunnies with a garden hose - they come right back.
What did work - I had three places to fence in. Once I got the hang of it, a 20' by 15' bed took me around an hour to install. I used 24" tall cheap chicken wire. It was around $10.00 for a 50 foot roll. I bought 8-foot 2" x 1" lumber for $1.00 apiece. I had each one cut into four 2-foot pieces. I used plastic zip ties to attach the chicken wire to the stakes.
I spaced the stakes about 4 to 6 feet apart. On the first fence I buried the chicken wire a few inches. That worked. Then I tried bending the wire outward a few inches. That worked too. For the last bed I didn't bother burying it or bending it. That worked fine too. I thought they might chew through wood or the zip ties or burrow under the fences but they didn't.
Good luck! | To try to get rid of nature, is like living in a bubble. Try to work with it and you'll probably be surprised. Last summer I was fortunate enough to flush out 4 baby rabbits before I ran over them with the lawn mower! I got them one by one and put them over in the woods-phew! I've seen a few in the back yard, but none bother my flower garden, mostly feed on certain weeds that are out there. Another deterrent is tabasco mixed with water, spray on or around the plants. As far as moles go, I've used a store bought repellent. They were so bad I had them in my flower beds. Eventually they've gone from the front yard towards the back. Stay diligent. |
140 | I have rabbits that routinely build nests in my yard. How can I get rid of the rabbits legally? I don't want some officer from the DNR knocking on my door because I improperly hunted or poisoned them.
The rabbits cause several problems:
1. Our dog goes absolutely nuts barking at them through the window, chases them when she can in the back yard, and gently removes the young from their nest to play with (or tend to as a mother) when she finds a nest.
2. The nests are basically a hole in the ground about the size of a softball. They're easily big enough to cause a twisted ankle when stepped in while walking in the yard.
3. I'd like to start planting tomatoes and other vegetables, but I'm fearful the rabbits will have their way with my crops.
I've recently started using [Liquid Fence](http://www.liquidfence.com/), but it's hard to say if that's had much of an effect. I've certainly still had some rabbits, but maybe not as often.
What's the best course of action for me? | 2011/06/08 | [
"https://gardening.stackexchange.com/questions/140",
"https://gardening.stackexchange.com",
"https://gardening.stackexchange.com/users/105/"
] | I've heard of dried blood working well as a repellent for rabbits as well as deer. If you were to plant a vegetable garden you could sprinkle some of this around the plants as a sort of combination fertilizer/pest deterrent. | Not to sound too glib, but we had rabbits and voles in our yard when we moved in 2.5 years ago. Then the foxes and owls came, and no more rabbits and voles. Maybe you can figure out some way to make that work for you. |
140 | I have rabbits that routinely build nests in my yard. How can I get rid of the rabbits legally? I don't want some officer from the DNR knocking on my door because I improperly hunted or poisoned them.
The rabbits cause several problems:
1. Our dog goes absolutely nuts barking at them through the window, chases them when she can in the back yard, and gently removes the young from their nest to play with (or tend to as a mother) when she finds a nest.
2. The nests are basically a hole in the ground about the size of a softball. They're easily big enough to cause a twisted ankle when stepped in while walking in the yard.
3. I'd like to start planting tomatoes and other vegetables, but I'm fearful the rabbits will have their way with my crops.
I've recently started using [Liquid Fence](http://www.liquidfence.com/), but it's hard to say if that's had much of an effect. I've certainly still had some rabbits, but maybe not as often.
What's the best course of action for me? | 2011/06/08 | [
"https://gardening.stackexchange.com/questions/140",
"https://gardening.stackexchange.com",
"https://gardening.stackexchange.com/users/105/"
] | After just reading the title, I was going to suggest get a dog. Our dog has killed a couple rabbits already this year. Perhaps you could simply leave your dog in the yard more often, letting him/her out when she's barking at them through the window. I guess this depends if your dog is fast enough to catch them. You could consider getting another dog, perhaps a bigger, faster one.
Another note: when putting in vegetables, make sure you have a sure method of keeping your dog out of them. Our dog ate quite a few of our green beans last year (didn't bother the tomatoes, though), so we had to put up a higher fence this year. | Truly, having dogs around gets rid of rabbits, feral cats, deer, bobcat, fishers, voles, moles...etc. You don't have to allow the dogs to kill them. Helloooo! Rabies and all kinds of disease could be transferred. It takes a few months but works just fine! I have all of the above and more. That and freezing temperatures at night any night of the year. I just went with a greenhouse and solves most of those problems.
I've shot one animal one time at 100 yards with a 22, it was a rabbit. It screamed! I'll never forget it. Made myself eat the poor thing. I have no problem with hunting and killing done correctly and humanely. I love my meat-sigh-but it'll be vegetarianism for me until I get hungry enough to kill. Lots of meat around here!
This area is full of squirrels (I love them!!), rabbits, rodents, feral cats not to mention lots of coyote, bobcat and cougar. I've two dogs I don't allow freedom to roam. My cats forever and always will be indoor cats. Yup, I have to exercise to exercise my dogs. Oh well! I've got two horses as well and I have to exercise them or be a heartless, self-centered and overweight person. This is my first garden here and it is a tough place. The greenhouses solved 90% of these problems. Having dogs, just having them here, pooping, peeing and occasionally barking has scared away most of these animals.
The point is, if you kill one, there are thousands waiting in line to fill in the niche. They do belong and it is up to us to figure out how to live together. That is why we have this so-called intelligence we think makes us so special. Killing should only be done for food. Period. Period!! I've made it happen and most of my life I've been a single parent with all of the responsibilities and work. It is not tough. Killing and pesticides are a last, last resort. They only make more trouble.
Think of it this way; you are training your environment (including your animals, varmints) to live in harmony with you. You start killing them and then you have to teach the new guys the 'rules' all over again. You allow your dogs to start killing and the next thing you know is they'll kill your neighbor's cats, little yappy dogs or bite kids. You don't need that heartache nor the expense!
Relax! If you are going to be a gardener then you should know you can't control anything!!! Orchestrating harmony is vastly superior, humility and education is a must! We are not more important nor more special than any other form of life. Asking questions on this site, studying, researching, going to school are the best ways to show we humans have something going for us. Kudos to you!! |
140 | I have rabbits that routinely build nests in my yard. How can I get rid of the rabbits legally? I don't want some officer from the DNR knocking on my door because I improperly hunted or poisoned them.
The rabbits cause several problems:
1. Our dog goes absolutely nuts barking at them through the window, chases them when she can in the back yard, and gently removes the young from their nest to play with (or tend to as a mother) when she finds a nest.
2. The nests are basically a hole in the ground about the size of a softball. They're easily big enough to cause a twisted ankle when stepped in while walking in the yard.
3. I'd like to start planting tomatoes and other vegetables, but I'm fearful the rabbits will have their way with my crops.
I've recently started using [Liquid Fence](http://www.liquidfence.com/), but it's hard to say if that's had much of an effect. I've certainly still had some rabbits, but maybe not as often.
What's the best course of action for me? | 2011/06/08 | [
"https://gardening.stackexchange.com/questions/140",
"https://gardening.stackexchange.com",
"https://gardening.stackexchange.com/users/105/"
] | Truly, having dogs around gets rid of rabbits, feral cats, deer, bobcat, fishers, voles, moles...etc. You don't have to allow the dogs to kill them. Helloooo! Rabies and all kinds of disease could be transferred. It takes a few months but works just fine! I have all of the above and more. That and freezing temperatures at night any night of the year. I just went with a greenhouse and solves most of those problems.
I've shot one animal one time at 100 yards with a 22, it was a rabbit. It screamed! I'll never forget it. Made myself eat the poor thing. I have no problem with hunting and killing done correctly and humanely. I love my meat-sigh-but it'll be vegetarianism for me until I get hungry enough to kill. Lots of meat around here!
This area is full of squirrels (I love them!!), rabbits, rodents, feral cats not to mention lots of coyote, bobcat and cougar. I've two dogs I don't allow freedom to roam. My cats forever and always will be indoor cats. Yup, I have to exercise to exercise my dogs. Oh well! I've got two horses as well and I have to exercise them or be a heartless, self-centered and overweight person. This is my first garden here and it is a tough place. The greenhouses solved 90% of these problems. Having dogs, just having them here, pooping, peeing and occasionally barking has scared away most of these animals.
The point is, if you kill one, there are thousands waiting in line to fill in the niche. They do belong and it is up to us to figure out how to live together. That is why we have this so-called intelligence we think makes us so special. Killing should only be done for food. Period. Period!! I've made it happen and most of my life I've been a single parent with all of the responsibilities and work. It is not tough. Killing and pesticides are a last, last resort. They only make more trouble.
Think of it this way; you are training your environment (including your animals, varmints) to live in harmony with you. You start killing them and then you have to teach the new guys the 'rules' all over again. You allow your dogs to start killing and the next thing you know is they'll kill your neighbor's cats, little yappy dogs or bite kids. You don't need that heartache nor the expense!
Relax! If you are going to be a gardener then you should know you can't control anything!!! Orchestrating harmony is vastly superior, humility and education is a must! We are not more important nor more special than any other form of life. Asking questions on this site, studying, researching, going to school are the best ways to show we humans have something going for us. Kudos to you!! | To try to get rid of nature, is like living in a bubble. Try to work with it and you'll probably be surprised. Last summer I was fortunate enough to flush out 4 baby rabbits before I ran over them with the lawn mower! I got them one by one and put them over in the woods-phew! I've seen a few in the back yard, but none bother my flower garden, mostly feed on certain weeds that are out there. Another deterrent is tabasco mixed with water, spray on or around the plants. As far as moles go, I've used a store bought repellent. They were so bad I had them in my flower beds. Eventually they've gone from the front yard towards the back. Stay diligent. |
140 | I have rabbits that routinely build nests in my yard. How can I get rid of the rabbits legally? I don't want some officer from the DNR knocking on my door because I improperly hunted or poisoned them.
The rabbits cause several problems:
1. Our dog goes absolutely nuts barking at them through the window, chases them when she can in the back yard, and gently removes the young from their nest to play with (or tend to as a mother) when she finds a nest.
2. The nests are basically a hole in the ground about the size of a softball. They're easily big enough to cause a twisted ankle when stepped in while walking in the yard.
3. I'd like to start planting tomatoes and other vegetables, but I'm fearful the rabbits will have their way with my crops.
I've recently started using [Liquid Fence](http://www.liquidfence.com/), but it's hard to say if that's had much of an effect. I've certainly still had some rabbits, but maybe not as often.
What's the best course of action for me? | 2011/06/08 | [
"https://gardening.stackexchange.com/questions/140",
"https://gardening.stackexchange.com",
"https://gardening.stackexchange.com/users/105/"
] | I've heard of dried blood working well as a repellent for rabbits as well as deer. If you were to plant a vegetable garden you could sprinkle some of this around the plants as a sort of combination fertilizer/pest deterrent. | Truly, having dogs around gets rid of rabbits, feral cats, deer, bobcat, fishers, voles, moles...etc. You don't have to allow the dogs to kill them. Helloooo! Rabies and all kinds of disease could be transferred. It takes a few months but works just fine! I have all of the above and more. That and freezing temperatures at night any night of the year. I just went with a greenhouse and solves most of those problems.
I've shot one animal one time at 100 yards with a 22, it was a rabbit. It screamed! I'll never forget it. Made myself eat the poor thing. I have no problem with hunting and killing done correctly and humanely. I love my meat-sigh-but it'll be vegetarianism for me until I get hungry enough to kill. Lots of meat around here!
This area is full of squirrels (I love them!!), rabbits, rodents, feral cats not to mention lots of coyote, bobcat and cougar. I've two dogs I don't allow freedom to roam. My cats forever and always will be indoor cats. Yup, I have to exercise to exercise my dogs. Oh well! I've got two horses as well and I have to exercise them or be a heartless, self-centered and overweight person. This is my first garden here and it is a tough place. The greenhouses solved 90% of these problems. Having dogs, just having them here, pooping, peeing and occasionally barking has scared away most of these animals.
The point is, if you kill one, there are thousands waiting in line to fill in the niche. They do belong and it is up to us to figure out how to live together. That is why we have this so-called intelligence we think makes us so special. Killing should only be done for food. Period. Period!! I've made it happen and most of my life I've been a single parent with all of the responsibilities and work. It is not tough. Killing and pesticides are a last, last resort. They only make more trouble.
Think of it this way; you are training your environment (including your animals, varmints) to live in harmony with you. You start killing them and then you have to teach the new guys the 'rules' all over again. You allow your dogs to start killing and the next thing you know is they'll kill your neighbor's cats, little yappy dogs or bite kids. You don't need that heartache nor the expense!
Relax! If you are going to be a gardener then you should know you can't control anything!!! Orchestrating harmony is vastly superior, humility and education is a must! We are not more important nor more special than any other form of life. Asking questions on this site, studying, researching, going to school are the best ways to show we humans have something going for us. Kudos to you!! |