qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
3,815,606 | The plane $/4+/4+/7=1$ intersects the $-$ , $ -$ , and $-$ axes in points $, , $. Find the area of the triangle $Δ$.
So here's my attempt.
First I find the normal vector:
$\left\langle\frac{1}{4}+\frac{1}{4}+\frac{1}{7}\right\rangle$
And then I find its magnitude:
$\frac{\sqrt{57}}{14\sqrt{2}}$
And then I take a half to it because 1/2 base times height for triangle area.
But this isn't right. What am I doing wrong? Thank you in advance. | 2020/09/05 | [
"https://math.stackexchange.com/questions/3815606",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/752703/"
] | The points $P,Q,R$ are easily seen to be $P=(4,0,0),Q=(0,4,0),R=(0,0,7)$. By the symmetry in the $x-$ and $y-$coordinates, this is an isosceles triangle with base $PQ$ and height $TR$, where $T$ is the mid-point of $PQ$. Can you take it from there? | Let $O$ be an origin.
Thus, $OP=OQ=4,$ $OR=7,$ $PR=RQ=\sqrt{65},$ $PQ=\sqrt{32}$ and
$$S\_{\Delta PQR}=\frac{1}{4}\sqrt{2(65^2+65\cdot32+65\cdot32)-65^2-32^2-65^2}=\sqrt{456}.$$ |
3,815,606 | The plane $/4+/4+/7=1$ intersects the $-$ , $ -$ , and $-$ axes in points $, , $. Find the area of the triangle $Δ$.
So here's my attempt.
First I find the normal vector:
$\left\langle\frac{1}{4}+\frac{1}{4}+\frac{1}{7}\right\rangle$
And then I find its magnitude:
$\frac{\sqrt{57}}{14\sqrt{2}}$
And then I take a half to it because 1/2 base times height for triangle area.
But this isn't right. What am I doing wrong? Thank you in advance. | 2020/09/05 | [
"https://math.stackexchange.com/questions/3815606",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/752703/"
] | The points $P,Q,R$ are easily seen to be $P=(4,0,0),Q=(0,4,0),R=(0,0,7)$. By the symmetry in the $x-$ and $y-$coordinates, this is an isosceles triangle with base $PQ$ and height $TR$, where $T$ is the mid-point of $PQ$. Can you take it from there? | Intercepts on the axes are $(4,4,7)$.
The sides are $ 4\sqrt2, \sqrt{65},\sqrt {65}...$ because they are perpendicular. Pythagoras thm can be used.
Use formula $\sqrt{s(s-a)(s-b)(s-c)}$ |
3,815,606 | The plane $/4+/4+/7=1$ intersects the $-$ , $ -$ , and $-$ axes in points $, , $. Find the area of the triangle $Δ$.
So here's my attempt.
First I find the normal vector:
$\left\langle\frac{1}{4}+\frac{1}{4}+\frac{1}{7}\right\rangle$
And then I find its magnitude:
$\frac{\sqrt{57}}{14\sqrt{2}}$
And then I take a half to it because 1/2 base times height for triangle area.
But this isn't right. What am I doing wrong? Thank you in advance. | 2020/09/05 | [
"https://math.stackexchange.com/questions/3815606",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/752703/"
] | Points of intersection are
$$P=(4,0,0)\quad Q=(0,4,0)\quad R=(0,0,7)\quad$$
then we can find the base and hight and then the area.
Otherwise we can use [cross product](https://en.wikipedia.org/wiki/Triangle#Using_vectors)
$$S=\frac12 \left|\vec{RP}\times \vec{RQ}\right|$$ | Let $O$ be an origin.
Thus, $OP=OQ=4,$ $OR=7,$ $PR=RQ=\sqrt{65},$ $PQ=\sqrt{32}$ and
$$S\_{\Delta PQR}=\frac{1}{4}\sqrt{2(65^2+65\cdot32+65\cdot32)-65^2-32^2-65^2}=\sqrt{456}.$$ |
3,815,606 | The plane $/4+/4+/7=1$ intersects the $-$ , $ -$ , and $-$ axes in points $, , $. Find the area of the triangle $Δ$.
So here's my attempt.
First I find the normal vector:
$\left\langle\frac{1}{4}+\frac{1}{4}+\frac{1}{7}\right\rangle$
And then I find its magnitude:
$\frac{\sqrt{57}}{14\sqrt{2}}$
And then I take a half to it because 1/2 base times height for triangle area.
But this isn't right. What am I doing wrong? Thank you in advance. | 2020/09/05 | [
"https://math.stackexchange.com/questions/3815606",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/752703/"
] | Points of intersection are
$$P=(4,0,0)\quad Q=(0,4,0)\quad R=(0,0,7)\quad$$
then we can find the base and hight and then the area.
Otherwise we can use [cross product](https://en.wikipedia.org/wiki/Triangle#Using_vectors)
$$S=\frac12 \left|\vec{RP}\times \vec{RQ}\right|$$ | Intercepts on the axes are $(4,4,7)$.
The sides are $ 4\sqrt2, \sqrt{65},\sqrt {65}...$ because they are perpendicular. Pythagoras thm can be used.
Use formula $\sqrt{s(s-a)(s-b)(s-c)}$ |
18,135,119 | I need sort functions [function1(), function2(), function3()] in order of the values in array $numbers ($numbers[0], $numbers[1], $numbers[2]).
I only successfully sorted values $n1, $n2, $n3. But now I do not know how to sort functions below according these sorted values in array.
In this cause it means that first will be function3() next function1() and last function2(). And when I change values ($n1, $n2, $n3), order of functions will be automatically corrected.
```
$n1 = 50000;
$n2 = 100000;
$n3 = 25000;
$numbers = array($n1, $n2, $n3);
sort($numbers);
function function1() {
global $n1;
echo 'STANDARD';
echo '35 mil';
echo number_format($n1, 0, '', ' ');
}
function function2() {
global $n2;
echo 'STANDARD PLUS';
echo '70 mil';
echo number_format($n2, 0, '', ' ');
}
function function3() {
global $n3;
echo 'STANDARD PLUS';
echo '35 mil';
echo number_format($n3, 0, '', ' ');
}
```
Thanks in advance (Sorry - I am very beginner in programming) | 2013/08/08 | [
"https://Stackoverflow.com/questions/18135119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2166133/"
] | How to change the order of the functions...
-------------------------------------------
I'll answer the question in the topic first, because that's what I've been asked to do.
```
// First, create an array with the three values mapping to the three functions
$numbers = array(
50000 => 'function1',
25000 => 'function2',
100000 => 'function3'
);
ksort($numbers);
// Next, define the functions
function function1($number) {
echo "STANDARD<br>";
echo "35 mil<br>";
echo number_format($number, 0, '', ' ') . "<br>";
}
function function2($number) {
echo "STANDARD PLUS<br>";
echo "70 mil<br>";
echo number_format($number, 0, '', ' ') . "<br>";
}
function function3($number) {
echo "STANDARD PLUS<br>";
echo "35 mil<br>";
echo number_format($number, 0, '', ' ') . "<br>";
}
// Finally, let's call the functions in order
foreach($numbers as $value => $function) {
$function($value);
}
```
([Demo](https://eval.in/41768))
However, we can make this MUCH simpler...
-----------------------------------------
Since these functions all basically follow the same pattern, they should really be one function, within the `foreach` loop structure. Therefore, I'd do this:
```
// Set up variable parameters within the array
$numbers = array(
50000 => array(
'tier' => 'STANDARD',
'mil' => '35 mil'
),
25000 => array(
'tier' => 'STANDARD PLUS',
'mil' => '70 mil'
),
100000 => array(
'tier' => 'STANDARD PLUS',
'mil' => '35 mil'
)
);
// Sort the array
ksort($numbers);
// Now, run the logic
foreach($numbers as $number => $details) {
echo $details['tier'] . "<br>";
echo $details['mil'] . "<br>";
echo number_format($number, 0, '', ' ') . "<br>";
}
```
([Demo](https://eval.in/41770))
As you can see, it's a lot shorter and doesn't require expensive function calls. | What do you mean by "sorting functions"? Do you want to change the order in which the functions are called?
I see that you are not calling your functions from anywhere in your code. So, what do you intend to do in the first place? |
61,558,488 | I used tkinter to create a button and assigned a function to it using `command` parameter. But this function contains some code takes time to execute. I have simulated it here using `time.sleep()`. I want to remove this button when this button is clicked. For this I called the global variable for button inside the function and then used `pack_forget()`.
```
from tkinter import *
import time
def signIn():
global login_button
login_button.pack_forget()
# code after this takes some time to run.
time.sleep(10)
login_screen = Tk()
login_button = Button(login_screen, text="Login", width=10, height=1, command=signIn)
login_button.pack()
login_screen.mainloop()
```
But the problem is that button gets removed only after the function execution is complete (i.e after 10 seconds). Is there any way I can get the button removed as soon as the `pack_forget()` line gets executed and not wait for the full function to complete execution? | 2020/05/02 | [
"https://Stackoverflow.com/questions/61558488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5360375/"
] | Call [update\_idletasks](http://effbot.org/tkinterbook/widget.htm#Tkinter.Widget.update_idletasks-method) method of the *login\_screen* window after removing the button.
From *effbot*:
>
> **update\_idletasks()**
>
>
> Calls all pending idle tasks, without processing any other events. This can be used to carry out geometry management and redraw widgets if necessary, without calling any callbacks.
>
>
>
```
def signIn():
global login_button, login_screen
login_button.pack_forget()
login_screen.update_idletasks()
# code after this takes some time to run.
time.sleep(10)
``` | Using `update()` works:
```
def signIn():
global login_button, login_screen
login_button.pack_forget()
login_screen.update()
# code after this takes some time to run.
time.sleep(10)
``` |
61,558,488 | I used tkinter to create a button and assigned a function to it using `command` parameter. But this function contains some code takes time to execute. I have simulated it here using `time.sleep()`. I want to remove this button when this button is clicked. For this I called the global variable for button inside the function and then used `pack_forget()`.
```
from tkinter import *
import time
def signIn():
global login_button
login_button.pack_forget()
# code after this takes some time to run.
time.sleep(10)
login_screen = Tk()
login_button = Button(login_screen, text="Login", width=10, height=1, command=signIn)
login_button.pack()
login_screen.mainloop()
```
But the problem is that button gets removed only after the function execution is complete (i.e after 10 seconds). Is there any way I can get the button removed as soon as the `pack_forget()` line gets executed and not wait for the full function to complete execution? | 2020/05/02 | [
"https://Stackoverflow.com/questions/61558488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5360375/"
] | Call [update\_idletasks](http://effbot.org/tkinterbook/widget.htm#Tkinter.Widget.update_idletasks-method) method of the *login\_screen* window after removing the button.
From *effbot*:
>
> **update\_idletasks()**
>
>
> Calls all pending idle tasks, without processing any other events. This can be used to carry out geometry management and redraw widgets if necessary, without calling any callbacks.
>
>
>
```
def signIn():
global login_button, login_screen
login_button.pack_forget()
login_screen.update_idletasks()
# code after this takes some time to run.
time.sleep(10)
``` | This worked for me in that situation.
```
def launch_button(*args):
# button will show new text when this function is done. The second argument
# is the new text we're sending to the button
data_button_widget.configure(text=args[1])
# schedule launch of the next function, 1 ms after returning to mainloop -
# The first argument is the function to launch
data_button_widget.after(1, args[0])
def get_data(*args):
# button will reconfigure to original text when this function is done
data_button_widget.configure(text='Original button text')
<code that takes some time here>
# make a window
wndw = Tk()
# add a frame widget to the window
fram = ttk.Frame(wndw, padding=SM_PAD)
fram.grid(column=0, row=0)
wndw.columnconfigure(0, weight=1)
wndw.rowconfigure(0, weight=1)
# make a button widget
data_button_widget = ttk.Button(fram, command=lambda: launch_button(get_data, 'wait...'))
data_button_widget.grid(column=2, row=4, padx=SM_PAD, pady=LG_PAD)
data_button_widget.configure(text='Original button text')
# start mainloop
wndw.mainloop()
``` |
61,558,488 | I used tkinter to create a button and assigned a function to it using `command` parameter. But this function contains some code takes time to execute. I have simulated it here using `time.sleep()`. I want to remove this button when this button is clicked. For this I called the global variable for button inside the function and then used `pack_forget()`.
```
from tkinter import *
import time
def signIn():
global login_button
login_button.pack_forget()
# code after this takes some time to run.
time.sleep(10)
login_screen = Tk()
login_button = Button(login_screen, text="Login", width=10, height=1, command=signIn)
login_button.pack()
login_screen.mainloop()
```
But the problem is that button gets removed only after the function execution is complete (i.e after 10 seconds). Is there any way I can get the button removed as soon as the `pack_forget()` line gets executed and not wait for the full function to complete execution? | 2020/05/02 | [
"https://Stackoverflow.com/questions/61558488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5360375/"
] | This worked for me in that situation.
```
def launch_button(*args):
# button will show new text when this function is done. The second argument
# is the new text we're sending to the button
data_button_widget.configure(text=args[1])
# schedule launch of the next function, 1 ms after returning to mainloop -
# The first argument is the function to launch
data_button_widget.after(1, args[0])
def get_data(*args):
# button will reconfigure to original text when this function is done
data_button_widget.configure(text='Original button text')
<code that takes some time here>
# make a window
wndw = Tk()
# add a frame widget to the window
fram = ttk.Frame(wndw, padding=SM_PAD)
fram.grid(column=0, row=0)
wndw.columnconfigure(0, weight=1)
wndw.rowconfigure(0, weight=1)
# make a button widget
data_button_widget = ttk.Button(fram, command=lambda: launch_button(get_data, 'wait...'))
data_button_widget.grid(column=2, row=4, padx=SM_PAD, pady=LG_PAD)
data_button_widget.configure(text='Original button text')
# start mainloop
wndw.mainloop()
``` | Using `update()` works:
```
def signIn():
global login_button, login_screen
login_button.pack_forget()
login_screen.update()
# code after this takes some time to run.
time.sleep(10)
``` |
30,635,873 | Currently i have a span and a progress div as below-

But what I want is -

Current code is
```
<td>
<span>570</span> <br />
<div class="progress slim">
<div class="bar no-text" data-percentage="54"></div>
</div>
</td>
```
Removing `</br>` is not working.
>
> UPDATE: Adding `style="display:inline-block;"` to the progress div makes the div disappeared.
>
>
>
How can I place two contents in one line? | 2015/06/04 | [
"https://Stackoverflow.com/questions/30635873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/770135/"
] | Remove `<br />`
If you have additional styling, you can also use the **display: inline** css class.
See here:
<http://jsfiddle.net/cz7rh719/> | Remove `<br />` and add `display:inline-block` for your progress div.
```
div.progress{display:inline-block;}
```
[**DEMO**](http://jsfiddle.net/kkvz0yn9/) |
30,635,873 | Currently i have a span and a progress div as below-

But what I want is -

Current code is
```
<td>
<span>570</span> <br />
<div class="progress slim">
<div class="bar no-text" data-percentage="54"></div>
</div>
</td>
```
Removing `</br>` is not working.
>
> UPDATE: Adding `style="display:inline-block;"` to the progress div makes the div disappeared.
>
>
>
How can I place two contents in one line? | 2015/06/04 | [
"https://Stackoverflow.com/questions/30635873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/770135/"
] | \*\*Remove \*\*
```
<br />
```
\*\*and its inline style should be \*\*
```
style="display:inline-block;"
``` | Remove `<br />` and add `display:inline-block` for your progress div.
```
div.progress{display:inline-block;}
```
[**DEMO**](http://jsfiddle.net/kkvz0yn9/) |
21,670,405 | There seems to be a very important change in the way ACTION\_BOOT\_COMPLETED broadcast is sent out in the latest android release.
In JB 4.3, the boot complete broadcast was processed in parallel. Where as in KK 4.4.2 its being processed serially.
This is delaying the start of services after boot up.
[KITKAT 4.4.2](http://androidxref.com/4.4.2_r1/xref/frameworks/base/services/java/com/android/server/am/ActivityManagerService.java#5189)
[JELLY BEAN 4.3](http://androidxref.com/4.3_r2.1/xref/frameworks/base/services/java/com/android/server/am/ActivityManagerService.java#4512)
Because of this change by Google, my service start is being delayed after boot complete.
One can observe that the device gets sluggish and audio for touch doesn't play-out. All of these because the respective services are starting late.
Also, from the logs I see that the first guy to receive ACTION\_BOOT\_COMPLETED after its is sent out, is receiving it after 16-19 seconds, where as on JBP it hardly takes 10 milliseconds for the first guy in the receiver-queue to get it.
Could anyone who is aware of this change explain why this was made.
It would be a great help.
Thanks a lot! | 2014/02/10 | [
"https://Stackoverflow.com/questions/21670405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2172676/"
] | The change was made by @hackbod, perhaps she can shed light on the reason.
Her checkin note states:
>
> Finish issue #10779747: Calendar Storage crash observed...
>
>
> ...while setting up a new user from settings.
>
>
> We can now delay broadcasts when there are enough background services
> currently starting (still set to 1 for svelte devices, 3 for normal
> devices).
>
>
> Add new intent flag to not allow receivers to abort broadcasts, which
> I use to fix an issue with the initial BOOT\_COMPLETED broadcast not
> actually requesting pss data at the right time -- it can now be sent
> as an ordered broadcast without the ability for the receivers to cancel
> it.
>
>
>
[Checkin diff](http://androidxref.com/4.4.2_r1/diff/frameworks/base/services/java/com/android/server/am/ActivityManagerService.java?r2=%2Fframeworks%2Fbase%2Fservices%2Fjava%2Fcom%2Fandroid%2Fserver%2Fam%2FActivityManagerService.java%406285a32f74890b761579b4f67afde1b08763fd0a&r1=%2Fframeworks%2Fbase%2Fservices%2Fjava%2Fcom%2Fandroid%2Fserver%2Fam%2FActivityManagerService.java%40e56c2c3f059b24c968a3f28f701b6b6cf5883fd9) | Yeah,I meet this question now.
BOOT\_COMPLETED ordered = true,many services running delay for a long time.
If I remove all the GMS apps,it'll be OK.Because too many GMS apps register the BOOT\_COMPLETED broadcast.
```
public class BootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
```
It seems to be a bug. Beacuse if I write a demo app to receive the BOOT\_COMPLETED as above,the incorrect issue will reappear.
I've checked @hackbod's modification.I don't have any idea except for modifying ordered from true to false.
Waiting for @hackbod's reply! |
21,670,405 | There seems to be a very important change in the way ACTION\_BOOT\_COMPLETED broadcast is sent out in the latest android release.
In JB 4.3, the boot complete broadcast was processed in parallel. Where as in KK 4.4.2 its being processed serially.
This is delaying the start of services after boot up.
[KITKAT 4.4.2](http://androidxref.com/4.4.2_r1/xref/frameworks/base/services/java/com/android/server/am/ActivityManagerService.java#5189)
[JELLY BEAN 4.3](http://androidxref.com/4.3_r2.1/xref/frameworks/base/services/java/com/android/server/am/ActivityManagerService.java#4512)
Because of this change by Google, my service start is being delayed after boot complete.
One can observe that the device gets sluggish and audio for touch doesn't play-out. All of these because the respective services are starting late.
Also, from the logs I see that the first guy to receive ACTION\_BOOT\_COMPLETED after its is sent out, is receiving it after 16-19 seconds, where as on JBP it hardly takes 10 milliseconds for the first guy in the receiver-queue to get it.
Could anyone who is aware of this change explain why this was made.
It would be a great help.
Thanks a lot! | 2014/02/10 | [
"https://Stackoverflow.com/questions/21670405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2172676/"
] | You can try to modify the follow code
in frameworks\base\services\java\com\android\server\am\ActivityManagerService.java(line 1974 around):
```
private ActivityManagerService() {
......
mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT, true);
......
}
```
from:
```
mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT, true);
```
to:
```
mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT, false);
```
Another solution is just set the ACTION\_BOOT\_COMPLETED intent to be "FLAG\_RECEIVER\_NO\_ABORT" in finishBooting(),ActivityManagerService.java:
```
final void finishBooting() {
...
Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
intent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT);
//add FLAG_RECEIVER_FOREGROUND to force the intent in foreground
intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
......
}
``` | Yeah,I meet this question now.
BOOT\_COMPLETED ordered = true,many services running delay for a long time.
If I remove all the GMS apps,it'll be OK.Because too many GMS apps register the BOOT\_COMPLETED broadcast.
```
public class BootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
```
It seems to be a bug. Beacuse if I write a demo app to receive the BOOT\_COMPLETED as above,the incorrect issue will reappear.
I've checked @hackbod's modification.I don't have any idea except for modifying ordered from true to false.
Waiting for @hackbod's reply! |
3,752,272 | Why does the remark in [Wiki's proof of Warning's theorem](https://en.wikipedia.org/wiki/Chevalley%E2%80%93Warning_theorem#Proof_of_Warning%27s_theorem) true?
>
> If ${\displaystyle i<q-1}$ then ${\displaystyle \sum \_{x\in \mathbb {F} }x^{i}=0}$
>
>
>
Best regards | 2020/07/10 | [
"https://math.stackexchange.com/questions/3752272",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/735934/"
] | This a special case of something more general.
**Fact 1.** Suppose $F$ is a field, $G$ is a finite group, and $\varphi:G \to F^{\times}$ is a nontrivial group homomorphism. Then $\sum\_{x\in G}\varphi(x)=0$.
Here:
* $0$ is the additive identity of $F$,
* $F^{\times}$ is the multiplicative group $F\setminus \{0\}$
* $\varphi$ *nontrivial* means there is some $a\in G$ such that $\varphi(a)\neq 1$, where $1$ the multiplicative identity of $F$.
**Proof:** Let $S=\sum\_{x\in G}\varphi(x)$. Fix $a\in G$ such that $\varphi(a)\neq 1$. Then we have
$$
\varphi(a)S=\sum\_{x\in G}\varphi(a)\varphi(x)=\sum\_{x\in G}\varphi(ax)=S
$$
The last equality uses the fact that as $x$ ranges over $G$ so does $ax$ (with $a$ fixed). So we have $\varphi(a)S=S$, which means $S=0$ since $\varphi(a)\neq 1$. The proof is complete.
So you can apply this fact in your case to $G=\mathbb{F}^{\times}$. (We assume $q=|\mathbb{F}|$.) As noted by others, $x\mapsto x^i$ is a (nontrivial) homomorphism from $\mathbb{F}^{\times}$ to itself, and clearly adding $x=0$ to the sum does nothing.
The only subtle point is proving that $x\mapsto x^i$ is nontrivial. As others note, this follows from the fact that $\mathbb{F}^{\times}$ is cyclic, and so if $a$ is a generator then $a^i\neq 1$ for $i<q-1$. But you don't technically need this, you just need that if $i<q-1$ then there is some $a\in\mathbb{F}^{\times}$ such that $a^i\neq 1$. This follows from the fact that in any field, the polynomial $x^i-1$ has at most $i$ solutions. (Admittedly, that last fact is a big part of the usual proofs that $\mathbb{F}^{\times}$ is cyclic.) | The map $x \mapsto x^i$ is a group homomorphism $\mathbb{F}^{\times} \to \mathbb{F}^{\times}$.
If its image is a subgroup of $H$ order $d$, then the image is exactly the set of solutions of $x^d=1$ because $\mathbb{F}^{\times}$ is cyclic. Therefore, the sum of its elements is $0$ because there is no $x^{d-1}$ term in $x^d-1$. Finally, $$\sum \_{x\in \mathbb {F} }x^{i}=\sum \_{x\in \mathbb {F}^\times}x^{i}= m \sum \_{y \in H} y=0$$ because the preimage of every $y \in H$ has the same number of elements $m$, the order of the kernel. |
22,921 | I am designing a checkout workflow where the old IA has mocked up different screens for billing/shipping and payment.
I want to combine into one page like this (which I've abbreviated):

I've said there is an evidence base behind it but can't find anything conclusive either for same or different pages. There are more back end implications for the combo approach though, but these dont affect the UX
Q: can you direct me to evidence that looks at this exact scenario vs different pages for checkout.
bounty will be offered
Update:
I've blogged my thoughts based on your comments
<http://colmcqux.wordpress.com/single-vs-multi-step-checkout/>
tx for all your help! | 2012/06/27 | [
"https://ux.stackexchange.com/questions/22921",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/4701/"
] | It's not even studies or evidence. It's one of the main principles of good UX: the fewer the screens a person needs to see to accomplish a task the better the experience is and the least frustration s/he feels.
Fewer screens mean fewer steps, fewer opportunities to make a mistake, less time spent getting familiar with the content of the screen (even if it's milliseconds), HTTP requests & data transfer (in web context), and no need to remember info from another step (in this case particularly).
Here's a [study by Get Elastic](http://www.getelastic.com/single-vs-two-page-checkout/) that found single-page checkouts outperforming multi-page ones by 21.8% in 606 transactions. And here's [their discussion of the technical cons](http://www.getelastic.com/single-page-checkout/) of single-page checkouts.
At the same time, Baymard Institute [found that the main problem with multi-page](http://baymard.com/blog/one-page-checkout) checkouts is with the actual tasks of the each of the screens rather than with their number. | Here is my opinion which I have understand from question:
 |
22,921 | I am designing a checkout workflow where the old IA has mocked up different screens for billing/shipping and payment.
I want to combine into one page like this (which I've abbreviated):

I've said there is an evidence base behind it but can't find anything conclusive either for same or different pages. There are more back end implications for the combo approach though, but these dont affect the UX
Q: can you direct me to evidence that looks at this exact scenario vs different pages for checkout.
bounty will be offered
Update:
I've blogged my thoughts based on your comments
<http://colmcqux.wordpress.com/single-vs-multi-step-checkout/>
tx for all your help! | 2012/06/27 | [
"https://ux.stackexchange.com/questions/22921",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/4701/"
] | It's not even studies or evidence. It's one of the main principles of good UX: the fewer the screens a person needs to see to accomplish a task the better the experience is and the least frustration s/he feels.
Fewer screens mean fewer steps, fewer opportunities to make a mistake, less time spent getting familiar with the content of the screen (even if it's milliseconds), HTTP requests & data transfer (in web context), and no need to remember info from another step (in this case particularly).
Here's a [study by Get Elastic](http://www.getelastic.com/single-vs-two-page-checkout/) that found single-page checkouts outperforming multi-page ones by 21.8% in 606 transactions. And here's [their discussion of the technical cons](http://www.getelastic.com/single-page-checkout/) of single-page checkouts.
At the same time, Baymard Institute [found that the main problem with multi-page](http://baymard.com/blog/one-page-checkout) checkouts is with the actual tasks of the each of the screens rather than with their number. | There are some other considerations which take precedence to UX studies. Besides backend technicalities there's an issue of security/privacy and how repeat customer purchases are structured during the checkout. On security and privacy I merely mention the concept of minimal exposure and leave it at that. Successful checkout interfaces combine registering a first time purchase (or not) with reusability for repeat customer (registered) in a way that still allows the delivery fields (more prone to adjustment) to be changed at will without editing credit card details. At all times still keeping in mind to minimize security risk to credit card details being stolen.
These are serious considerations that are at least as important as any UX studies. UX studies of e-commerce are particularly difficult to re-construct accurately. It's one thing to spend x dollars of virtual money not from you wallet, a real purchase where you're knowingly exposing your credit card to fraud is another.
So just because it's possible to combine checkout screens, it might still not be a good idea to do so. UX studies should not take over as the dominant factor in e-commerce. |
72,459,839 | So i want my page to reload an amount of seconds after the button is clicked. Right now it reloads every 5 seconds automatically. But if i put the timeout function in the addEvenlistener then it errors. What can i do to solve it?
```
button.addEventListener(
'click',
() =>
(cover.style.visibility = 'hidden') && (button.style.visibility = 'hidden'),
);
setTimeout(function () {
window.location.reload();
}, 5000);
``` | 2022/06/01 | [
"https://Stackoverflow.com/questions/72459839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Weird, this should work. Are you sure you didn't forget the curly braces in the click callback?
```
button.addEventListener('click', () => {
cover.style.visibility = 'hidden';
button.style.visibility = 'hidden';
setTimeout(function () {
window.location.reload();
}, 5000);
});
``` | You just need to write it inside the EventListener as @Jonas mentioned. And also you can have that timeout value to be dynamic as well
```js
var timeoutValue = 5000
button.addEventListener('click', () => {
cover.style.visibility = 'hidden';
button.style.visibility = 'hidden';
setTimeout(function () {
window.location.reload();
}, timeoutValue);
});
``` |
37,751,511 | I am using SQL Server 2012. I guess what I am asking is should I continue on the path of researching the ability to create a SP (or UDF, but with #Temp tables probably involved, I was thinking SP) in order to have a reusable object to determine the median?
I hope this isn't too generic of a question, and is hosed, but I have spent some time researching the ability to determine a median value. Some possible hurdles include the need to pass in a string representation of the query that will return the data that I wish to perform the median on.
Anyone attempt this in the past? | 2016/06/10 | [
"https://Stackoverflow.com/questions/37751511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4118263/"
] | Here is a stored proc I use to generate some quick stats.
Simply pass a Source, Measure and/or Filter.
```
CREATE PROCEDURE [dbo].[prc-Dynamic-Stats](@Table varchar(150),@Fld varchar(50), @Filter varchar(500))
-- Syntax: Exec [dbo].[prc-Dynamic-Stats] '[Chinrus-Series].[dbo].[DS_Treasury_Rates]','TR_Y10','Year(TR_Date)>2001'
As
Begin
Set NoCount On;
Declare @SQL varchar(max) =
'
;with cteBase as (
Select RowNr=Row_Number() over (Order By ['+@Fld+'])
,Measure = ['+@Fld+']
From '+@Table+'
Where '+case when @Filter='' then '1=1' else @Filter end+'
)
Select RecordCount = Count(*)
,DistinctCount = Count(Distinct A.Measure)
,SumTotal = Sum(A.Measure)
,Minimum = Min(A.Measure)
,Maximum = Max(A.Measure)
,Mean = Avg(A.Measure)
,Median = Max(B.Measure)
,Mode = Max(C.Measure)
,StdDev = STDEV(A.Measure)
From cteBase A
Join (Select Measure From cteBase where RowNr=(Select Cnt=count(*) from cteBase)/2) B on 1=1
Join (Select Top 1 Measure,Hits=count(*) From cteBase Group By Measure Order by 2 desc ) C on 1=1
'
Exec(@SQL)
End
```
Returns
```
RecordCount DistinctCount SumTotal Minimum Maximum Mean Median Mode StdDev
3615 391 12311.81 0.00 5.44 3.4057 3.57 4.38 1.06400795277565
``` | If using SQL Server 2008 or newer (which you are), you can write a function that accepts a `table-valued parameter` as input.
```
Create Type MedianData As Table ( DataPoint Int )
Create Function CalculateMedian ( @MedianData MedianData ReadOnly )
Returns Int
As
Begin
-- do something with @MedianData which is a table
End
``` |
37,751,511 | I am using SQL Server 2012. I guess what I am asking is should I continue on the path of researching the ability to create a SP (or UDF, but with #Temp tables probably involved, I was thinking SP) in order to have a reusable object to determine the median?
I hope this isn't too generic of a question, and is hosed, but I have spent some time researching the ability to determine a median value. Some possible hurdles include the need to pass in a string representation of the query that will return the data that I wish to perform the median on.
Anyone attempt this in the past? | 2016/06/10 | [
"https://Stackoverflow.com/questions/37751511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4118263/"
] | You may want to take a look at a response that I had to [this](https://stackoverflow.com/a/37753974/6448783) post. In short, if you're comfortable with C# or VB .NET, you could create a user defined CLR aggregate. We use CLR implementations for quite a few things, especially statistical methods that you may see in other platforms like SAS, R, etc. | If using SQL Server 2008 or newer (which you are), you can write a function that accepts a `table-valued parameter` as input.
```
Create Type MedianData As Table ( DataPoint Int )
Create Function CalculateMedian ( @MedianData MedianData ReadOnly )
Returns Int
As
Begin
-- do something with @MedianData which is a table
End
``` |
37,751,511 | I am using SQL Server 2012. I guess what I am asking is should I continue on the path of researching the ability to create a SP (or UDF, but with #Temp tables probably involved, I was thinking SP) in order to have a reusable object to determine the median?
I hope this isn't too generic of a question, and is hosed, but I have spent some time researching the ability to determine a median value. Some possible hurdles include the need to pass in a string representation of the query that will return the data that I wish to perform the median on.
Anyone attempt this in the past? | 2016/06/10 | [
"https://Stackoverflow.com/questions/37751511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4118263/"
] | This is easily accomplished by creating a User-Defined Aggregate (UDA) via SQLCLR. If you want to see how to do it, or even just download the UDA, check out the article I wrote about it on SQL Server Central: [Getting The Most Out of SQL Server 2005 UDTs and UDAs](http://www.sqlservercentral.com/articles/SQL+CLR/3208/) (please note that the site requires free registration in order to read their content).
Or, it is also available in the Free version of the SQL# SQLCLR library (which I created, but again, it is free) available at <http://SQLsharp.com/>. It is called **Agg\_Median**. | If using SQL Server 2008 or newer (which you are), you can write a function that accepts a `table-valued parameter` as input.
```
Create Type MedianData As Table ( DataPoint Int )
Create Function CalculateMedian ( @MedianData MedianData ReadOnly )
Returns Int
As
Begin
-- do something with @MedianData which is a table
End
``` |
37,751,511 | I am using SQL Server 2012. I guess what I am asking is should I continue on the path of researching the ability to create a SP (or UDF, but with #Temp tables probably involved, I was thinking SP) in order to have a reusable object to determine the median?
I hope this isn't too generic of a question, and is hosed, but I have spent some time researching the ability to determine a median value. Some possible hurdles include the need to pass in a string representation of the query that will return the data that I wish to perform the median on.
Anyone attempt this in the past? | 2016/06/10 | [
"https://Stackoverflow.com/questions/37751511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4118263/"
] | Here is a stored proc I use to generate some quick stats.
Simply pass a Source, Measure and/or Filter.
```
CREATE PROCEDURE [dbo].[prc-Dynamic-Stats](@Table varchar(150),@Fld varchar(50), @Filter varchar(500))
-- Syntax: Exec [dbo].[prc-Dynamic-Stats] '[Chinrus-Series].[dbo].[DS_Treasury_Rates]','TR_Y10','Year(TR_Date)>2001'
As
Begin
Set NoCount On;
Declare @SQL varchar(max) =
'
;with cteBase as (
Select RowNr=Row_Number() over (Order By ['+@Fld+'])
,Measure = ['+@Fld+']
From '+@Table+'
Where '+case when @Filter='' then '1=1' else @Filter end+'
)
Select RecordCount = Count(*)
,DistinctCount = Count(Distinct A.Measure)
,SumTotal = Sum(A.Measure)
,Minimum = Min(A.Measure)
,Maximum = Max(A.Measure)
,Mean = Avg(A.Measure)
,Median = Max(B.Measure)
,Mode = Max(C.Measure)
,StdDev = STDEV(A.Measure)
From cteBase A
Join (Select Measure From cteBase where RowNr=(Select Cnt=count(*) from cteBase)/2) B on 1=1
Join (Select Top 1 Measure,Hits=count(*) From cteBase Group By Measure Order by 2 desc ) C on 1=1
'
Exec(@SQL)
End
```
Returns
```
RecordCount DistinctCount SumTotal Minimum Maximum Mean Median Mode StdDev
3615 391 12311.81 0.00 5.44 3.4057 3.57 4.38 1.06400795277565
``` | You may want to take a look at a response that I had to [this](https://stackoverflow.com/a/37753974/6448783) post. In short, if you're comfortable with C# or VB .NET, you could create a user defined CLR aggregate. We use CLR implementations for quite a few things, especially statistical methods that you may see in other platforms like SAS, R, etc. |
37,751,511 | I am using SQL Server 2012. I guess what I am asking is should I continue on the path of researching the ability to create a SP (or UDF, but with #Temp tables probably involved, I was thinking SP) in order to have a reusable object to determine the median?
I hope this isn't too generic of a question, and is hosed, but I have spent some time researching the ability to determine a median value. Some possible hurdles include the need to pass in a string representation of the query that will return the data that I wish to perform the median on.
Anyone attempt this in the past? | 2016/06/10 | [
"https://Stackoverflow.com/questions/37751511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4118263/"
] | Here is a stored proc I use to generate some quick stats.
Simply pass a Source, Measure and/or Filter.
```
CREATE PROCEDURE [dbo].[prc-Dynamic-Stats](@Table varchar(150),@Fld varchar(50), @Filter varchar(500))
-- Syntax: Exec [dbo].[prc-Dynamic-Stats] '[Chinrus-Series].[dbo].[DS_Treasury_Rates]','TR_Y10','Year(TR_Date)>2001'
As
Begin
Set NoCount On;
Declare @SQL varchar(max) =
'
;with cteBase as (
Select RowNr=Row_Number() over (Order By ['+@Fld+'])
,Measure = ['+@Fld+']
From '+@Table+'
Where '+case when @Filter='' then '1=1' else @Filter end+'
)
Select RecordCount = Count(*)
,DistinctCount = Count(Distinct A.Measure)
,SumTotal = Sum(A.Measure)
,Minimum = Min(A.Measure)
,Maximum = Max(A.Measure)
,Mean = Avg(A.Measure)
,Median = Max(B.Measure)
,Mode = Max(C.Measure)
,StdDev = STDEV(A.Measure)
From cteBase A
Join (Select Measure From cteBase where RowNr=(Select Cnt=count(*) from cteBase)/2) B on 1=1
Join (Select Top 1 Measure,Hits=count(*) From cteBase Group By Measure Order by 2 desc ) C on 1=1
'
Exec(@SQL)
End
```
Returns
```
RecordCount DistinctCount SumTotal Minimum Maximum Mean Median Mode StdDev
3615 391 12311.81 0.00 5.44 3.4057 3.57 4.38 1.06400795277565
``` | This is easily accomplished by creating a User-Defined Aggregate (UDA) via SQLCLR. If you want to see how to do it, or even just download the UDA, check out the article I wrote about it on SQL Server Central: [Getting The Most Out of SQL Server 2005 UDTs and UDAs](http://www.sqlservercentral.com/articles/SQL+CLR/3208/) (please note that the site requires free registration in order to read their content).
Or, it is also available in the Free version of the SQL# SQLCLR library (which I created, but again, it is free) available at <http://SQLsharp.com/>. It is called **Agg\_Median**. |
59,448 | I'm confused by the famous wave-particle duality mystery:
When a particle is left unobserved, it acts like a wave and can explore all classically available particle trajectories simultaneously. By looking at it, you force it to decide on a single trajectory, like going through the left or right slit, or like Schrödinger's cat that ends up being either dead or alive; the wave-like characteristics are lost.
Are there theories that actually *explain* this behaviour? | 2013/03/30 | [
"https://physics.stackexchange.com/questions/59448",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/8091/"
] | The answer by JKL is sufficient but I want to address particularly the *Why?*.
>
> I am so confused. Why does it act the way it does?
>
>
>
If one reads a bit about the history of science and physics in particular, it becomes clear that physics at the ultimate end does not answer the ultimate *Why?*. Physics posits laws and uses sophisticated mathematical tools to theorize from "axioms", get equations, and check against the data experimentally. It finds *How*, from "axioms" one ends with predictions for measurements that validate them.
The *Why?* questions addressed to the "axioms" has the only answer: *Because* .
When one is validating a theory, as for example Newton's gravitational theory, and one hits a disagreement with the data, new "axioms" and new theoretical tools are developed to explain the *Why* of the disagreement and the new theory validated for the regime of disagreement. Special and General Relativity are an example. The history of physics has other examples : Thermodynamics, developed theoretically to explain bulk behavior, statistical mechanics, out of classical mechanics emerge out of asking *How* and assuming "axioms" to contain the *Why*. Each theory with its own regime of validity.
Within a theory a question with a *Why* is answered by proofs of *How* finally hitting on the "axioms". Quantum mechanics is the last in the series of exploring the microcosm. The *Why* you are asking hits against the *Because* of its "axioms".
There are people who continue the exploration, trying new axiomatic theories of how a quantum mechanical theory can emerge from a smaller regime where we are back to classical concepts, and contain the *Why* in "axioms" for their new theory. They are not successful except with small models. The bulk of theoretical physicists either ignores their efforts or proves that their new theories would violate a basic validated law as, for example, Lorentz invariance. And that is the story of *Why* in Physics. Ultimately the answer is *Because*.
Edit: "axioms" in quotation marks , to include mathematial axioms and physics postulates. Physical theories start from strict axiomatic mathematical theories where everything is contained and rigorously self consistent and add postulates in order to connect physical observables to the mathematical variables/functions. [Postulates](http://hyperphysics.phy-astr.gsu.edu/hbase/quantum/qm.html) are a necessary choice to turn a mathematical theory into a physics theory and in classical theories are referred as "laws". I call them "axioms" because they are the foundation stones of the theories, if one goes the whole theory goes. | You will probably find a satisfactory answer reading the experiment done by **Shahriar Afshar**, who claimes to have observed both, the wave and particle, properties of mater simultaneously. Here is the link,
<http://en.wikipedia.org/wiki/Afshar_experiment>
You will find more links therein, as well as criticism of the interpretation of his experiment. The best way to settle scientific "conflicts" is by experiment. Debates and arguments have conceptual limitations. |
59,448 | I'm confused by the famous wave-particle duality mystery:
When a particle is left unobserved, it acts like a wave and can explore all classically available particle trajectories simultaneously. By looking at it, you force it to decide on a single trajectory, like going through the left or right slit, or like Schrödinger's cat that ends up being either dead or alive; the wave-like characteristics are lost.
Are there theories that actually *explain* this behaviour? | 2013/03/30 | [
"https://physics.stackexchange.com/questions/59448",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/8091/"
] | This answer expands on the answer given by anna v
It is easy to become accustomed to a pattern of physics providing explanation after explanation.
For example, how is it that a gas has elastic properties under compression? If you compress it to half the volume, the pressure pretty much doubles. It's surprisingly similar to a spring, yet a gas isn't a spring, surely?
Physics offers a wonderful explanation: the molecules of the gas are moving fast, and collisions of molecules are perfectly elastic. The pressure of a gas against the walls of the vessel arises from elastic collisions of the molecules with the walls. If you half the volume the number of collisions pretty much doubles, hence the change of pressure.
What the physics did there: it moved the description of physics taking place to a deeper level. As it happens the physics on this deeper level (fast moving, elastically colliding molecules) is very readily visualized in things we know in the macroscopic world. We can readily visualize a population of bouncing balls.
In this particular case we are fortunate: the *description at a deeper level* consists of something that has a counterpart in physics we can see happening with our own eyes.
So yeah, it's natural to *hope* that a theory at quantum level can describe the physics taking place in terms of things we can visualize: particles, and waves. Well, in the case of quantum mechanics it turns out that what is expressed by the equations has no counterpart in the macroscopic world.
We make do with concepts we *can* visualize; particles and waves. In that sense the duality is introduced by the human thinking process; it's not inherent in the physics.
---
On more remark, again expanding on the anwser by anna v:
What is not in physics is *exhaustive explanation*.
When a new theory replaces an existing theory the description of the physics taking place moves to a deeper level.
When newtonian mechanics was established it looked for more than 300 years that no deeper level existed. Then, in the course of development of relativistic physics, theory of motion moved to a yet deeper level. So we learned not to expect that we are at the most fundamental level. A deeper level of description may be possible, we don't know.
Physics is not in the business of looking for exhaustive explanation. For the duration of working at a particular level of description (which can last hundreds of years) the assumptions necessary for that level of description are taken as given.
For comparison:
Newton *assumed* the existence of a gravitational force, acting over large distance, to explain the fact that the planets are orbiting the Sun. Newton's contemporaries were more demanding. For example, Descartes offered a hypothesis of vortices in space, with those vortices exerting an inward push on the planets. Descartes was determined to restrict himself to hypotheses with understandable elements only. He could visualize vortices, thus he ended up with vortices.
In retrospect we see that Descartes was just bogging himself down. Newton was more successfull because he operated on a need-to-assume basis.
Newton could not explain gravity itself, but he saw the strong explanatory strength it offered, and he moved ahead. | You will probably find a satisfactory answer reading the experiment done by **Shahriar Afshar**, who claimes to have observed both, the wave and particle, properties of mater simultaneously. Here is the link,
<http://en.wikipedia.org/wiki/Afshar_experiment>
You will find more links therein, as well as criticism of the interpretation of his experiment. The best way to settle scientific "conflicts" is by experiment. Debates and arguments have conceptual limitations. |
59,448 | I'm confused by the famous wave-particle duality mystery:
When a particle is left unobserved, it acts like a wave and can explore all classically available particle trajectories simultaneously. By looking at it, you force it to decide on a single trajectory, like going through the left or right slit, or like Schrödinger's cat that ends up being either dead or alive; the wave-like characteristics are lost.
Are there theories that actually *explain* this behaviour? | 2013/03/30 | [
"https://physics.stackexchange.com/questions/59448",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/8091/"
] | >
> Are there theories that explain wave-particle duality?
>
>
>
Yes, several actually, but they are interpretations rather than new theories.
As anna v explained in her reply, at its most fundamental level the only answer a physical theory can give to the question *Why?* is *Because!*.
It's impossible to give a more meaningful definite answer until we've taken another step down the rabbit hole (assuming we've not yet arrived at the bottom, of course).
However, you're not the only one uncomfortable with the situation, and that's where *interpretations* of our physical models come in, and there's a whole bunch of them for quantum mechanics.
As far as wave-particle duality goes, here are the explanations given by various interpretations:
* according to the [statistical interpretation](http://en.wikipedia.org/wiki/Ensemble_interpretation), quantum mechanis only describes ensembles and the question cannot be answered without an underlying new theory
* according to the [de Broglie-Bohm interpretation](http://en.wikipedia.org/wiki/De_Broglie%E2%80%93Bohm_theory), there are both particles and waves, the former being guided by the latter
* according to the [transactional interpretation](http://en.wikipedia.org/wiki/Transactional_interpretation), we have waves going forwards and backwards in time, resulting in particle-like interactions by interference
* according to the [many worlds interpretation](http://en.wikipedia.org/wiki/Many-worlds_interpretation), we have particles going all possible ways in different worlds
* according to the [consistent histories interpretation](http://en.wikipedia.org/wiki/Consistent_histories) (on which I should probably read up some more, so take this with a grain of salt), the particle or wave-like characteristics are just artifacts of a particular choice of history, which gain reality be decoherence
The [Copenhagen interpretation](http://en.wikipedia.org/wiki/Copenhagen_interpretation) is missing from this list by intention ;) | You will probably find a satisfactory answer reading the experiment done by **Shahriar Afshar**, who claimes to have observed both, the wave and particle, properties of mater simultaneously. Here is the link,
<http://en.wikipedia.org/wiki/Afshar_experiment>
You will find more links therein, as well as criticism of the interpretation of his experiment. The best way to settle scientific "conflicts" is by experiment. Debates and arguments have conceptual limitations. |
59,448 | I'm confused by the famous wave-particle duality mystery:
When a particle is left unobserved, it acts like a wave and can explore all classically available particle trajectories simultaneously. By looking at it, you force it to decide on a single trajectory, like going through the left or right slit, or like Schrödinger's cat that ends up being either dead or alive; the wave-like characteristics are lost.
Are there theories that actually *explain* this behaviour? | 2013/03/30 | [
"https://physics.stackexchange.com/questions/59448",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/8091/"
] | You will probably find a satisfactory answer reading the experiment done by **Shahriar Afshar**, who claimes to have observed both, the wave and particle, properties of mater simultaneously. Here is the link,
<http://en.wikipedia.org/wiki/Afshar_experiment>
You will find more links therein, as well as criticism of the interpretation of his experiment. The best way to settle scientific "conflicts" is by experiment. Debates and arguments have conceptual limitations. | I think your confusion about waves and particles will go away if you start thinking about what information nature *allows* you to know about the system you are examining.
Think about macroscopic ball: billions of air molecules and photons bounce off from it all the time. You can in theory use all the information to have lots of data about the ball: it's position shape, color, etc. It's all behave classical because of the so many clues the nature give you.
But things become interesting if you think about a single particle. You cannot see a photon flying along the same way you see a ball flying after it was kicked. The only way to observe a photon is catching it in a detector.
Imagine we excite a single atom, that electron will soon drop back to a lower orbital and the will emit the photon. What do you know about this photon? Once it's emitted we can be pretty sure that after 1 nanosecond it will be roughly 30cm away, after 2 nanoseconds it will be roughly 60cm away as it's moving precisely at the speed of light. So if it didn't hit the wall 40 cm away from the emission site within 2 nanoseconds, we can be certain it never will.
We also don't know which direction it was emitted. Any direction possible.
If we plot the possible paths the photon may take as a probability density function and animate it as the time passes it really start looking like a spherical wave going away from the emission site.
Then we don't even know when the photon is emitted, we can know a probability density function when the emission happens after excitation. So our expanding wave like sphere now really looks like a pulse of wave not like a sharp sphere. Then we can add further twists by adding optics to the system, mirrors will reflect the photon, if we address this in our calculations it looks like the wave is reflected from the mirror, or refracted on the prism like real waves do.
Then the final twist is when we deal with the case when the photon can reach the the same point in space via multiple paths at the same time: Feynman's path integral formula can be used to calculate what's the chance we can catch it there. That's why the interference happens.
All of these can be derived from the information what we can know about the photon, it doesn't mean there is a real wave there. It just exist our heads, while trying to reason about the information we know about the photon.
Eventually one atom somewhere will absorb the photon and nature will finally reveal where the photon actually went and you can verify that it behaved according to the laws of Physics, but until that, you can only guess, and that's why it seems there are waves. |
59,448 | I'm confused by the famous wave-particle duality mystery:
When a particle is left unobserved, it acts like a wave and can explore all classically available particle trajectories simultaneously. By looking at it, you force it to decide on a single trajectory, like going through the left or right slit, or like Schrödinger's cat that ends up being either dead or alive; the wave-like characteristics are lost.
Are there theories that actually *explain* this behaviour? | 2013/03/30 | [
"https://physics.stackexchange.com/questions/59448",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/8091/"
] | The answer by JKL is sufficient but I want to address particularly the *Why?*.
>
> I am so confused. Why does it act the way it does?
>
>
>
If one reads a bit about the history of science and physics in particular, it becomes clear that physics at the ultimate end does not answer the ultimate *Why?*. Physics posits laws and uses sophisticated mathematical tools to theorize from "axioms", get equations, and check against the data experimentally. It finds *How*, from "axioms" one ends with predictions for measurements that validate them.
The *Why?* questions addressed to the "axioms" has the only answer: *Because* .
When one is validating a theory, as for example Newton's gravitational theory, and one hits a disagreement with the data, new "axioms" and new theoretical tools are developed to explain the *Why* of the disagreement and the new theory validated for the regime of disagreement. Special and General Relativity are an example. The history of physics has other examples : Thermodynamics, developed theoretically to explain bulk behavior, statistical mechanics, out of classical mechanics emerge out of asking *How* and assuming "axioms" to contain the *Why*. Each theory with its own regime of validity.
Within a theory a question with a *Why* is answered by proofs of *How* finally hitting on the "axioms". Quantum mechanics is the last in the series of exploring the microcosm. The *Why* you are asking hits against the *Because* of its "axioms".
There are people who continue the exploration, trying new axiomatic theories of how a quantum mechanical theory can emerge from a smaller regime where we are back to classical concepts, and contain the *Why* in "axioms" for their new theory. They are not successful except with small models. The bulk of theoretical physicists either ignores their efforts or proves that their new theories would violate a basic validated law as, for example, Lorentz invariance. And that is the story of *Why* in Physics. Ultimately the answer is *Because*.
Edit: "axioms" in quotation marks , to include mathematial axioms and physics postulates. Physical theories start from strict axiomatic mathematical theories where everything is contained and rigorously self consistent and add postulates in order to connect physical observables to the mathematical variables/functions. [Postulates](http://hyperphysics.phy-astr.gsu.edu/hbase/quantum/qm.html) are a necessary choice to turn a mathematical theory into a physics theory and in classical theories are referred as "laws". I call them "axioms" because they are the foundation stones of the theories, if one goes the whole theory goes. | This answer expands on the answer given by anna v
It is easy to become accustomed to a pattern of physics providing explanation after explanation.
For example, how is it that a gas has elastic properties under compression? If you compress it to half the volume, the pressure pretty much doubles. It's surprisingly similar to a spring, yet a gas isn't a spring, surely?
Physics offers a wonderful explanation: the molecules of the gas are moving fast, and collisions of molecules are perfectly elastic. The pressure of a gas against the walls of the vessel arises from elastic collisions of the molecules with the walls. If you half the volume the number of collisions pretty much doubles, hence the change of pressure.
What the physics did there: it moved the description of physics taking place to a deeper level. As it happens the physics on this deeper level (fast moving, elastically colliding molecules) is very readily visualized in things we know in the macroscopic world. We can readily visualize a population of bouncing balls.
In this particular case we are fortunate: the *description at a deeper level* consists of something that has a counterpart in physics we can see happening with our own eyes.
So yeah, it's natural to *hope* that a theory at quantum level can describe the physics taking place in terms of things we can visualize: particles, and waves. Well, in the case of quantum mechanics it turns out that what is expressed by the equations has no counterpart in the macroscopic world.
We make do with concepts we *can* visualize; particles and waves. In that sense the duality is introduced by the human thinking process; it's not inherent in the physics.
---
On more remark, again expanding on the anwser by anna v:
What is not in physics is *exhaustive explanation*.
When a new theory replaces an existing theory the description of the physics taking place moves to a deeper level.
When newtonian mechanics was established it looked for more than 300 years that no deeper level existed. Then, in the course of development of relativistic physics, theory of motion moved to a yet deeper level. So we learned not to expect that we are at the most fundamental level. A deeper level of description may be possible, we don't know.
Physics is not in the business of looking for exhaustive explanation. For the duration of working at a particular level of description (which can last hundreds of years) the assumptions necessary for that level of description are taken as given.
For comparison:
Newton *assumed* the existence of a gravitational force, acting over large distance, to explain the fact that the planets are orbiting the Sun. Newton's contemporaries were more demanding. For example, Descartes offered a hypothesis of vortices in space, with those vortices exerting an inward push on the planets. Descartes was determined to restrict himself to hypotheses with understandable elements only. He could visualize vortices, thus he ended up with vortices.
In retrospect we see that Descartes was just bogging himself down. Newton was more successfull because he operated on a need-to-assume basis.
Newton could not explain gravity itself, but he saw the strong explanatory strength it offered, and he moved ahead. |
59,448 | I'm confused by the famous wave-particle duality mystery:
When a particle is left unobserved, it acts like a wave and can explore all classically available particle trajectories simultaneously. By looking at it, you force it to decide on a single trajectory, like going through the left or right slit, or like Schrödinger's cat that ends up being either dead or alive; the wave-like characteristics are lost.
Are there theories that actually *explain* this behaviour? | 2013/03/30 | [
"https://physics.stackexchange.com/questions/59448",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/8091/"
] | The answer by JKL is sufficient but I want to address particularly the *Why?*.
>
> I am so confused. Why does it act the way it does?
>
>
>
If one reads a bit about the history of science and physics in particular, it becomes clear that physics at the ultimate end does not answer the ultimate *Why?*. Physics posits laws and uses sophisticated mathematical tools to theorize from "axioms", get equations, and check against the data experimentally. It finds *How*, from "axioms" one ends with predictions for measurements that validate them.
The *Why?* questions addressed to the "axioms" has the only answer: *Because* .
When one is validating a theory, as for example Newton's gravitational theory, and one hits a disagreement with the data, new "axioms" and new theoretical tools are developed to explain the *Why* of the disagreement and the new theory validated for the regime of disagreement. Special and General Relativity are an example. The history of physics has other examples : Thermodynamics, developed theoretically to explain bulk behavior, statistical mechanics, out of classical mechanics emerge out of asking *How* and assuming "axioms" to contain the *Why*. Each theory with its own regime of validity.
Within a theory a question with a *Why* is answered by proofs of *How* finally hitting on the "axioms". Quantum mechanics is the last in the series of exploring the microcosm. The *Why* you are asking hits against the *Because* of its "axioms".
There are people who continue the exploration, trying new axiomatic theories of how a quantum mechanical theory can emerge from a smaller regime where we are back to classical concepts, and contain the *Why* in "axioms" for their new theory. They are not successful except with small models. The bulk of theoretical physicists either ignores their efforts or proves that their new theories would violate a basic validated law as, for example, Lorentz invariance. And that is the story of *Why* in Physics. Ultimately the answer is *Because*.
Edit: "axioms" in quotation marks , to include mathematial axioms and physics postulates. Physical theories start from strict axiomatic mathematical theories where everything is contained and rigorously self consistent and add postulates in order to connect physical observables to the mathematical variables/functions. [Postulates](http://hyperphysics.phy-astr.gsu.edu/hbase/quantum/qm.html) are a necessary choice to turn a mathematical theory into a physics theory and in classical theories are referred as "laws". I call them "axioms" because they are the foundation stones of the theories, if one goes the whole theory goes. | >
> Are there theories that explain wave-particle duality?
>
>
>
Yes, several actually, but they are interpretations rather than new theories.
As anna v explained in her reply, at its most fundamental level the only answer a physical theory can give to the question *Why?* is *Because!*.
It's impossible to give a more meaningful definite answer until we've taken another step down the rabbit hole (assuming we've not yet arrived at the bottom, of course).
However, you're not the only one uncomfortable with the situation, and that's where *interpretations* of our physical models come in, and there's a whole bunch of them for quantum mechanics.
As far as wave-particle duality goes, here are the explanations given by various interpretations:
* according to the [statistical interpretation](http://en.wikipedia.org/wiki/Ensemble_interpretation), quantum mechanis only describes ensembles and the question cannot be answered without an underlying new theory
* according to the [de Broglie-Bohm interpretation](http://en.wikipedia.org/wiki/De_Broglie%E2%80%93Bohm_theory), there are both particles and waves, the former being guided by the latter
* according to the [transactional interpretation](http://en.wikipedia.org/wiki/Transactional_interpretation), we have waves going forwards and backwards in time, resulting in particle-like interactions by interference
* according to the [many worlds interpretation](http://en.wikipedia.org/wiki/Many-worlds_interpretation), we have particles going all possible ways in different worlds
* according to the [consistent histories interpretation](http://en.wikipedia.org/wiki/Consistent_histories) (on which I should probably read up some more, so take this with a grain of salt), the particle or wave-like characteristics are just artifacts of a particular choice of history, which gain reality be decoherence
The [Copenhagen interpretation](http://en.wikipedia.org/wiki/Copenhagen_interpretation) is missing from this list by intention ;) |
59,448 | I'm confused by the famous wave-particle duality mystery:
When a particle is left unobserved, it acts like a wave and can explore all classically available particle trajectories simultaneously. By looking at it, you force it to decide on a single trajectory, like going through the left or right slit, or like Schrödinger's cat that ends up being either dead or alive; the wave-like characteristics are lost.
Are there theories that actually *explain* this behaviour? | 2013/03/30 | [
"https://physics.stackexchange.com/questions/59448",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/8091/"
] | The answer by JKL is sufficient but I want to address particularly the *Why?*.
>
> I am so confused. Why does it act the way it does?
>
>
>
If one reads a bit about the history of science and physics in particular, it becomes clear that physics at the ultimate end does not answer the ultimate *Why?*. Physics posits laws and uses sophisticated mathematical tools to theorize from "axioms", get equations, and check against the data experimentally. It finds *How*, from "axioms" one ends with predictions for measurements that validate them.
The *Why?* questions addressed to the "axioms" has the only answer: *Because* .
When one is validating a theory, as for example Newton's gravitational theory, and one hits a disagreement with the data, new "axioms" and new theoretical tools are developed to explain the *Why* of the disagreement and the new theory validated for the regime of disagreement. Special and General Relativity are an example. The history of physics has other examples : Thermodynamics, developed theoretically to explain bulk behavior, statistical mechanics, out of classical mechanics emerge out of asking *How* and assuming "axioms" to contain the *Why*. Each theory with its own regime of validity.
Within a theory a question with a *Why* is answered by proofs of *How* finally hitting on the "axioms". Quantum mechanics is the last in the series of exploring the microcosm. The *Why* you are asking hits against the *Because* of its "axioms".
There are people who continue the exploration, trying new axiomatic theories of how a quantum mechanical theory can emerge from a smaller regime where we are back to classical concepts, and contain the *Why* in "axioms" for their new theory. They are not successful except with small models. The bulk of theoretical physicists either ignores their efforts or proves that their new theories would violate a basic validated law as, for example, Lorentz invariance. And that is the story of *Why* in Physics. Ultimately the answer is *Because*.
Edit: "axioms" in quotation marks , to include mathematial axioms and physics postulates. Physical theories start from strict axiomatic mathematical theories where everything is contained and rigorously self consistent and add postulates in order to connect physical observables to the mathematical variables/functions. [Postulates](http://hyperphysics.phy-astr.gsu.edu/hbase/quantum/qm.html) are a necessary choice to turn a mathematical theory into a physics theory and in classical theories are referred as "laws". I call them "axioms" because they are the foundation stones of the theories, if one goes the whole theory goes. | I think your confusion about waves and particles will go away if you start thinking about what information nature *allows* you to know about the system you are examining.
Think about macroscopic ball: billions of air molecules and photons bounce off from it all the time. You can in theory use all the information to have lots of data about the ball: it's position shape, color, etc. It's all behave classical because of the so many clues the nature give you.
But things become interesting if you think about a single particle. You cannot see a photon flying along the same way you see a ball flying after it was kicked. The only way to observe a photon is catching it in a detector.
Imagine we excite a single atom, that electron will soon drop back to a lower orbital and the will emit the photon. What do you know about this photon? Once it's emitted we can be pretty sure that after 1 nanosecond it will be roughly 30cm away, after 2 nanoseconds it will be roughly 60cm away as it's moving precisely at the speed of light. So if it didn't hit the wall 40 cm away from the emission site within 2 nanoseconds, we can be certain it never will.
We also don't know which direction it was emitted. Any direction possible.
If we plot the possible paths the photon may take as a probability density function and animate it as the time passes it really start looking like a spherical wave going away from the emission site.
Then we don't even know when the photon is emitted, we can know a probability density function when the emission happens after excitation. So our expanding wave like sphere now really looks like a pulse of wave not like a sharp sphere. Then we can add further twists by adding optics to the system, mirrors will reflect the photon, if we address this in our calculations it looks like the wave is reflected from the mirror, or refracted on the prism like real waves do.
Then the final twist is when we deal with the case when the photon can reach the the same point in space via multiple paths at the same time: Feynman's path integral formula can be used to calculate what's the chance we can catch it there. That's why the interference happens.
All of these can be derived from the information what we can know about the photon, it doesn't mean there is a real wave there. It just exist our heads, while trying to reason about the information we know about the photon.
Eventually one atom somewhere will absorb the photon and nature will finally reveal where the photon actually went and you can verify that it behaved according to the laws of Physics, but until that, you can only guess, and that's why it seems there are waves. |
59,448 | I'm confused by the famous wave-particle duality mystery:
When a particle is left unobserved, it acts like a wave and can explore all classically available particle trajectories simultaneously. By looking at it, you force it to decide on a single trajectory, like going through the left or right slit, or like Schrödinger's cat that ends up being either dead or alive; the wave-like characteristics are lost.
Are there theories that actually *explain* this behaviour? | 2013/03/30 | [
"https://physics.stackexchange.com/questions/59448",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/8091/"
] | This answer expands on the answer given by anna v
It is easy to become accustomed to a pattern of physics providing explanation after explanation.
For example, how is it that a gas has elastic properties under compression? If you compress it to half the volume, the pressure pretty much doubles. It's surprisingly similar to a spring, yet a gas isn't a spring, surely?
Physics offers a wonderful explanation: the molecules of the gas are moving fast, and collisions of molecules are perfectly elastic. The pressure of a gas against the walls of the vessel arises from elastic collisions of the molecules with the walls. If you half the volume the number of collisions pretty much doubles, hence the change of pressure.
What the physics did there: it moved the description of physics taking place to a deeper level. As it happens the physics on this deeper level (fast moving, elastically colliding molecules) is very readily visualized in things we know in the macroscopic world. We can readily visualize a population of bouncing balls.
In this particular case we are fortunate: the *description at a deeper level* consists of something that has a counterpart in physics we can see happening with our own eyes.
So yeah, it's natural to *hope* that a theory at quantum level can describe the physics taking place in terms of things we can visualize: particles, and waves. Well, in the case of quantum mechanics it turns out that what is expressed by the equations has no counterpart in the macroscopic world.
We make do with concepts we *can* visualize; particles and waves. In that sense the duality is introduced by the human thinking process; it's not inherent in the physics.
---
On more remark, again expanding on the anwser by anna v:
What is not in physics is *exhaustive explanation*.
When a new theory replaces an existing theory the description of the physics taking place moves to a deeper level.
When newtonian mechanics was established it looked for more than 300 years that no deeper level existed. Then, in the course of development of relativistic physics, theory of motion moved to a yet deeper level. So we learned not to expect that we are at the most fundamental level. A deeper level of description may be possible, we don't know.
Physics is not in the business of looking for exhaustive explanation. For the duration of working at a particular level of description (which can last hundreds of years) the assumptions necessary for that level of description are taken as given.
For comparison:
Newton *assumed* the existence of a gravitational force, acting over large distance, to explain the fact that the planets are orbiting the Sun. Newton's contemporaries were more demanding. For example, Descartes offered a hypothesis of vortices in space, with those vortices exerting an inward push on the planets. Descartes was determined to restrict himself to hypotheses with understandable elements only. He could visualize vortices, thus he ended up with vortices.
In retrospect we see that Descartes was just bogging himself down. Newton was more successfull because he operated on a need-to-assume basis.
Newton could not explain gravity itself, but he saw the strong explanatory strength it offered, and he moved ahead. | I think your confusion about waves and particles will go away if you start thinking about what information nature *allows* you to know about the system you are examining.
Think about macroscopic ball: billions of air molecules and photons bounce off from it all the time. You can in theory use all the information to have lots of data about the ball: it's position shape, color, etc. It's all behave classical because of the so many clues the nature give you.
But things become interesting if you think about a single particle. You cannot see a photon flying along the same way you see a ball flying after it was kicked. The only way to observe a photon is catching it in a detector.
Imagine we excite a single atom, that electron will soon drop back to a lower orbital and the will emit the photon. What do you know about this photon? Once it's emitted we can be pretty sure that after 1 nanosecond it will be roughly 30cm away, after 2 nanoseconds it will be roughly 60cm away as it's moving precisely at the speed of light. So if it didn't hit the wall 40 cm away from the emission site within 2 nanoseconds, we can be certain it never will.
We also don't know which direction it was emitted. Any direction possible.
If we plot the possible paths the photon may take as a probability density function and animate it as the time passes it really start looking like a spherical wave going away from the emission site.
Then we don't even know when the photon is emitted, we can know a probability density function when the emission happens after excitation. So our expanding wave like sphere now really looks like a pulse of wave not like a sharp sphere. Then we can add further twists by adding optics to the system, mirrors will reflect the photon, if we address this in our calculations it looks like the wave is reflected from the mirror, or refracted on the prism like real waves do.
Then the final twist is when we deal with the case when the photon can reach the the same point in space via multiple paths at the same time: Feynman's path integral formula can be used to calculate what's the chance we can catch it there. That's why the interference happens.
All of these can be derived from the information what we can know about the photon, it doesn't mean there is a real wave there. It just exist our heads, while trying to reason about the information we know about the photon.
Eventually one atom somewhere will absorb the photon and nature will finally reveal where the photon actually went and you can verify that it behaved according to the laws of Physics, but until that, you can only guess, and that's why it seems there are waves. |
59,448 | I'm confused by the famous wave-particle duality mystery:
When a particle is left unobserved, it acts like a wave and can explore all classically available particle trajectories simultaneously. By looking at it, you force it to decide on a single trajectory, like going through the left or right slit, or like Schrödinger's cat that ends up being either dead or alive; the wave-like characteristics are lost.
Are there theories that actually *explain* this behaviour? | 2013/03/30 | [
"https://physics.stackexchange.com/questions/59448",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/8091/"
] | >
> Are there theories that explain wave-particle duality?
>
>
>
Yes, several actually, but they are interpretations rather than new theories.
As anna v explained in her reply, at its most fundamental level the only answer a physical theory can give to the question *Why?* is *Because!*.
It's impossible to give a more meaningful definite answer until we've taken another step down the rabbit hole (assuming we've not yet arrived at the bottom, of course).
However, you're not the only one uncomfortable with the situation, and that's where *interpretations* of our physical models come in, and there's a whole bunch of them for quantum mechanics.
As far as wave-particle duality goes, here are the explanations given by various interpretations:
* according to the [statistical interpretation](http://en.wikipedia.org/wiki/Ensemble_interpretation), quantum mechanis only describes ensembles and the question cannot be answered without an underlying new theory
* according to the [de Broglie-Bohm interpretation](http://en.wikipedia.org/wiki/De_Broglie%E2%80%93Bohm_theory), there are both particles and waves, the former being guided by the latter
* according to the [transactional interpretation](http://en.wikipedia.org/wiki/Transactional_interpretation), we have waves going forwards and backwards in time, resulting in particle-like interactions by interference
* according to the [many worlds interpretation](http://en.wikipedia.org/wiki/Many-worlds_interpretation), we have particles going all possible ways in different worlds
* according to the [consistent histories interpretation](http://en.wikipedia.org/wiki/Consistent_histories) (on which I should probably read up some more, so take this with a grain of salt), the particle or wave-like characteristics are just artifacts of a particular choice of history, which gain reality be decoherence
The [Copenhagen interpretation](http://en.wikipedia.org/wiki/Copenhagen_interpretation) is missing from this list by intention ;) | I think your confusion about waves and particles will go away if you start thinking about what information nature *allows* you to know about the system you are examining.
Think about macroscopic ball: billions of air molecules and photons bounce off from it all the time. You can in theory use all the information to have lots of data about the ball: it's position shape, color, etc. It's all behave classical because of the so many clues the nature give you.
But things become interesting if you think about a single particle. You cannot see a photon flying along the same way you see a ball flying after it was kicked. The only way to observe a photon is catching it in a detector.
Imagine we excite a single atom, that electron will soon drop back to a lower orbital and the will emit the photon. What do you know about this photon? Once it's emitted we can be pretty sure that after 1 nanosecond it will be roughly 30cm away, after 2 nanoseconds it will be roughly 60cm away as it's moving precisely at the speed of light. So if it didn't hit the wall 40 cm away from the emission site within 2 nanoseconds, we can be certain it never will.
We also don't know which direction it was emitted. Any direction possible.
If we plot the possible paths the photon may take as a probability density function and animate it as the time passes it really start looking like a spherical wave going away from the emission site.
Then we don't even know when the photon is emitted, we can know a probability density function when the emission happens after excitation. So our expanding wave like sphere now really looks like a pulse of wave not like a sharp sphere. Then we can add further twists by adding optics to the system, mirrors will reflect the photon, if we address this in our calculations it looks like the wave is reflected from the mirror, or refracted on the prism like real waves do.
Then the final twist is when we deal with the case when the photon can reach the the same point in space via multiple paths at the same time: Feynman's path integral formula can be used to calculate what's the chance we can catch it there. That's why the interference happens.
All of these can be derived from the information what we can know about the photon, it doesn't mean there is a real wave there. It just exist our heads, while trying to reason about the information we know about the photon.
Eventually one atom somewhere will absorb the photon and nature will finally reveal where the photon actually went and you can verify that it behaved according to the laws of Physics, but until that, you can only guess, and that's why it seems there are waves. |
34,955,076 | When I run this, the first time I open History tab, nothing shows up on the tableView. Only after I rotate the screen things show up but they are still being funny.Both labels show up only after rotating the screen. Not all the history is being shown as well sometimes. I read that I am missing some initializer but I keep getting errors once change things... Any help will be appreciated
```
//
// SecondViewController.swift
//
// Created by Artiom Sobol on 1/3/16.
// Copyright © 2016 Artiom Sobol. All rights reserved.
//
import UIKit
class History: UIViewController, UITableViewDataSource, UITableViewDelegate
{
// test variable
var test: MyHistory!
// array to store unarchived history
var newHistory = [MyHistory]()
//outlet for tableview
@IBOutlet var tableView: UITableView!
override func viewDidLoad()
{
//change the background
self.view.backgroundColor = UIColor(patternImage: UIImage(named: "newBackground.jpg")!)
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
//self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "historyCell")
self.tableView.reloadData()
//unarchive any new data
let defaults = NSUserDefaults.standardUserDefaults()
if let savedPeople = defaults.objectForKey("MyHistory") as? NSData {
newHistory = NSKeyedUnarchiver.unarchiveObjectWithData(savedPeople) as! [MyHistory]
}
}
func tableView(tableView: UITableView,numberOfRowsInSection section: Int) -> Int
{
if (newHistory.count < 1)
{
return 1
}
else
{
return self.newHistory.count
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("historyCell", forIndexPath: indexPath) as! historyCell
let person = newHistory[indexPath.item]
let defaults2 = NSUserDefaults.standardUserDefaults()
print("This is count", newHistory.count)
if let savedPeople = defaults2.objectForKey("MyHistory") as? NSData {
newHistory = NSKeyedUnarchiver.unarchiveObjectWithData(savedPeople) as! [MyHistory]
}
// cell.durationLabel.text = String(person.durationNumber)
let (hour,minutes,seconds) = secondsToHoursMinutesSeconds(person.durationNumber)
if(seconds < 10 && minutes < 10)
{
cell.durationLabel.text = "0\(hour):0\(minutes):0\(seconds)"
}
else if(seconds > 9 && minutes < 10)
{
cell.durationLabel.text = "0\(hour):0\(minutes):\(seconds)"
}
else if(seconds > 9 && minutes > 9)
{
cell.durationLabel.text = "0\(hour):\(minutes):\(seconds)"
}
else if(seconds < 10 && minutes > 9)
{
cell.durationLabel.text = "0\(hour):\(minutes):0\(seconds)"
}
cell.kicksLabel.text = String(person.kicksNumber)
return cell
}
func secondsToHoursMinutesSeconds (seconds : Int) -> (Int, Int, Int)
{
return (seconds / 3600, (seconds % 3600) / 60, (seconds % 3600) % 60)
}
override func viewWillAppear(animated: Bool)
{
super.viewWillAppear(animated)
self.tableView.reloadData()
}
}
``` | 2016/01/22 | [
"https://Stackoverflow.com/questions/34955076",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5601771/"
] | **A Requirements**:
Let’s assume below simplified case/scenario
1 *We have one "big" table:*
TableAll
```
Row a b c
1 1 11 12
2 1 13 14
3 1 15 16
4 1 17 18
5 2 21 22
6 2 23 24
7 2 25 26
8 2 27 28
9 3 31 32
10 3 33 34
11 3 35 36
12 3 37 38
```
2 *We need to split data to separate "smaller" tables partitioned by filed "a"*
TableA1
```
Row b c
1 11 12
2 13 14
3 15 16
4 17 18
```
TableA2
```
Row b c
1 21 22
2 23 24
3 25 26
4 27 28
```
TableA3
```
Row b c
1 31 32
2 33 34
3 35 36
4 37 38
```
3 *Problem to address*
Most straightforward way is to issue three separate statements with writing output to respectively TableA1, TableA2, TableA3
```
SELECT b, c FROM TableAll WHERE a = 1;
SELECT b, c FROM TableAll WHERE a = 2;
SELECT b, c FROM TableAll WHERE a = 3;
```
Pros: Fast and Furious!
Cons: We need as many table scans of whole table (full cost) as many distinct value of "a" we have (in this particular case just three, but in real life it can be let’s say up to N=1K distinct values).
So final Cost is **$5 \* N \* SizeInTB(TableAll)**
>
> Our Target Goal
>
>
>
```
We want to minimize cost as much as possible
ideally down to fixed price of $5 * SizeInTB(TableAll)
```
**B Possible Solution (Idea and simple implementation)**:
*Logical Step 1 – transform data to be presented as below (transform columns into JSON)*
```
Row a json
1 1 {"b":"11", "c":"12"}
2 1 {"b":"13", "c":"14"}
3 1 {"b":"15", "c":"16"}
4 1 {"b":"17", "c":"18"}
5 2 {"b":"21", "c":"22"}
6 2 {"b":"23", "c":"24"}
7 2 {"b":"25", "c":"26"}
8 2 {"b":"27", "c":"28"}
9 3 {"b":"31", "c":"32"}
10 3 {"b":"33", "c":"34"}
11 3 {"b":"35", "c":"36"}
12 3 {"b":"37", "c":"38"}
```
*Logical Step 2 – Pivot table so that values of field "a" become name of fields (prefixed with a to make sure we comply with column name convention)*
```
Row a1 a2 a3
1 {"b":"11", "c":"12"} null null
2 {"b":"13", "c":"14"} null null
3 {"b":"15", "c":"16"} null null
4 {"b":"17", "c":"18"} null null
5 null {"b":"21", "c":"22"} null
6 null {"b":"23", "c":"24"} null
7 null {"b":"25", "c":"26"} null
8 null {"b":"27", "c":"28"} null
9 null null {"b":"31", "c":"32"}
10 null null {"b":"33", "c":"34"}
11 null null {"b":"35", "c":"36"}
12 null null {"b":"37", "c":"38"}
```
Note: *size of above data is of same order as size of original table (w/o column a)
It is still bigger than original data because data now is in verbose json format vs native data types + column names.
This can be optimized by eliminating spaces, not needed quotes, normalizing/minimizing original column names to have just one char in name, etc.
I think this difference becomes negligible with N going up! (haven’t had chance to evaluate this though)*
*Step 3 – Preserve resulted pivot into table TableAllPivot*
Implementation Example:
```
SELECT
IF(a=1, json, NULL) as a1,
IF(a=2, json, NULL) as a2,
IF(a=3, json, NULL) as a3
FROM (
SELECT a, CONCAT("{\"b\":\"",STRING(b), "\","," \"c\":\"", STRING(c), "\"}") AS json
FROM TableAll
)
```
Cost of Step 3: `$5 * TableAllSizeInTB`
Based on comments in Step 2 assume: `Size(TableAllPivot) = 2 * Size(TableAll)`
*Step 4 – Produce Shards, by querying only one column per shard*
To preserve schema/data-types – respective Shard Tables can be created in advance
*Data Extraction* :
//For TableA1:
```
SELECT
JSON_EXTRACT_SCALAR(a1, '$.b') AS b,
JSON_EXTRACT_SCALAR(a1, '$.c') AS c
FROM TableAllPivot
WHERE NOT a1 IS NULL
```
//For TableA2:
```
SELECT
JSON_EXTRACT_SCALAR(a2, '$.b') AS b,
JSON_EXTRACT_SCALAR(a2, '$.c') AS c
FROM TableAllPivot
WHERE NOT a2 IS NULL
```
//For TableA3:
```
SELECT
JSON_EXTRACT_SCALAR(a3, '$.b') AS b,
JSON_EXTRACT_SCALAR(a3, '$.c') AS c
FROM TableAllPivot
WHERE NOT a3 IS NULL
```
Cost of Step 4: `$5 * TableAllPivot`
Total Cost: `Step 3 Cost + Step 4 Cost` =
`$5 * SizeInTB(TableAll) + $5 * SizeInTB(TableAllPivot)` ~ `$5 * 3 * SizeInTB(TableAll)`
**Summary**:
Proposed approach fixed price = `$5 * 3 * SizeInTB(TableAll)`
vs.
Initial linear price = `$5 * N * SizeInTB(TableAll)`
**Please note**: `3` in `$5 * 3 * SizeInTB(TableAll)` formula is not defined by number of shards in my simplified example, but rather estimated constant that mostly reflects price of transforming data to json. Number of shards doesnt matter here. Same formula will be for 100 shards and for 1K shard and so on. The only limitation in this solution is 10K shards as this is a hard limit for number of columns in one table
**C Some helper code and references**:
1 *Produce Pivoting Query (result is used in step 3 above section)*
Can be useful for number of fields in initial table greater than let's say 10-20, when typing query manually is boring, so you can use below script/query
```
SELECT 'SELECT ' +
GROUP_CONCAT_UNQUOTED(
'IF(a=' + STRING(a) + ', json, NULL) as a' + STRING(a)
)
+ ' FROM (
SELECT a,
CONCAT("{\\\"b\\\":\\\"\",STRING(b),"\\\","," \\\"c\\\":\\\"\", STRING(c),"\\\"}") AS json
FROM TableAll
)'
FROM (
SELECT a FROM TableAll GROUP BY a
)
```
2 *In case if you want to explore and dive more into this option - see also below references to related & potentially useful here code*
[Pivot Repeated fields in BigQuery](https://stackoverflow.com/questions/33768448/pivot-repeated-fields-in-bigquery/33769831#33769831)
[How to scale Pivoting in BigQuery?](https://stackoverflow.com/questions/34845697/how-to-scale-pivoting-in-bigquery)
[How to extract all the keys in a JSON object with BigQuery](https://stackoverflow.com/questions/34890339/how-to-extract-all-the-keys-in-a-json-object-with-bigquery/#34892989) | 2018 update
-----------
* Instead of creating multiple tables, create a partitioned one.
* Partition for free: Create partitioned table (by date), import into it.
* Partition with one query (one scan): `CREATE TABLE ... AS SELECT * FROM old-table`
See the following post to also benefit from clustering:
* <https://medium.com/google-cloud/bigquery-optimized-cluster-your-tables-65e2f684594b>
---
I really like Mikhail's answer, but let me give you a different one: Divide to conquer:
Let's say your table has 8 numbers (think of each number as a partition): 12345678. To shard this into 8 tables, you are looking into running 8 times a query over a table size 8 (cost: 8\*8=64).
What if you first divide this table into 2: 1234, 5678. The cost was 8\*2 (2 full scans), but we now have 2 tables. If we want to partition these half tables, now we only need to scan half 2 times (2\*4\*2). Then we are left with 4 tables: 12,34,56,78. The cost of partitioning them would be 4\*2\*2... so the total cost would be 8\*2+2\*4\*2+4\*2\*2=48. By doing halves we took the cost of partitioning a table in 8 from 64 to 48.
Mathematically speaking, we are going from O(n\*\*2) to O(n(log n)) - and that's always a good thing.
Cost-wise Mikhail's answer is better, as it goes from O(n\*\*2) to O(n), but writing the intermediate helper functions will introduce additional complexity to the task. |
60,019,558 | I am trying to write a bash script that takes in a directory, reads each file in the directory, and then appends the first line of each file in that directory to a new file. When I hard-code the variables in my script, it works fine.
This works:
```
#!/bin/bash
rm /local/SomePath/multigene.firstline.btab
touch /local/SomePath/multigene.firstline.btab
btabdir=/local/SomePath/test/*
outfile=/local/SomePath/multigene.firstline.btab
for f in $btabdir
do
head -1 $f >> $outfile
done
```
This does not work:
```
#!/bin/bash
while getopts ":d:o:" opt; do
case ${opt} in
d) btabdir=$OPTARG;;
o) outfile=$OPTARG;;
esac
done
rm $outfile
touch $outfile
for f in $btabdir
do
head -1 $f >> $outfile
done
```
Here is how I call the script:
```
bash /local/SomePath/Scripts/btab.besthits.wBp-q_wBm-r.sh -d /local/SomePath/test/* -o /local/SomePath/out.test/multigene.firstline.btab
```
And here is what I get when I run it:
```
rm: missing operand
Try 'rm --help' for more information.
touch: missing file operand
Try 'touch --help' for more information.
/local/SomePath/Scripts/btab.besthits.wBp-q_wBm-r.sh: line 23: $outfile: ambiguous redirect
```
Any suggestions? I'd like to be able to use `getopts` so I can make the script more generic. Thanks! | 2020/02/01 | [
"https://Stackoverflow.com/questions/60019558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8334443/"
] | You have to pay extra attention to [quoting](https://mywiki.wooledge.org/Quotes#Prevent_field_splitting_and_ignore_glob_pattern_characters) and [globbing](https://www.tldp.org/LDP/abs/html/globbingref.html) when writing bash scripts.
When you call the script with a glob (`*` here) it gets expanded and split into words by your shell. This happends before your script even gets executed.
If you for example do `cat *.txt` cat will get all .txt files in the directory as its arguments. It will be the same as calling `cat afile.txt nextfile.txt` (and so on). Cat will never see the asterisk.
In your script it means that the input `-d /local/SomePath/test/*` gets expanded som something like `/local/SomePath/test/someFile /local/SomePath/test/someOtherFile /test/someThirdFile`.
Subsequently `getopts` only takes the first file after `-d` as for `$btabdir` and the `-o` doesn't get handled in the case switch.
I suggest you start by quoting every variable, preferable in the `"${name}"` style, and only invoke the script with quoted input.
It might also be send in a directory path, test that it is a directory (`test -d`), and change your for loop to `for f in "${btabdir}"/*` | This also works:
```
head -n1 -q /local/SomePath/test/* >> /local/SomePath/out.test/multigene.firstline.btab
``` |
60,019,558 | I am trying to write a bash script that takes in a directory, reads each file in the directory, and then appends the first line of each file in that directory to a new file. When I hard-code the variables in my script, it works fine.
This works:
```
#!/bin/bash
rm /local/SomePath/multigene.firstline.btab
touch /local/SomePath/multigene.firstline.btab
btabdir=/local/SomePath/test/*
outfile=/local/SomePath/multigene.firstline.btab
for f in $btabdir
do
head -1 $f >> $outfile
done
```
This does not work:
```
#!/bin/bash
while getopts ":d:o:" opt; do
case ${opt} in
d) btabdir=$OPTARG;;
o) outfile=$OPTARG;;
esac
done
rm $outfile
touch $outfile
for f in $btabdir
do
head -1 $f >> $outfile
done
```
Here is how I call the script:
```
bash /local/SomePath/Scripts/btab.besthits.wBp-q_wBm-r.sh -d /local/SomePath/test/* -o /local/SomePath/out.test/multigene.firstline.btab
```
And here is what I get when I run it:
```
rm: missing operand
Try 'rm --help' for more information.
touch: missing file operand
Try 'touch --help' for more information.
/local/SomePath/Scripts/btab.besthits.wBp-q_wBm-r.sh: line 23: $outfile: ambiguous redirect
```
Any suggestions? I'd like to be able to use `getopts` so I can make the script more generic. Thanks! | 2020/02/01 | [
"https://Stackoverflow.com/questions/60019558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8334443/"
] | You have to pay extra attention to [quoting](https://mywiki.wooledge.org/Quotes#Prevent_field_splitting_and_ignore_glob_pattern_characters) and [globbing](https://www.tldp.org/LDP/abs/html/globbingref.html) when writing bash scripts.
When you call the script with a glob (`*` here) it gets expanded and split into words by your shell. This happends before your script even gets executed.
If you for example do `cat *.txt` cat will get all .txt files in the directory as its arguments. It will be the same as calling `cat afile.txt nextfile.txt` (and so on). Cat will never see the asterisk.
In your script it means that the input `-d /local/SomePath/test/*` gets expanded som something like `/local/SomePath/test/someFile /local/SomePath/test/someOtherFile /test/someThirdFile`.
Subsequently `getopts` only takes the first file after `-d` as for `$btabdir` and the `-o` doesn't get handled in the case switch.
I suggest you start by quoting every variable, preferable in the `"${name}"` style, and only invoke the script with quoted input.
It might also be send in a directory path, test that it is a directory (`test -d`), and change your for loop to `for f in "${btabdir}"/*` | I think the right answer here is "don't do it that way." :-)
The reason your current script isn't working may be that the wildcard is expanded by your interactive shell, not by your script. Try running your command with an `echo` at the beginning of the line for a hint at what's really happening. Once `getopts` sees the second of the matched files in the glob, it stops processing options, so `-o` never gets read, and `$outfile` remains unset. And since you don't quote your variable in `rm $outfile`, it's as if you're running `rm` without options. Test the difference in your shell between `rm` alone and `rm ""`.
Also, what happens to your `for` loop if there's a space in a filename? Since you have bash, you have arrays. And arrays are *much* better for processing lists of files.
Perhaps use something like this instead:
```
#!/bin/bash
# initialize an array
files=()
while getopts :d:o: opt; do
case "$opt" in
d)
if [[ ! -d "$OPTARG" ]]; then
printf 'ERROR: not a directory: %s\n' "$OPTARG" >&2
exit 65
fi
# add to the array
files+=( "$OPTARG"/* )
;;
o) outfile="$OPTARG" ;;
*)
printf 'ERROR: unknown option: %s\n' "$opt" >&2
exit 64
;;
esac
done
if ! rm -f "$outfile" && touch "$outfile"; then
printf 'ERROR: cannot create %s\n' "$outfile" >&2
exit 73
fi
for f in "${files[@]}"; do
read -r < "$f"
printf '%s\n' "$REPLY"
done > "$outfile"
```
Here are some highlights of the changes....
* We're using arrays, of course. The array `${files[@]}` will contain one-file-per-record, without relying on whitespace, so with proper quoting you'll avoid problems with special characters in filenames.
* We test for more error conditions, and actually show errors and exit if we see them. (The exit values are [sysexits](http://man.freebsd.org/sysexits).)
* Instead of using `head`, we use `read` and a single redirect to `$outfile`. This saves multiple forks to an external program, and multiple `fopen()` calls to your output file.
Note that the argument to `-d` should be a *directory*, not a glob. And you can specify options multiple times. Multiple `-d` options will be added together, but only the last `-o` option will be used. |
1,053,207 | I know that the reason that Microsoft came out with ASP.NET MVC was to make it simpler to do Test Driven Design (TDD) for ASP.NET. However, I have a rather large brown field (existing) application in ASP.NET WebForms that I would love to implement some TDD type functionality in. I'm assuming that there IS a way to do this, but what are some viable options? | 2009/06/27 | [
"https://Stackoverflow.com/questions/1053207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116620/"
] | Microsoft introduced ASP.NET MVC because they thought they could make money from an untapped market - those who feel that Web Forms are too "heavyweight", and who are programming using a lighter-weight framework. This includes those who are accustomed to the MVC paradigm.
It also includes those who couldn't figure out how to do unit tests in web forms, and who want to use unit tests and TDD.
The way to do it with web forms, as with anything else, is to separate everything but the UI code into separate classes in a class library. Use TDD to develop those classes.
The next layer of controversy is whether it's necessary to use TDD to develop the remainder of the code: the markup, client-side code, user interactions, etc. My answer is that if you've got the rest isolated and tested, that it's not worth the trouble to use TDD for this.
Consider: your pages need to have a particular appearance. Are you going to write a failing unit test to prove that you are using CSS correctly? To prove that you're using the correct CSS styles? I don't think so.
---
To clarify: In TDD, we start with a failing unit test. We then make the simplest possible changes that will make the test succeed.
Imagine using TDD for a web page. What failing tests will you produce?
1. Test that page is well-formed HTML
2. Test that page includes the correct title
3. Test that page includes
1. "Enter ID" label
2. An id textbox
3. A data grid
4. A "Go" button
4. Test that data grid is empty after a GET
5. Test that grid loads with data from customer 1 when "1" is entered into the text box and "Go" is clicked.
And none of the above tests for the appearance of the page. None of it tests the client-side behavior of any JavaScript on the page.
I think that's silly. Instead, test your DAL method that retrieves data based on the ID. Make sure it returns the correct ID for id 1. Then, how long will it take to manually test the page to make sure it looks correct, you can enter the "1" and click "Go", and that the data that appears in the grid is the correct data for customer 1?
Test-Driven Development and automated unit tests are meant to test behavior. The UI of a web form is mostly declarative. There's a large "impedance mismatch" here. | You can run HTTP-based tests to test the high level functionality. The best thing would be to encapsulate code-behind code into your business layer and run unit tests on it. |
1,053,207 | I know that the reason that Microsoft came out with ASP.NET MVC was to make it simpler to do Test Driven Design (TDD) for ASP.NET. However, I have a rather large brown field (existing) application in ASP.NET WebForms that I would love to implement some TDD type functionality in. I'm assuming that there IS a way to do this, but what are some viable options? | 2009/06/27 | [
"https://Stackoverflow.com/questions/1053207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116620/"
] | First of all, its really hard to test WebForms. But if you break out logic to Controllers/Presenters like the MVC/MVP pattern you can at least test the presenters.
Pseudo-code
Default.aspx
```
public void Page_Init(object sender, EventArgs e) {
_presenter = new DefaultPresenter(IDependencyOne, IDependencyTwo etc) //Init new presenter, either from IoC container of choose or "new-it-up"
}
public void Save() {
_presenter.Save(txtValue.Text)
}
```
Than you can easily test the presenter in isolation at least =) | You can run HTTP-based tests to test the high level functionality. The best thing would be to encapsulate code-behind code into your business layer and run unit tests on it. |
1,053,207 | I know that the reason that Microsoft came out with ASP.NET MVC was to make it simpler to do Test Driven Design (TDD) for ASP.NET. However, I have a rather large brown field (existing) application in ASP.NET WebForms that I would love to implement some TDD type functionality in. I'm assuming that there IS a way to do this, but what are some viable options? | 2009/06/27 | [
"https://Stackoverflow.com/questions/1053207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116620/"
] | Microsoft introduced ASP.NET MVC because they thought they could make money from an untapped market - those who feel that Web Forms are too "heavyweight", and who are programming using a lighter-weight framework. This includes those who are accustomed to the MVC paradigm.
It also includes those who couldn't figure out how to do unit tests in web forms, and who want to use unit tests and TDD.
The way to do it with web forms, as with anything else, is to separate everything but the UI code into separate classes in a class library. Use TDD to develop those classes.
The next layer of controversy is whether it's necessary to use TDD to develop the remainder of the code: the markup, client-side code, user interactions, etc. My answer is that if you've got the rest isolated and tested, that it's not worth the trouble to use TDD for this.
Consider: your pages need to have a particular appearance. Are you going to write a failing unit test to prove that you are using CSS correctly? To prove that you're using the correct CSS styles? I don't think so.
---
To clarify: In TDD, we start with a failing unit test. We then make the simplest possible changes that will make the test succeed.
Imagine using TDD for a web page. What failing tests will you produce?
1. Test that page is well-formed HTML
2. Test that page includes the correct title
3. Test that page includes
1. "Enter ID" label
2. An id textbox
3. A data grid
4. A "Go" button
4. Test that data grid is empty after a GET
5. Test that grid loads with data from customer 1 when "1" is entered into the text box and "Go" is clicked.
And none of the above tests for the appearance of the page. None of it tests the client-side behavior of any JavaScript on the page.
I think that's silly. Instead, test your DAL method that retrieves data based on the ID. Make sure it returns the correct ID for id 1. Then, how long will it take to manually test the page to make sure it looks correct, you can enter the "1" and click "Go", and that the data that appears in the grid is the correct data for customer 1?
Test-Driven Development and automated unit tests are meant to test behavior. The UI of a web form is mostly declarative. There's a large "impedance mismatch" here. | You can use the official Unittest Framework:
<http://msdn.microsoft.com/en-us/library/ms182526.aspx> |
1,053,207 | I know that the reason that Microsoft came out with ASP.NET MVC was to make it simpler to do Test Driven Design (TDD) for ASP.NET. However, I have a rather large brown field (existing) application in ASP.NET WebForms that I would love to implement some TDD type functionality in. I'm assuming that there IS a way to do this, but what are some viable options? | 2009/06/27 | [
"https://Stackoverflow.com/questions/1053207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116620/"
] | Microsoft introduced ASP.NET MVC because they thought they could make money from an untapped market - those who feel that Web Forms are too "heavyweight", and who are programming using a lighter-weight framework. This includes those who are accustomed to the MVC paradigm.
It also includes those who couldn't figure out how to do unit tests in web forms, and who want to use unit tests and TDD.
The way to do it with web forms, as with anything else, is to separate everything but the UI code into separate classes in a class library. Use TDD to develop those classes.
The next layer of controversy is whether it's necessary to use TDD to develop the remainder of the code: the markup, client-side code, user interactions, etc. My answer is that if you've got the rest isolated and tested, that it's not worth the trouble to use TDD for this.
Consider: your pages need to have a particular appearance. Are you going to write a failing unit test to prove that you are using CSS correctly? To prove that you're using the correct CSS styles? I don't think so.
---
To clarify: In TDD, we start with a failing unit test. We then make the simplest possible changes that will make the test succeed.
Imagine using TDD for a web page. What failing tests will you produce?
1. Test that page is well-formed HTML
2. Test that page includes the correct title
3. Test that page includes
1. "Enter ID" label
2. An id textbox
3. A data grid
4. A "Go" button
4. Test that data grid is empty after a GET
5. Test that grid loads with data from customer 1 when "1" is entered into the text box and "Go" is clicked.
And none of the above tests for the appearance of the page. None of it tests the client-side behavior of any JavaScript on the page.
I think that's silly. Instead, test your DAL method that retrieves data based on the ID. Make sure it returns the correct ID for id 1. Then, how long will it take to manually test the page to make sure it looks correct, you can enter the "1" and click "Go", and that the data that appears in the grid is the correct data for customer 1?
Test-Driven Development and automated unit tests are meant to test behavior. The UI of a web form is mostly declarative. There's a large "impedance mismatch" here. | First of all, its really hard to test WebForms. But if you break out logic to Controllers/Presenters like the MVC/MVP pattern you can at least test the presenters.
Pseudo-code
Default.aspx
```
public void Page_Init(object sender, EventArgs e) {
_presenter = new DefaultPresenter(IDependencyOne, IDependencyTwo etc) //Init new presenter, either from IoC container of choose or "new-it-up"
}
public void Save() {
_presenter.Save(txtValue.Text)
}
```
Than you can easily test the presenter in isolation at least =) |
1,053,207 | I know that the reason that Microsoft came out with ASP.NET MVC was to make it simpler to do Test Driven Design (TDD) for ASP.NET. However, I have a rather large brown field (existing) application in ASP.NET WebForms that I would love to implement some TDD type functionality in. I'm assuming that there IS a way to do this, but what are some viable options? | 2009/06/27 | [
"https://Stackoverflow.com/questions/1053207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116620/"
] | First of all, its really hard to test WebForms. But if you break out logic to Controllers/Presenters like the MVC/MVP pattern you can at least test the presenters.
Pseudo-code
Default.aspx
```
public void Page_Init(object sender, EventArgs e) {
_presenter = new DefaultPresenter(IDependencyOne, IDependencyTwo etc) //Init new presenter, either from IoC container of choose or "new-it-up"
}
public void Save() {
_presenter.Save(txtValue.Text)
}
```
Than you can easily test the presenter in isolation at least =) | You can use the official Unittest Framework:
<http://msdn.microsoft.com/en-us/library/ms182526.aspx> |
27,610,422 | If i recall correctly there used to be a third party library that upon device shake would allow the user to record the app ui and send feedback to the developers. Unfortunately my Google-fu is weak and i cant find it. Anyone know what I'm talking about? | 2014/12/22 | [
"https://Stackoverflow.com/questions/27610422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/481983/"
] | There are some tools that are exactly what you are looking at:
* Instabug (<http://instabug.com>)
* Flurry (<http://www.flurry.com>)
* Crashlytics (<http://try.crashlytics.com/sdk/>)
* Test Flight (<https://www.testflightapp.com>)
* PLCrashReporter (<https://www.plcrashreporter.org/>)
* BlitFeedback (<http://www.blitfeedback.com>)
* BugClipper (<http://www.bugclipper.com>)
* Glazum (<https://www.glazum.com>)
* Crittercism (<http://www.crittercism.com>)
* Tattle-UI-iOS (<https://github.com/npctech/Tattle-UI-iOS>)
* User Voice (<https://www.uservoice.com/mobile/>)
* AppHance (<http://apphance.com>)
That's all I know of at the moment. | Don't know if it does video, but [Telerik's AppFeedback](http://www.telerik.com/appfeedback#shake-point-and-comment) does incorporate the shake gesture, and capture of screenshots. |
124,972 | I want to switch some 12V landscape light LEDs, totaling about 5 watts, using MOSFETs, with the control signal provided by a digital output line from an Arduino microcontroller running at 5V.
I thought I had some logic level N-Channel MOSFETs lying around, but apparently not.
What I have is several 400N80Z and IRLB8721PBF power MOSFETS. I tried using the 400N80Z in m circuit, but the LEDs don't light fully.
I have a variety of low to medium power NPN and PNP switching transistors on hand (BC33716, PN2222A, and 2N4401 NPNs, various others, plus a few TIP120 NPN power darlingtons.
Clearly logic MOSFETs are the right tool for the job and I need to order some. In the meantime, though, can I rig up a circuit that will fully saturate one of my power MOSFETs with a 5V CMOS logic signal from an Arduino?
I'm a software guy, and only passingly familiar with analog circuits. | 2014/08/13 | [
"https://electronics.stackexchange.com/questions/124972",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/46155/"
] | The FCPF400N80Z has a maximum gate threshold voltage (VGS(th)) of 4.5V, which is marginal for logic operation, but the IRLB8721PbF has a maximum threshold voltage of 2.35V. This should work decently well for even 3.3V logic provided you don't need to pass more than about 3A of current. | Since you already have it on hand, you may use TIP120 NPN power darlingtons which is rated at 5A as Adafruit [TIP120 data sheet](http://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&sqi=2&ved=0CDQQFjAA&url=http%3A%2F%2Fwww.adafruit.com%2Fdatasheets%2FTIP120.pdf&ei=HuLqU-2aJ4_yoATqyICwBg&usg=AFQjCNFtfNslmI-Ccdi5Sdn3B71HoEfwdA&bvm=bv.72938740,d.cGU&cad=rja). Note, in data sheet max. 5A us 'infinite heat sink', refers to case temperature at 25 (or similar) degrees centigrade. Practical heat sink give about half current rating.
1 watt LED is about 300 to 350mA. For 5 watts, one transistors with good size heat sink is enough. Spread to two is better for added safety margin by keeping current to 1A. If individual LED is used, 2 or 3 LED (depends on color, voltage) can be connected in series, so the total current is kept low.
Connect Base with 300 ohms resistor to one of the digital output pin to drive about 10mA into the transistor. E to ground. C to LED, resistor (matching current rating of LED) to positive power. To reduce current, rise efficency by reducing heat loss in current limiting resistor, multiple LED can be connected in series (one LED is 2 to 4V, depends on color). Data sheet,figure 2, Vce Sat is 0.6 volt at 1A Ic, which is good for 2 to 3 LED in parallel (1W LED is 300 to 350mA).
As original poster mention 'right tool', transistor is suitable/usable (have not check price for this one to see if it is 'best solution') and have been working well for decades in application like this one, at a few watts. MOSFET has added advantage of small heat sink requirement, especially more significant in much higher power applications. |
124,972 | I want to switch some 12V landscape light LEDs, totaling about 5 watts, using MOSFETs, with the control signal provided by a digital output line from an Arduino microcontroller running at 5V.
I thought I had some logic level N-Channel MOSFETs lying around, but apparently not.
What I have is several 400N80Z and IRLB8721PBF power MOSFETS. I tried using the 400N80Z in m circuit, but the LEDs don't light fully.
I have a variety of low to medium power NPN and PNP switching transistors on hand (BC33716, PN2222A, and 2N4401 NPNs, various others, plus a few TIP120 NPN power darlingtons.
Clearly logic MOSFETs are the right tool for the job and I need to order some. In the meantime, though, can I rig up a circuit that will fully saturate one of my power MOSFETs with a 5V CMOS logic signal from an Arduino?
I'm a software guy, and only passingly familiar with analog circuits. | 2014/08/13 | [
"https://electronics.stackexchange.com/questions/124972",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/46155/"
] | The FCPF400N80Z has a maximum gate threshold voltage (VGS(th)) of 4.5V, which is marginal for logic operation, but the IRLB8721PbF has a maximum threshold voltage of 2.35V. This should work decently well for even 3.3V logic provided you don't need to pass more than about 3A of current. | When being bitten by the threshold voltage, an option is introducing a simple voltage amplification stage using a NPN BJT. You power your load from 12V, so you can use that voltage to pull the MOSFET's gate up to a level much higher than the logic level.
Basically what happens is the gate is pulled up to 12V unless the BJT is forcing the gate down to ground. The first stage inverts the behavior of the whole power switch, but that should be easy to solve in software of the controller.

[simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fY9CtZ.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/)
Advantage of this circuit is that it barely loads the controller output, only about 0.5mA is drawn from the output pin.
Disadvantage is that you have to route the +12V to the output stage, just for pulling up the gate. When you use a long lead from power supply to the buffer stage, you should decouple the power supply locally with a small (order magnitude) 100nF capacitor. |
124,972 | I want to switch some 12V landscape light LEDs, totaling about 5 watts, using MOSFETs, with the control signal provided by a digital output line from an Arduino microcontroller running at 5V.
I thought I had some logic level N-Channel MOSFETs lying around, but apparently not.
What I have is several 400N80Z and IRLB8721PBF power MOSFETS. I tried using the 400N80Z in m circuit, but the LEDs don't light fully.
I have a variety of low to medium power NPN and PNP switching transistors on hand (BC33716, PN2222A, and 2N4401 NPNs, various others, plus a few TIP120 NPN power darlingtons.
Clearly logic MOSFETs are the right tool for the job and I need to order some. In the meantime, though, can I rig up a circuit that will fully saturate one of my power MOSFETs with a 5V CMOS logic signal from an Arduino?
I'm a software guy, and only passingly familiar with analog circuits. | 2014/08/13 | [
"https://electronics.stackexchange.com/questions/124972",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/46155/"
] | When being bitten by the threshold voltage, an option is introducing a simple voltage amplification stage using a NPN BJT. You power your load from 12V, so you can use that voltage to pull the MOSFET's gate up to a level much higher than the logic level.
Basically what happens is the gate is pulled up to 12V unless the BJT is forcing the gate down to ground. The first stage inverts the behavior of the whole power switch, but that should be easy to solve in software of the controller.

[simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fY9CtZ.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/)
Advantage of this circuit is that it barely loads the controller output, only about 0.5mA is drawn from the output pin.
Disadvantage is that you have to route the +12V to the output stage, just for pulling up the gate. When you use a long lead from power supply to the buffer stage, you should decouple the power supply locally with a small (order magnitude) 100nF capacitor. | Since you already have it on hand, you may use TIP120 NPN power darlingtons which is rated at 5A as Adafruit [TIP120 data sheet](http://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&sqi=2&ved=0CDQQFjAA&url=http%3A%2F%2Fwww.adafruit.com%2Fdatasheets%2FTIP120.pdf&ei=HuLqU-2aJ4_yoATqyICwBg&usg=AFQjCNFtfNslmI-Ccdi5Sdn3B71HoEfwdA&bvm=bv.72938740,d.cGU&cad=rja). Note, in data sheet max. 5A us 'infinite heat sink', refers to case temperature at 25 (or similar) degrees centigrade. Practical heat sink give about half current rating.
1 watt LED is about 300 to 350mA. For 5 watts, one transistors with good size heat sink is enough. Spread to two is better for added safety margin by keeping current to 1A. If individual LED is used, 2 or 3 LED (depends on color, voltage) can be connected in series, so the total current is kept low.
Connect Base with 300 ohms resistor to one of the digital output pin to drive about 10mA into the transistor. E to ground. C to LED, resistor (matching current rating of LED) to positive power. To reduce current, rise efficency by reducing heat loss in current limiting resistor, multiple LED can be connected in series (one LED is 2 to 4V, depends on color). Data sheet,figure 2, Vce Sat is 0.6 volt at 1A Ic, which is good for 2 to 3 LED in parallel (1W LED is 300 to 350mA).
As original poster mention 'right tool', transistor is suitable/usable (have not check price for this one to see if it is 'best solution') and have been working well for decades in application like this one, at a few watts. MOSFET has added advantage of small heat sink requirement, especially more significant in much higher power applications. |
25,541 | I have been wondering about why [oxyhydrogen (HHO)](https://en.wikipedia.org/wiki/Oxyhydrogen), which is a ~2:1 H2/O2 stoichiometric mixture, hasn't been used as a fuel? I know it has been used for bottle rockets and other types of small scale rockets, and I know hydrogen and oxygen have been used as fuel (like in the delta IV) but could it be used for a large scale rocket? Would there be any problems with just one fuel tank holding both the oxidizer and fuel (maybe
it would be dangerous to keep them together?) Would there be any changes needed to engines to use HHO as a fuel? | 2018/02/20 | [
"https://space.stackexchange.com/questions/25541",
"https://space.stackexchange.com",
"https://space.stackexchange.com/users/22496/"
] | Oxyhydrogen is an extremely bad idea for a fuel. It is highly explosive, and too dangerous to be used on rockets.
But rockets today do use liquid hydrogen as fuel which is oxidized by liquid oxygen(Lox/LH2) as it is cheap and provides extremely high thrust and can be controlled to burn steadily. It is one of the most powerful liquid propellants.It also yields the highest specific impulse of any currently used rocket propellant. | Oxyhydrogen is not fuel in the strict sense of that term. Instead, it is an explosive mixture, made from stoichiometric proportions of fuel and oxidizer. As such, it could theoretically be used in reciprocating internal combustion (IC) engines, like those used in cars. These engines normally use explosive mixtures made of atomized fuel droplets finely dispersed in atmospheric air, but note how this mixture is prepared *in situ* and utilized immediately afterwards. It is partly due to technical reasons, as car fuel usually tends to be liquid in room temperature and solid in temperature of oxygen's boiling point, and it would make no sense to attempt storing an aerosol of fuel droplets nor reinforce ordinary car engines enough to withstand pressures needed to contain liquid oxygen in room temperature.
Nonetheless, even if it was technically possible to do in cars, it would not be done because such a car would be a horribly dangerous piece of equipment presenting perpetual explosion risk, potentially lethal to anyone within the radius of several dozens of meters. Absolutely unacceptable from the public safety's viewpoint, and the driver surely would also not appreciate having to operate a vehicle that was actually a ticking explosive device in disguise, a structure straight from the forbidden chapter of civil engineer's handbook. I'm half kidding, of course, as some currently-in-use solutions are honestly not that much better. Not only that, but HHO mixture does not deflagrate: it detonates instead, and that is highly undesirable in car combustion engine. Not only it wastes energy, but damages the engine as well. That phenomenon is named *engine knocking*, and to put things in perspective about how undesirable it is, certain individuals in the past, about whom I cannot find enough rotten things to say about, had come into conclusion that [contaminating our entire environment with a neurotoxic heavy metal is a reasonable price to pay for preventing that phenomenon from happening in car engines](https://en.wikipedia.org/wiki/Tetraethyllead). Yikes.
However, rocket engines operate differently than those of cars. While most of them are also classified as IC engines, the are not reciprocating IC engines but continuous combustion IC engines. Instead of going through intermittently periodic cycle of igniting an explosive mixture of fuel and oxidizer inside a chamber, and then harnessing the power of said explosion to force a piston downward in engine's cylinder, rocket engines harness the thermal energy released by combustion; the resulting pressure in the combustion chamber is converted to thrust by ejecting the combustion products through the nozzle, according to the recoil principle.
In case of HHO, it is reasonable to assume what you imagine was a monopropellant engine. Continuous combustion makes it somewhat more troubling for HHO to be used in this context, because as mentioned, it is an explosive: once ignited, this mixture does not really combust, but outright detonates. That's wonderful if you want to perform a demolition or break rocks for an excavation, but not if you want to cleanly and relatively safely generate thrust. That is difficult to control, and you surely need to be able to control that in order to finely tune the thrust generated by engine and throttle the engine if needed.
Let's compare HHO to other monopropellant, like hydrogen peroxide. Water solutions of hydrogen peroxide in concentrations higher than 68% are also explosive, potentially being able to be exothermically converted entirely into hot water vapor and oxygen. However, it is possible to localize where the decomposition happens by the use of a catalyst bed. It facilitates controlled decomposition that could be regulated, and thus allows you to throttle the engine if needed.
On the other hand, in case of HHO engine I cannot possibly imagine how one could safely localize the the reaction. Any potential flashback would go back inside the fuel storage chamber -- and have in mind that the velocity of detonation front of HHO gas is around 1.8 to 3.8 km/s. Once a flashback happens and does not get arrested before reaching the fuel tank, your whole remaining amount of fuel would release its energy all at once, ripping the whole rocket apart.
[Here is a video of NightHawkInLight building and using a HHO torch](https://www.youtube.com/watch?v=7M4yqcO_pPo). WARNING: this is extremely dangerous, absolutely do not attempt recreating that yourself! In his setup, he uses a thin metal nozzle made of a syringe with a needle of miniscule diameter (0.6 mm) to increase the velocity of gas flow in order to prevent flashbacks. The metal nozzle also serves as a radiator, facilitating the dissipation of flame's heat and thus slowing down the potential backward movement of the flame front; he has also stuffed some aluminium wool into the syringe to further facilitate heat dissipation in order to reduce the chances of flashbacks. Nonetheless, he still uses two separate flashback arrestors, wears goggles, stores the HHO producing unit in a metal cage, and uses a steel sheet to shield himself from it. He also happens to have committed a big whoopsie, as he appears to be using stainless steel electrodes for water electrolysis. Stainless steel generally should not be used for aqueous electrolysis because it contains a significant fraction of chromium which, depending on the electrolytic cell's pH and voltage, could potentially get oxidized on the anode to the highly toxic, carcinogenic, and corrosive Cr(VI) form ([hexavalent chromium](https://en.wikipedia.org/wiki/Hexavalent_chromium)), namely chromate and dichromate anions: $\text{CrO}^{2-}\_{4}$ and $\text{Cr}\_{2}\text{O}^{2-}\_{7}$. Any solutions containing Cr(VI) are extremely harmful to the environment with long lasting effects and cannot be disposed of by pouring them down the drain; one needs to give them to a chemical waste company and pay a fee to have such solutions properly and safely disposed of. Do not recreate; not only you could potentially produce volumes of hazardous waste in the form of forbidden cancer juice, but if anything goes wrong, you may also go blind, deaf, or even end up being stuck sniffing flowers from below the ground.
That is why HHO is not used as fuel. It is inherently dangerous to store any non-trivial amount of oxyhydrogen gas for extended periods. |
25,541 | I have been wondering about why [oxyhydrogen (HHO)](https://en.wikipedia.org/wiki/Oxyhydrogen), which is a ~2:1 H2/O2 stoichiometric mixture, hasn't been used as a fuel? I know it has been used for bottle rockets and other types of small scale rockets, and I know hydrogen and oxygen have been used as fuel (like in the delta IV) but could it be used for a large scale rocket? Would there be any problems with just one fuel tank holding both the oxidizer and fuel (maybe
it would be dangerous to keep them together?) Would there be any changes needed to engines to use HHO as a fuel? | 2018/02/20 | [
"https://space.stackexchange.com/questions/25541",
"https://space.stackexchange.com",
"https://space.stackexchange.com/users/22496/"
] | Oxyhydrogen is an extremely bad idea for a fuel. It is highly explosive, and too dangerous to be used on rockets.
But rockets today do use liquid hydrogen as fuel which is oxidized by liquid oxygen(Lox/LH2) as it is cheap and provides extremely high thrust and can be controlled to burn steadily. It is one of the most powerful liquid propellants.It also yields the highest specific impulse of any currently used rocket propellant. | HHO mixture. Energy per gram: 112KJ.
TNT. Energy per gram: 4KJ.
A HHO mixture contains everything it needs to combust, all tightly packed together. We generally call such materials explosives.
Furthermore, you've got a big storage problem. The melting point of oxygen is far above the critical point of hydrogen, no liquid can exist.
We already have an example that approximates HHO as a gas: A potato cannon. It's far more powerful with HHO than the normal hydrocarbon in air, but it still doesn't have enough energy to be a useful rocket.
That leaves solid. Below 14K you can have solid HHO but you have nothing to moderate the burn, you would get a mushroom cloud, not a space flight.
In practice hydrolox engines don't mix them until they enter the combustion chamber. It means two pumps and two tanks but it will actually get you up there. |
25,541 | I have been wondering about why [oxyhydrogen (HHO)](https://en.wikipedia.org/wiki/Oxyhydrogen), which is a ~2:1 H2/O2 stoichiometric mixture, hasn't been used as a fuel? I know it has been used for bottle rockets and other types of small scale rockets, and I know hydrogen and oxygen have been used as fuel (like in the delta IV) but could it be used for a large scale rocket? Would there be any problems with just one fuel tank holding both the oxidizer and fuel (maybe
it would be dangerous to keep them together?) Would there be any changes needed to engines to use HHO as a fuel? | 2018/02/20 | [
"https://space.stackexchange.com/questions/25541",
"https://space.stackexchange.com",
"https://space.stackexchange.com/users/22496/"
] | Oxyhydrogen is an extremely bad idea for a fuel. It is highly explosive, and too dangerous to be used on rockets.
But rockets today do use liquid hydrogen as fuel which is oxidized by liquid oxygen(Lox/LH2) as it is cheap and provides extremely high thrust and can be controlled to burn steadily. It is one of the most powerful liquid propellants.It also yields the highest specific impulse of any currently used rocket propellant. | Why could you not produce your HHO and use it directly into a Pulse detonation engine. Small quantities of HHO gas could be stored at low pressure in an on demand system then Maybe pumped to the fuel injector then pulse timed by the injector with a spark delay time. The outlet would require a valve at the outlet to stop the reverse flow of air caused by the vacuum caused by the hho to water explosion. Flash back arrestors and bubblers use of course. |
25,541 | I have been wondering about why [oxyhydrogen (HHO)](https://en.wikipedia.org/wiki/Oxyhydrogen), which is a ~2:1 H2/O2 stoichiometric mixture, hasn't been used as a fuel? I know it has been used for bottle rockets and other types of small scale rockets, and I know hydrogen and oxygen have been used as fuel (like in the delta IV) but could it be used for a large scale rocket? Would there be any problems with just one fuel tank holding both the oxidizer and fuel (maybe
it would be dangerous to keep them together?) Would there be any changes needed to engines to use HHO as a fuel? | 2018/02/20 | [
"https://space.stackexchange.com/questions/25541",
"https://space.stackexchange.com",
"https://space.stackexchange.com/users/22496/"
] | Oxyhydrogen is not fuel in the strict sense of that term. Instead, it is an explosive mixture, made from stoichiometric proportions of fuel and oxidizer. As such, it could theoretically be used in reciprocating internal combustion (IC) engines, like those used in cars. These engines normally use explosive mixtures made of atomized fuel droplets finely dispersed in atmospheric air, but note how this mixture is prepared *in situ* and utilized immediately afterwards. It is partly due to technical reasons, as car fuel usually tends to be liquid in room temperature and solid in temperature of oxygen's boiling point, and it would make no sense to attempt storing an aerosol of fuel droplets nor reinforce ordinary car engines enough to withstand pressures needed to contain liquid oxygen in room temperature.
Nonetheless, even if it was technically possible to do in cars, it would not be done because such a car would be a horribly dangerous piece of equipment presenting perpetual explosion risk, potentially lethal to anyone within the radius of several dozens of meters. Absolutely unacceptable from the public safety's viewpoint, and the driver surely would also not appreciate having to operate a vehicle that was actually a ticking explosive device in disguise, a structure straight from the forbidden chapter of civil engineer's handbook. I'm half kidding, of course, as some currently-in-use solutions are honestly not that much better. Not only that, but HHO mixture does not deflagrate: it detonates instead, and that is highly undesirable in car combustion engine. Not only it wastes energy, but damages the engine as well. That phenomenon is named *engine knocking*, and to put things in perspective about how undesirable it is, certain individuals in the past, about whom I cannot find enough rotten things to say about, had come into conclusion that [contaminating our entire environment with a neurotoxic heavy metal is a reasonable price to pay for preventing that phenomenon from happening in car engines](https://en.wikipedia.org/wiki/Tetraethyllead). Yikes.
However, rocket engines operate differently than those of cars. While most of them are also classified as IC engines, the are not reciprocating IC engines but continuous combustion IC engines. Instead of going through intermittently periodic cycle of igniting an explosive mixture of fuel and oxidizer inside a chamber, and then harnessing the power of said explosion to force a piston downward in engine's cylinder, rocket engines harness the thermal energy released by combustion; the resulting pressure in the combustion chamber is converted to thrust by ejecting the combustion products through the nozzle, according to the recoil principle.
In case of HHO, it is reasonable to assume what you imagine was a monopropellant engine. Continuous combustion makes it somewhat more troubling for HHO to be used in this context, because as mentioned, it is an explosive: once ignited, this mixture does not really combust, but outright detonates. That's wonderful if you want to perform a demolition or break rocks for an excavation, but not if you want to cleanly and relatively safely generate thrust. That is difficult to control, and you surely need to be able to control that in order to finely tune the thrust generated by engine and throttle the engine if needed.
Let's compare HHO to other monopropellant, like hydrogen peroxide. Water solutions of hydrogen peroxide in concentrations higher than 68% are also explosive, potentially being able to be exothermically converted entirely into hot water vapor and oxygen. However, it is possible to localize where the decomposition happens by the use of a catalyst bed. It facilitates controlled decomposition that could be regulated, and thus allows you to throttle the engine if needed.
On the other hand, in case of HHO engine I cannot possibly imagine how one could safely localize the the reaction. Any potential flashback would go back inside the fuel storage chamber -- and have in mind that the velocity of detonation front of HHO gas is around 1.8 to 3.8 km/s. Once a flashback happens and does not get arrested before reaching the fuel tank, your whole remaining amount of fuel would release its energy all at once, ripping the whole rocket apart.
[Here is a video of NightHawkInLight building and using a HHO torch](https://www.youtube.com/watch?v=7M4yqcO_pPo). WARNING: this is extremely dangerous, absolutely do not attempt recreating that yourself! In his setup, he uses a thin metal nozzle made of a syringe with a needle of miniscule diameter (0.6 mm) to increase the velocity of gas flow in order to prevent flashbacks. The metal nozzle also serves as a radiator, facilitating the dissipation of flame's heat and thus slowing down the potential backward movement of the flame front; he has also stuffed some aluminium wool into the syringe to further facilitate heat dissipation in order to reduce the chances of flashbacks. Nonetheless, he still uses two separate flashback arrestors, wears goggles, stores the HHO producing unit in a metal cage, and uses a steel sheet to shield himself from it. He also happens to have committed a big whoopsie, as he appears to be using stainless steel electrodes for water electrolysis. Stainless steel generally should not be used for aqueous electrolysis because it contains a significant fraction of chromium which, depending on the electrolytic cell's pH and voltage, could potentially get oxidized on the anode to the highly toxic, carcinogenic, and corrosive Cr(VI) form ([hexavalent chromium](https://en.wikipedia.org/wiki/Hexavalent_chromium)), namely chromate and dichromate anions: $\text{CrO}^{2-}\_{4}$ and $\text{Cr}\_{2}\text{O}^{2-}\_{7}$. Any solutions containing Cr(VI) are extremely harmful to the environment with long lasting effects and cannot be disposed of by pouring them down the drain; one needs to give them to a chemical waste company and pay a fee to have such solutions properly and safely disposed of. Do not recreate; not only you could potentially produce volumes of hazardous waste in the form of forbidden cancer juice, but if anything goes wrong, you may also go blind, deaf, or even end up being stuck sniffing flowers from below the ground.
That is why HHO is not used as fuel. It is inherently dangerous to store any non-trivial amount of oxyhydrogen gas for extended periods. | HHO mixture. Energy per gram: 112KJ.
TNT. Energy per gram: 4KJ.
A HHO mixture contains everything it needs to combust, all tightly packed together. We generally call such materials explosives.
Furthermore, you've got a big storage problem. The melting point of oxygen is far above the critical point of hydrogen, no liquid can exist.
We already have an example that approximates HHO as a gas: A potato cannon. It's far more powerful with HHO than the normal hydrocarbon in air, but it still doesn't have enough energy to be a useful rocket.
That leaves solid. Below 14K you can have solid HHO but you have nothing to moderate the burn, you would get a mushroom cloud, not a space flight.
In practice hydrolox engines don't mix them until they enter the combustion chamber. It means two pumps and two tanks but it will actually get you up there. |
25,541 | I have been wondering about why [oxyhydrogen (HHO)](https://en.wikipedia.org/wiki/Oxyhydrogen), which is a ~2:1 H2/O2 stoichiometric mixture, hasn't been used as a fuel? I know it has been used for bottle rockets and other types of small scale rockets, and I know hydrogen and oxygen have been used as fuel (like in the delta IV) but could it be used for a large scale rocket? Would there be any problems with just one fuel tank holding both the oxidizer and fuel (maybe
it would be dangerous to keep them together?) Would there be any changes needed to engines to use HHO as a fuel? | 2018/02/20 | [
"https://space.stackexchange.com/questions/25541",
"https://space.stackexchange.com",
"https://space.stackexchange.com/users/22496/"
] | Oxyhydrogen is not fuel in the strict sense of that term. Instead, it is an explosive mixture, made from stoichiometric proportions of fuel and oxidizer. As such, it could theoretically be used in reciprocating internal combustion (IC) engines, like those used in cars. These engines normally use explosive mixtures made of atomized fuel droplets finely dispersed in atmospheric air, but note how this mixture is prepared *in situ* and utilized immediately afterwards. It is partly due to technical reasons, as car fuel usually tends to be liquid in room temperature and solid in temperature of oxygen's boiling point, and it would make no sense to attempt storing an aerosol of fuel droplets nor reinforce ordinary car engines enough to withstand pressures needed to contain liquid oxygen in room temperature.
Nonetheless, even if it was technically possible to do in cars, it would not be done because such a car would be a horribly dangerous piece of equipment presenting perpetual explosion risk, potentially lethal to anyone within the radius of several dozens of meters. Absolutely unacceptable from the public safety's viewpoint, and the driver surely would also not appreciate having to operate a vehicle that was actually a ticking explosive device in disguise, a structure straight from the forbidden chapter of civil engineer's handbook. I'm half kidding, of course, as some currently-in-use solutions are honestly not that much better. Not only that, but HHO mixture does not deflagrate: it detonates instead, and that is highly undesirable in car combustion engine. Not only it wastes energy, but damages the engine as well. That phenomenon is named *engine knocking*, and to put things in perspective about how undesirable it is, certain individuals in the past, about whom I cannot find enough rotten things to say about, had come into conclusion that [contaminating our entire environment with a neurotoxic heavy metal is a reasonable price to pay for preventing that phenomenon from happening in car engines](https://en.wikipedia.org/wiki/Tetraethyllead). Yikes.
However, rocket engines operate differently than those of cars. While most of them are also classified as IC engines, the are not reciprocating IC engines but continuous combustion IC engines. Instead of going through intermittently periodic cycle of igniting an explosive mixture of fuel and oxidizer inside a chamber, and then harnessing the power of said explosion to force a piston downward in engine's cylinder, rocket engines harness the thermal energy released by combustion; the resulting pressure in the combustion chamber is converted to thrust by ejecting the combustion products through the nozzle, according to the recoil principle.
In case of HHO, it is reasonable to assume what you imagine was a monopropellant engine. Continuous combustion makes it somewhat more troubling for HHO to be used in this context, because as mentioned, it is an explosive: once ignited, this mixture does not really combust, but outright detonates. That's wonderful if you want to perform a demolition or break rocks for an excavation, but not if you want to cleanly and relatively safely generate thrust. That is difficult to control, and you surely need to be able to control that in order to finely tune the thrust generated by engine and throttle the engine if needed.
Let's compare HHO to other monopropellant, like hydrogen peroxide. Water solutions of hydrogen peroxide in concentrations higher than 68% are also explosive, potentially being able to be exothermically converted entirely into hot water vapor and oxygen. However, it is possible to localize where the decomposition happens by the use of a catalyst bed. It facilitates controlled decomposition that could be regulated, and thus allows you to throttle the engine if needed.
On the other hand, in case of HHO engine I cannot possibly imagine how one could safely localize the the reaction. Any potential flashback would go back inside the fuel storage chamber -- and have in mind that the velocity of detonation front of HHO gas is around 1.8 to 3.8 km/s. Once a flashback happens and does not get arrested before reaching the fuel tank, your whole remaining amount of fuel would release its energy all at once, ripping the whole rocket apart.
[Here is a video of NightHawkInLight building and using a HHO torch](https://www.youtube.com/watch?v=7M4yqcO_pPo). WARNING: this is extremely dangerous, absolutely do not attempt recreating that yourself! In his setup, he uses a thin metal nozzle made of a syringe with a needle of miniscule diameter (0.6 mm) to increase the velocity of gas flow in order to prevent flashbacks. The metal nozzle also serves as a radiator, facilitating the dissipation of flame's heat and thus slowing down the potential backward movement of the flame front; he has also stuffed some aluminium wool into the syringe to further facilitate heat dissipation in order to reduce the chances of flashbacks. Nonetheless, he still uses two separate flashback arrestors, wears goggles, stores the HHO producing unit in a metal cage, and uses a steel sheet to shield himself from it. He also happens to have committed a big whoopsie, as he appears to be using stainless steel electrodes for water electrolysis. Stainless steel generally should not be used for aqueous electrolysis because it contains a significant fraction of chromium which, depending on the electrolytic cell's pH and voltage, could potentially get oxidized on the anode to the highly toxic, carcinogenic, and corrosive Cr(VI) form ([hexavalent chromium](https://en.wikipedia.org/wiki/Hexavalent_chromium)), namely chromate and dichromate anions: $\text{CrO}^{2-}\_{4}$ and $\text{Cr}\_{2}\text{O}^{2-}\_{7}$. Any solutions containing Cr(VI) are extremely harmful to the environment with long lasting effects and cannot be disposed of by pouring them down the drain; one needs to give them to a chemical waste company and pay a fee to have such solutions properly and safely disposed of. Do not recreate; not only you could potentially produce volumes of hazardous waste in the form of forbidden cancer juice, but if anything goes wrong, you may also go blind, deaf, or even end up being stuck sniffing flowers from below the ground.
That is why HHO is not used as fuel. It is inherently dangerous to store any non-trivial amount of oxyhydrogen gas for extended periods. | Why could you not produce your HHO and use it directly into a Pulse detonation engine. Small quantities of HHO gas could be stored at low pressure in an on demand system then Maybe pumped to the fuel injector then pulse timed by the injector with a spark delay time. The outlet would require a valve at the outlet to stop the reverse flow of air caused by the vacuum caused by the hho to water explosion. Flash back arrestors and bubblers use of course. |
25,541 | I have been wondering about why [oxyhydrogen (HHO)](https://en.wikipedia.org/wiki/Oxyhydrogen), which is a ~2:1 H2/O2 stoichiometric mixture, hasn't been used as a fuel? I know it has been used for bottle rockets and other types of small scale rockets, and I know hydrogen and oxygen have been used as fuel (like in the delta IV) but could it be used for a large scale rocket? Would there be any problems with just one fuel tank holding both the oxidizer and fuel (maybe
it would be dangerous to keep them together?) Would there be any changes needed to engines to use HHO as a fuel? | 2018/02/20 | [
"https://space.stackexchange.com/questions/25541",
"https://space.stackexchange.com",
"https://space.stackexchange.com/users/22496/"
] | HHO mixture. Energy per gram: 112KJ.
TNT. Energy per gram: 4KJ.
A HHO mixture contains everything it needs to combust, all tightly packed together. We generally call such materials explosives.
Furthermore, you've got a big storage problem. The melting point of oxygen is far above the critical point of hydrogen, no liquid can exist.
We already have an example that approximates HHO as a gas: A potato cannon. It's far more powerful with HHO than the normal hydrocarbon in air, but it still doesn't have enough energy to be a useful rocket.
That leaves solid. Below 14K you can have solid HHO but you have nothing to moderate the burn, you would get a mushroom cloud, not a space flight.
In practice hydrolox engines don't mix them until they enter the combustion chamber. It means two pumps and two tanks but it will actually get you up there. | Why could you not produce your HHO and use it directly into a Pulse detonation engine. Small quantities of HHO gas could be stored at low pressure in an on demand system then Maybe pumped to the fuel injector then pulse timed by the injector with a spark delay time. The outlet would require a valve at the outlet to stop the reverse flow of air caused by the vacuum caused by the hho to water explosion. Flash back arrestors and bubblers use of course. |
12,361,475 | I'm a rookie in webpage development working on my first webpage. I wrote some `HTML` code in a text editor and saved it as an `HTML` file. However, when I open it in my browser, I only see the plain `HTML` text instead of the table. Can anyone help me with this?
The following is my code:
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
</HEAD>
<BODY>
<CENTER>
<TABLE border=2>
<CAPTION>My Homework</CAPTION>
<TR>
<TD>Link to Homework #1</TD>
<TD>Link to Homework #2</TD>
<TR>
<TD>Link to Homework #3</TD>
<TD>Link to Homework #4</TD>
<TR>
<TD>Link to Homework #5</TD>
<TD>Link to Homework #6</TD>
<TR>
<TD>Link to Homework #7</TD>
<TD>Link to Homework #8</TD>
</TABLE>
</CENTER>
</BODY>
</HTML>
``` | 2012/09/11 | [
"https://Stackoverflow.com/questions/12361475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1132983/"
] | In addition to closing the `<TR>`'s with `</TR>`'s make sure you are saving the file with an extension that indicates it's an HTML file. page.html, page.htm etc.
So you are using TextEdit on Mac. Sounds like you might want to read [this](http://www.askdavetaylor.com/how_do_i_save_html_files_from_textedit.html) to ensure you are saving the file correctly. | What Andrew said is correct about proper HTML. But all browsers fix slightly broken HTML when they render the page.
From the sounds of the issue, i think you might have a file with 2 extensions e.g.: `test.html.txt`
Make sure in windows, you show **known file type extensions** and the file doesn't have a `.txt` (or any other extension besides `.htm` or `.html`) at the end of it. |
12,361,475 | I'm a rookie in webpage development working on my first webpage. I wrote some `HTML` code in a text editor and saved it as an `HTML` file. However, when I open it in my browser, I only see the plain `HTML` text instead of the table. Can anyone help me with this?
The following is my code:
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
</HEAD>
<BODY>
<CENTER>
<TABLE border=2>
<CAPTION>My Homework</CAPTION>
<TR>
<TD>Link to Homework #1</TD>
<TD>Link to Homework #2</TD>
<TR>
<TD>Link to Homework #3</TD>
<TD>Link to Homework #4</TD>
<TR>
<TD>Link to Homework #5</TD>
<TD>Link to Homework #6</TD>
<TR>
<TD>Link to Homework #7</TD>
<TD>Link to Homework #8</TD>
</TABLE>
</CENTER>
</BODY>
</HTML>
``` | 2012/09/11 | [
"https://Stackoverflow.com/questions/12361475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1132983/"
] | In addition to closing the `<TR>`'s with `</TR>`'s make sure you are saving the file with an extension that indicates it's an HTML file. page.html, page.htm etc.
So you are using TextEdit on Mac. Sounds like you might want to read [this](http://www.askdavetaylor.com/how_do_i_save_html_files_from_textedit.html) to ensure you are saving the file correctly. | The HTML editor you are using may be translating what you type in as HTML - that is, when you type <html> , it becomes something like: <html>
Try opening up the file is a simple text editor to see if this is happening. |
12,361,475 | I'm a rookie in webpage development working on my first webpage. I wrote some `HTML` code in a text editor and saved it as an `HTML` file. However, when I open it in my browser, I only see the plain `HTML` text instead of the table. Can anyone help me with this?
The following is my code:
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
</HEAD>
<BODY>
<CENTER>
<TABLE border=2>
<CAPTION>My Homework</CAPTION>
<TR>
<TD>Link to Homework #1</TD>
<TD>Link to Homework #2</TD>
<TR>
<TD>Link to Homework #3</TD>
<TD>Link to Homework #4</TD>
<TR>
<TD>Link to Homework #5</TD>
<TD>Link to Homework #6</TD>
<TR>
<TD>Link to Homework #7</TD>
<TD>Link to Homework #8</TD>
</TABLE>
</CENTER>
</BODY>
</HTML>
``` | 2012/09/11 | [
"https://Stackoverflow.com/questions/12361475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1132983/"
] | What Andrew said is correct about proper HTML. But all browsers fix slightly broken HTML when they render the page.
From the sounds of the issue, i think you might have a file with 2 extensions e.g.: `test.html.txt`
Make sure in windows, you show **known file type extensions** and the file doesn't have a `.txt` (or any other extension besides `.htm` or `.html`) at the end of it. | The HTML editor you are using may be translating what you type in as HTML - that is, when you type <html> , it becomes something like: <html>
Try opening up the file is a simple text editor to see if this is happening. |
24,605,224 | i'm creating an Xcode app and i need to create an `NSMutableArray` that gets initialized when my switch are on and when a switch is off the value assigned to the switch that was also assigned to the NSMutableArray gets destroyed from the Array, how the code should be? I already initialized my switch but i don't know how to add/destroy the values from the NSMUtableArray | 2014/07/07 | [
"https://Stackoverflow.com/questions/24605224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3789527/"
] | ```
i=i++
```
This is not the correct use to increment `i`.
What this does:
1. Variable `i` gets incremented by `++`.
2. Variable `i` gets assigned old value of `i`, as `i++` returns the old value of `i`.
So basically, you are stuck in an endless loop. Just replace `i=i++` with just `i++` or `i=i+1` or `i+=1` and you should be fine.
Looking at your code again, I have to tell you, that this will still not yield the desired effect, as you are setting all the intervals to fire at the same exact time. What you would want to do looks something like this:
```
function next() {
setInterval(function(){
//display next image
},3000);
next();
}
next();
```
Depending on how your html-code is build, the simplest way to implement this would be:
```
var count = 3; current = 0, img=document.getElementById("img1");
function next() {
setInterval(function(){
current++;
if(current >= count) {
current = 0;
}
img.src="Images/" + current + ".jpg";
},3000);
next();
}
next();
``` | With respect to your angle of code.. try the below one.
```
function call(){
var i=0;
setInterval(function(){
document.getElementById("pics").innerHTML="<img src='img"+i+".jpg' width=300 height=300 alt='image' /> ";
i++;
if(i>=3){
i= i%3;
}
},3000);
}
```
"pics" is a div tag declared in html page. |
23,477,566 | I have the following POCO:
```
public class Specialty
{
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime? CreatedDate { get; set; }
public string Description { get; set; }
public string Id { get; set; }
public string Name { get; set; }
}
```
In Configuration.cs's Seed Method, I have:
```
public override void Seed(MyContext context)
{
context.Specialties.AddOrUpdate(p => p.Name,
new Specialty { Id = Guid.NewGuid().ToString(),
Description = "Allergy and Immunology",
Name = "Allergy and Immunology" },
new Specialty { Id = Guid.NewGuid().ToString(),
Description = "Anaesthesiology",
Name = "Anaesthesiology" });
}
```
The migration "command" for this table:
```
CreateTable("dbo.Specialty",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
CreatedDate = c.DateTime(defaultValueSql: "GETDATE()"),
Description = c.String(),
Name = c.String(),
})
.PrimaryKey(t => t.Id);
```
So, in the Seed function, I purposely left out CreatedDate because I figured SQL would take care of populating this upon insertion because of my annotation (database generated, computed) and Migration setting `defaultValueSql: "GETDATE()"`.
I am getting that error "The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value." when I run Update-Database. To my knowledge, not specifying CreatedDate in the Seeding method will try to save a null CreatedDate into the database, which is going to be allowed. It seems like EF did something behind my back - what?
My guess is that EF forced DateTime.Now.Min or something which is out-of-range for the SQL datetime data type... but since I've specified database generated, shouldn't it stop EF from creating an out-of-range value for insert? | 2014/05/05 | [
"https://Stackoverflow.com/questions/23477566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1858308/"
] | I believe this answers your question. datetime2 does not allow DateTime.Min but DateTime does. The DateTime.min value is 00:00:00.0000000, January 1, 0001.
Link with details.
------------------
[Conversion of a datetime2 data type to a datetime data type results out-of-range value](https://stackoverflow.com/questions/1331779/c-sharp-conversion-of-a-datetime2-data-type-to-a-datetime-data-type) | The above, as posted actually works. However, we will get this error if:
1. We have a non-nullable DateTime property other than CreatedDate that we might have missed, and did not specify in the Seed method.
2. VERY EASY TO FORGET: If you created custom AspNet.Identity entities with custom properties, you may have put a non-nullable DateTime property in them, as was my case. |
70,368,725 | What GUI tool can I use to connect to Postgres RDS that is not publicly accessible? I have used pgAdmin earlier when the db was open but now that the RDS is not publicly accessible, is there a GUI-based tool that I can use to connect? Thanks. | 2021/12/15 | [
"https://Stackoverflow.com/questions/70368725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13531163/"
] | First, you are using `std::count()` incorrectly.
Second, `std::string_view` has its own [`find_first_of()`](https://en.cppreference.com/w/cpp/string/basic_string_view/find_first_of) and [`substr()`](https://en.cppreference.com/w/cpp/string/basic_string_view/substr) methods, which you can use in this situation, instead of using iterators. `find_first_of()` allows you to specify multiple characters to search for.
Try something more like this:
```cpp
size_t split(std::vector<std::string_view>& result, std::string_view in, std::string_view seps) {
result.reserve(std::count_if(in.begin(), in.end(), [&](char ch){ return seps.find(ch) != std::string_view::npos; }) + 1);
std::string_view::size_type start = 0, end;
while ((end = in.find_first_of(seps, start)) != std::string_view::npos) {
result.push_back(in.substr(start, end-start));
start = in.find_first_not_of(' ', end+1);
}
if (start != std::string_view::npos)
result.push_back(in.substr(start));
return result.size();
}
```
[Online Demo](https://onlinegdb.com/d8G4IrL6uI) | I do not know about performance, but this code seems a lot simpler
```
std::vector<std::string> ParseDelimited(
const std::string &l, char delim )
{
std::vector<std::string> token;
std::stringstream sst(l);
std::string a;
while (getline(sst, a, delim))
token.push_back(a);
return token;
}
``` |
70,368,725 | What GUI tool can I use to connect to Postgres RDS that is not publicly accessible? I have used pgAdmin earlier when the db was open but now that the RDS is not publicly accessible, is there a GUI-based tool that I can use to connect? Thanks. | 2021/12/15 | [
"https://Stackoverflow.com/questions/70368725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13531163/"
] | This is my take on splitting a string view, just loops once over all the characters in the string view and returns a vector of string\_views (so no copying of data)
The calling code can still use words.size() to get the size if needed.
(I use C++20 std::set contains function)
Live demo here : <https://onlinegdb.com/tHfPIeo1iM>
```
#include <iostream>
#include <set>
#include <string_view>
#include <vector>
auto split(const std::string_view& string, const std::set<char>& separators)
{
std::vector<std::string_view> words;
auto word_begin{ string.data() };
std::size_t word_len{ 0ul };
for (const auto& c : string)
{
if (!separators.contains(c))
{
word_len++;
}
else
{
// we found a word and not a seperator repeat
if (word_len > 0)
{
words.emplace_back(word_begin, word_len);
word_begin += word_len;
word_len = 0;
}
word_begin++;
}
}
// string_view doesn't have a trailing zero so
// also no trailing separator so if there is still
// a word in the "pipeline" add it too
if (word_len > 0)
{
words.emplace_back(word_begin, word_len);
}
return words;
}
int main()
{
std::set<char> seperators{ ' ', ',', '.', '!', '\n' };
auto words = split("apple, phone, bread\n keyboard, computer", seperators);
bool comma = false;
std::cout << "[";
for (const auto& word : words)
{
if (comma) std::cout << ", ";
std::cout << word;
comma = true;
}
std::cout << "]\n";
return 0;
}
``` | I do not know about performance, but this code seems a lot simpler
```
std::vector<std::string> ParseDelimited(
const std::string &l, char delim )
{
std::vector<std::string> token;
std::stringstream sst(l);
std::string a;
while (getline(sst, a, delim))
token.push_back(a);
return token;
}
``` |
5,167,712 | is there any way to change default shortcuts used by JTable? For instance I would like to change Home and End keys, so they would move to first/last row instead of first/last column.
Any way to do this? Thank you for help. | 2011/03/02 | [
"https://Stackoverflow.com/questions/5167712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/739927/"
] | There is no automatic trimming of data in Oracle, you have to trim it explicitly yourself e.g.
```
insert into mytable (id, text) values (123, substr(var,1,4000));
``` | Oracle does support a variety of SQL functions which trim variables. I suspect the one you'll want is 'SUBSTR()'. The problem is that you will need to specify the desired length explicitly. In this example T23.WHATEVER is presumed to be VARCHAR2(30) and T24.TOO\_LONG\_COLUMN is, er, longer:
```
insert into t23
(id
, whatever)
select pk_col
, substr(too_long_col, 1, 30)
from t42
/
``` |
5,167,712 | is there any way to change default shortcuts used by JTable? For instance I would like to change Home and End keys, so they would move to first/last row instead of first/last column.
Any way to do this? Thank you for help. | 2011/03/02 | [
"https://Stackoverflow.com/questions/5167712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/739927/"
] | There is no automatic trimming of data in Oracle, you have to trim it explicitly yourself e.g.
```
insert into mytable (id, text) values (123, substr(var,1,4000));
``` | As well as Tony's suggestion, you can use a CAST
```
select cast ('1234' as varchar2(3)) a
from dual
```
If you are doing data migration, look into [DML Error Logging](http://www.oracle-base.com/articles/10g/DmlErrorLogging_10gR2.php)
Having all your non-conformant data put into a corresponding table with the failure reason is positively dreamy. |
5,167,712 | is there any way to change default shortcuts used by JTable? For instance I would like to change Home and End keys, so they would move to first/last row instead of first/last column.
Any way to do this? Thank you for help. | 2011/03/02 | [
"https://Stackoverflow.com/questions/5167712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/739927/"
] | Oracle does support a variety of SQL functions which trim variables. I suspect the one you'll want is 'SUBSTR()'. The problem is that you will need to specify the desired length explicitly. In this example T23.WHATEVER is presumed to be VARCHAR2(30) and T24.TOO\_LONG\_COLUMN is, er, longer:
```
insert into t23
(id
, whatever)
select pk_col
, substr(too_long_col, 1, 30)
from t42
/
``` | As well as Tony's suggestion, you can use a CAST
```
select cast ('1234' as varchar2(3)) a
from dual
```
If you are doing data migration, look into [DML Error Logging](http://www.oracle-base.com/articles/10g/DmlErrorLogging_10gR2.php)
Having all your non-conformant data put into a corresponding table with the failure reason is positively dreamy. |
13,267 | So, for reasons which may or may not pop up in a later question of mine, I need to light a small Moon-like moon on fire.
Well, sort of. See, I need a small object capable of emitting a lot of light - i.e. with a high luminosity. That could either be a large ball of gas on fire, or it could be something very, very hot - and thus very, very bright. So it actually doesn't have to be burning.
For undisclosed reasons, this thing must be a rocky moon, and it must radiate in all directions. I have access to all the materials that exist in our Solar System. Oh, and I have the capabilities of a Type II civilization (which I appear to be obsessed with).
To the smart-alecks who will say, "Hey, you've got a giant bloody star!": The moon needs to be in its own stable orbit, either around a planet or, most likely, the central star. For now. I can't crash it into the central star. I also don't care about what happens to any of the other bodies in the system.
. . . I need to know by Friday.1
---
1 Congratulations if you know what I'm referencing. | 2015/03/29 | [
"https://worldbuilding.stackexchange.com/questions/13267",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/627/"
] | Depends on the color of the light. The easiest to achieve by Friday is lava-red. All you need to do is have a massive collision of your local moon with another moonlet: if the moonlet is large enough, that completely remelts the surface of the moon. The mantle remelting process has been [seriously](http://web.gps.caltech.edu/~sue/TJA_LindhurstLabWebsite/ListPublications/Papers_pdf/Seismo_1716.pdf) [studied](http://www.hou.usra.edu/meetings/lpsc2015/pdf/2263.pdf) in the past, so your basic equations are ready to go.
$$Q\_S = Q\_R (1 + M\_p/ M\_t) ( 1 − b ) $$
$M\_t$ and $M\_p$ are the target and projectile masses, respectively, and $Q\_R$ is the specific energy, while b is a variable that measures the directness of the impact. For more details, see the linked article above. Here are some calculations of fractional melt for an Earth-sized body (note that moons should be a lot easier to melt):

If we assume a basic ocean of lava, given that now we're getting on a full moon somewhere around $5mW/m^2$, that would make it at least 200 times more luminous. Moreover, with a mantle-remelting impact, you can get significant rock vaporization and (rather briefly) temperatures in the [3-7,000K range (See page 79, bottom right)](http://www.whoi.edu/science/GG/geodynamics/2005/images2005/melosh90_origin.pdf), which would be a nice white sun-like glow.
But let's face it, an ocean of lava [played straight](http://tvtropes.org/pmwiki/pmwiki.php/Main/PlayingWithATrope) is boring: we've all seen it.

Here's my suggestion: you can make it all more interesting by having a moon large enough to hold an atmosphere that **literally allows burning to happen**: you can then have your asteroid impactor generate an ocean of [burning sulfurous lava](http://lostininternet.com/the-spectacular-blue-lava-of-kawah-ijen/), with a nice eerie purple glow, the perfect setting for a final climactic boss confrontation.

Of course, it might be a bit **messy**.
PS:You can never have too many XKCD references. | Spoiler alert!
--------------
---
Actually Arthur C. Clarke has done this in his first published novel, "The Sands of Mars"
from [wikipedia](http://en.wikipedia.org/wiki/The_Sands_of_Mars):
>
> Hadfield reveals that scientists have been working on "Project Dawn", which
> involves the ignition of the moon Phobos and its use as a second “sun” for Mars.
> It will burn for at least one thousand years and the extra heat, together with
> mass production of the oxygen-generating plants, will eventually – it is hoped –
> make the Martian atmosphere breathable for humans.
>
>
>
The resulting fireball is not as bright as the sun but it provides additional energy for Mars' development. However it makes the day/night and seasons cycle very complicated.
The moon (made of rock) is somehow ignited using meson reaction. The technical details of how the moon was ignited are not discussed in the book. However Clarke sets the stage for how a society can attract the brightest nuclear scientists togather to do this massive project.
The book also has amazing descriptions of the moon rising. I suggest reading chapter 15 if you are interested to know the details. |
13,267 | So, for reasons which may or may not pop up in a later question of mine, I need to light a small Moon-like moon on fire.
Well, sort of. See, I need a small object capable of emitting a lot of light - i.e. with a high luminosity. That could either be a large ball of gas on fire, or it could be something very, very hot - and thus very, very bright. So it actually doesn't have to be burning.
For undisclosed reasons, this thing must be a rocky moon, and it must radiate in all directions. I have access to all the materials that exist in our Solar System. Oh, and I have the capabilities of a Type II civilization (which I appear to be obsessed with).
To the smart-alecks who will say, "Hey, you've got a giant bloody star!": The moon needs to be in its own stable orbit, either around a planet or, most likely, the central star. For now. I can't crash it into the central star. I also don't care about what happens to any of the other bodies in the system.
. . . I need to know by Friday.1
---
1 Congratulations if you know what I'm referencing. | 2015/03/29 | [
"https://worldbuilding.stackexchange.com/questions/13267",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/627/"
] | If the moon was a watery moon like Europa, this might be easy (for certain values of easy); an intense beam of muons could be shot into the oceans and catalytically induce fusion in the molecules of D2 in the water. This would be fantastically inefficient and probably require a muon source emitting almost as much energy as the fusion reactions going on in the oceans would release, but if you are really determined to have a light show.....
For rocky or metallic bodies, the problem is much more difficult. Inducing nuclear reactions runs against the curve of binding energy; so while it is "sort of" easy to induce fusion with very light elements, or fission in very heavy elements, as you approach Iron things become more and more difficult (iron is right out; when the core of a supermassive star produces Iron there is no energy release and the gravitational forces collapse the star, triggering a supernova).
Your sort of serious solution would be to drop a slug of antimatter into the core of the moon, and the energy release would melt the body and you would have essentially a glowing ember in the sky (a big enough slug of antimatter compressed to neutronium density would consume the core and melt the rest; too big and you blow the moon into small pieces, too small and you simply get interesting earthquakes and volcanic eruptions).
Or you could just paint the surface of the moon with radioactive material and have it glow in the dark.... | Many answers linking cause and effect, that may not be necessary.
Consider, "How would you boil the ocean?"
Don't heat it of course, reduce the atmospheric pressure.
For your moon, use a set of Gravity Lens(s) to collect and focus ambient starglow.
. |
13,267 | So, for reasons which may or may not pop up in a later question of mine, I need to light a small Moon-like moon on fire.
Well, sort of. See, I need a small object capable of emitting a lot of light - i.e. with a high luminosity. That could either be a large ball of gas on fire, or it could be something very, very hot - and thus very, very bright. So it actually doesn't have to be burning.
For undisclosed reasons, this thing must be a rocky moon, and it must radiate in all directions. I have access to all the materials that exist in our Solar System. Oh, and I have the capabilities of a Type II civilization (which I appear to be obsessed with).
To the smart-alecks who will say, "Hey, you've got a giant bloody star!": The moon needs to be in its own stable orbit, either around a planet or, most likely, the central star. For now. I can't crash it into the central star. I also don't care about what happens to any of the other bodies in the system.
. . . I need to know by Friday.1
---
1 Congratulations if you know what I'm referencing. | 2015/03/29 | [
"https://worldbuilding.stackexchange.com/questions/13267",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/627/"
] | Depends on the color of the light. The easiest to achieve by Friday is lava-red. All you need to do is have a massive collision of your local moon with another moonlet: if the moonlet is large enough, that completely remelts the surface of the moon. The mantle remelting process has been [seriously](http://web.gps.caltech.edu/~sue/TJA_LindhurstLabWebsite/ListPublications/Papers_pdf/Seismo_1716.pdf) [studied](http://www.hou.usra.edu/meetings/lpsc2015/pdf/2263.pdf) in the past, so your basic equations are ready to go.
$$Q\_S = Q\_R (1 + M\_p/ M\_t) ( 1 − b ) $$
$M\_t$ and $M\_p$ are the target and projectile masses, respectively, and $Q\_R$ is the specific energy, while b is a variable that measures the directness of the impact. For more details, see the linked article above. Here are some calculations of fractional melt for an Earth-sized body (note that moons should be a lot easier to melt):

If we assume a basic ocean of lava, given that now we're getting on a full moon somewhere around $5mW/m^2$, that would make it at least 200 times more luminous. Moreover, with a mantle-remelting impact, you can get significant rock vaporization and (rather briefly) temperatures in the [3-7,000K range (See page 79, bottom right)](http://www.whoi.edu/science/GG/geodynamics/2005/images2005/melosh90_origin.pdf), which would be a nice white sun-like glow.
But let's face it, an ocean of lava [played straight](http://tvtropes.org/pmwiki/pmwiki.php/Main/PlayingWithATrope) is boring: we've all seen it.

Here's my suggestion: you can make it all more interesting by having a moon large enough to hold an atmosphere that **literally allows burning to happen**: you can then have your asteroid impactor generate an ocean of [burning sulfurous lava](http://lostininternet.com/the-spectacular-blue-lava-of-kawah-ijen/), with a nice eerie purple glow, the perfect setting for a final climactic boss confrontation.

Of course, it might be a bit **messy**.
PS:You can never have too many XKCD references. | Given that our moon's dull gray surface shines bright white and beige in sunlight, it seems that composing or covering your moon's surface with brighter colored, higher reflective compounds would greatly increase its luminousity. Whatever you use should be either solid or liquid at the moon's highest sun-struck temperature and zero pressure. If it evaporates into a gas, there probably wouldn't be enough gravity present to keep the gas around. As a result, the moon's size and brightness would deminish over time.
You might get a very firelike effect if the moon made of a bright substance that was a gas at its sun-struck temperature and a solid in the dark side chill. Then by spinning your moon quickly, you could give it a bright atmosphere that is continually erupting from the surface, glowing in wild tendrils and wisps until they flow into the darkness and condensing, return to the ground. Could look pretty cool! |
13,267 | So, for reasons which may or may not pop up in a later question of mine, I need to light a small Moon-like moon on fire.
Well, sort of. See, I need a small object capable of emitting a lot of light - i.e. with a high luminosity. That could either be a large ball of gas on fire, or it could be something very, very hot - and thus very, very bright. So it actually doesn't have to be burning.
For undisclosed reasons, this thing must be a rocky moon, and it must radiate in all directions. I have access to all the materials that exist in our Solar System. Oh, and I have the capabilities of a Type II civilization (which I appear to be obsessed with).
To the smart-alecks who will say, "Hey, you've got a giant bloody star!": The moon needs to be in its own stable orbit, either around a planet or, most likely, the central star. For now. I can't crash it into the central star. I also don't care about what happens to any of the other bodies in the system.
. . . I need to know by Friday.1
---
1 Congratulations if you know what I'm referencing. | 2015/03/29 | [
"https://worldbuilding.stackexchange.com/questions/13267",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/627/"
] | An ordinary impact event makes quite a bright light. You could direct impacts to several points around the sphere to make it light up from all directions. | Spoiler alert!
--------------
---
Actually Arthur C. Clarke has done this in his first published novel, "The Sands of Mars"
from [wikipedia](http://en.wikipedia.org/wiki/The_Sands_of_Mars):
>
> Hadfield reveals that scientists have been working on "Project Dawn", which
> involves the ignition of the moon Phobos and its use as a second “sun” for Mars.
> It will burn for at least one thousand years and the extra heat, together with
> mass production of the oxygen-generating plants, will eventually – it is hoped –
> make the Martian atmosphere breathable for humans.
>
>
>
The resulting fireball is not as bright as the sun but it provides additional energy for Mars' development. However it makes the day/night and seasons cycle very complicated.
The moon (made of rock) is somehow ignited using meson reaction. The technical details of how the moon was ignited are not discussed in the book. However Clarke sets the stage for how a society can attract the brightest nuclear scientists togather to do this massive project.
The book also has amazing descriptions of the moon rising. I suggest reading chapter 15 if you are interested to know the details. |
13,267 | So, for reasons which may or may not pop up in a later question of mine, I need to light a small Moon-like moon on fire.
Well, sort of. See, I need a small object capable of emitting a lot of light - i.e. with a high luminosity. That could either be a large ball of gas on fire, or it could be something very, very hot - and thus very, very bright. So it actually doesn't have to be burning.
For undisclosed reasons, this thing must be a rocky moon, and it must radiate in all directions. I have access to all the materials that exist in our Solar System. Oh, and I have the capabilities of a Type II civilization (which I appear to be obsessed with).
To the smart-alecks who will say, "Hey, you've got a giant bloody star!": The moon needs to be in its own stable orbit, either around a planet or, most likely, the central star. For now. I can't crash it into the central star. I also don't care about what happens to any of the other bodies in the system.
. . . I need to know by Friday.1
---
1 Congratulations if you know what I'm referencing. | 2015/03/29 | [
"https://worldbuilding.stackexchange.com/questions/13267",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/627/"
] | Depends on the color of the light. The easiest to achieve by Friday is lava-red. All you need to do is have a massive collision of your local moon with another moonlet: if the moonlet is large enough, that completely remelts the surface of the moon. The mantle remelting process has been [seriously](http://web.gps.caltech.edu/~sue/TJA_LindhurstLabWebsite/ListPublications/Papers_pdf/Seismo_1716.pdf) [studied](http://www.hou.usra.edu/meetings/lpsc2015/pdf/2263.pdf) in the past, so your basic equations are ready to go.
$$Q\_S = Q\_R (1 + M\_p/ M\_t) ( 1 − b ) $$
$M\_t$ and $M\_p$ are the target and projectile masses, respectively, and $Q\_R$ is the specific energy, while b is a variable that measures the directness of the impact. For more details, see the linked article above. Here are some calculations of fractional melt for an Earth-sized body (note that moons should be a lot easier to melt):

If we assume a basic ocean of lava, given that now we're getting on a full moon somewhere around $5mW/m^2$, that would make it at least 200 times more luminous. Moreover, with a mantle-remelting impact, you can get significant rock vaporization and (rather briefly) temperatures in the [3-7,000K range (See page 79, bottom right)](http://www.whoi.edu/science/GG/geodynamics/2005/images2005/melosh90_origin.pdf), which would be a nice white sun-like glow.
But let's face it, an ocean of lava [played straight](http://tvtropes.org/pmwiki/pmwiki.php/Main/PlayingWithATrope) is boring: we've all seen it.

Here's my suggestion: you can make it all more interesting by having a moon large enough to hold an atmosphere that **literally allows burning to happen**: you can then have your asteroid impactor generate an ocean of [burning sulfurous lava](http://lostininternet.com/the-spectacular-blue-lava-of-kawah-ijen/), with a nice eerie purple glow, the perfect setting for a final climactic boss confrontation.

Of course, it might be a bit **messy**.
PS:You can never have too many XKCD references. | Many answers linking cause and effect, that may not be necessary.
Consider, "How would you boil the ocean?"
Don't heat it of course, reduce the atmospheric pressure.
For your moon, use a set of Gravity Lens(s) to collect and focus ambient starglow.
. |
13,267 | So, for reasons which may or may not pop up in a later question of mine, I need to light a small Moon-like moon on fire.
Well, sort of. See, I need a small object capable of emitting a lot of light - i.e. with a high luminosity. That could either be a large ball of gas on fire, or it could be something very, very hot - and thus very, very bright. So it actually doesn't have to be burning.
For undisclosed reasons, this thing must be a rocky moon, and it must radiate in all directions. I have access to all the materials that exist in our Solar System. Oh, and I have the capabilities of a Type II civilization (which I appear to be obsessed with).
To the smart-alecks who will say, "Hey, you've got a giant bloody star!": The moon needs to be in its own stable orbit, either around a planet or, most likely, the central star. For now. I can't crash it into the central star. I also don't care about what happens to any of the other bodies in the system.
. . . I need to know by Friday.1
---
1 Congratulations if you know what I'm referencing. | 2015/03/29 | [
"https://worldbuilding.stackexchange.com/questions/13267",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/627/"
] | If the moon was a watery moon like Europa, this might be easy (for certain values of easy); an intense beam of muons could be shot into the oceans and catalytically induce fusion in the molecules of D2 in the water. This would be fantastically inefficient and probably require a muon source emitting almost as much energy as the fusion reactions going on in the oceans would release, but if you are really determined to have a light show.....
For rocky or metallic bodies, the problem is much more difficult. Inducing nuclear reactions runs against the curve of binding energy; so while it is "sort of" easy to induce fusion with very light elements, or fission in very heavy elements, as you approach Iron things become more and more difficult (iron is right out; when the core of a supermassive star produces Iron there is no energy release and the gravitational forces collapse the star, triggering a supernova).
Your sort of serious solution would be to drop a slug of antimatter into the core of the moon, and the energy release would melt the body and you would have essentially a glowing ember in the sky (a big enough slug of antimatter compressed to neutronium density would consume the core and melt the rest; too big and you blow the moon into small pieces, too small and you simply get interesting earthquakes and volcanic eruptions).
Or you could just paint the surface of the moon with radioactive material and have it glow in the dark.... | Given that our moon's dull gray surface shines bright white and beige in sunlight, it seems that composing or covering your moon's surface with brighter colored, higher reflective compounds would greatly increase its luminousity. Whatever you use should be either solid or liquid at the moon's highest sun-struck temperature and zero pressure. If it evaporates into a gas, there probably wouldn't be enough gravity present to keep the gas around. As a result, the moon's size and brightness would deminish over time.
You might get a very firelike effect if the moon made of a bright substance that was a gas at its sun-struck temperature and a solid in the dark side chill. Then by spinning your moon quickly, you could give it a bright atmosphere that is continually erupting from the surface, glowing in wild tendrils and wisps until they flow into the darkness and condensing, return to the ground. Could look pretty cool! |
13,267 | So, for reasons which may or may not pop up in a later question of mine, I need to light a small Moon-like moon on fire.
Well, sort of. See, I need a small object capable of emitting a lot of light - i.e. with a high luminosity. That could either be a large ball of gas on fire, or it could be something very, very hot - and thus very, very bright. So it actually doesn't have to be burning.
For undisclosed reasons, this thing must be a rocky moon, and it must radiate in all directions. I have access to all the materials that exist in our Solar System. Oh, and I have the capabilities of a Type II civilization (which I appear to be obsessed with).
To the smart-alecks who will say, "Hey, you've got a giant bloody star!": The moon needs to be in its own stable orbit, either around a planet or, most likely, the central star. For now. I can't crash it into the central star. I also don't care about what happens to any of the other bodies in the system.
. . . I need to know by Friday.1
---
1 Congratulations if you know what I'm referencing. | 2015/03/29 | [
"https://worldbuilding.stackexchange.com/questions/13267",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/627/"
] | If the moon was a watery moon like Europa, this might be easy (for certain values of easy); an intense beam of muons could be shot into the oceans and catalytically induce fusion in the molecules of D2 in the water. This would be fantastically inefficient and probably require a muon source emitting almost as much energy as the fusion reactions going on in the oceans would release, but if you are really determined to have a light show.....
For rocky or metallic bodies, the problem is much more difficult. Inducing nuclear reactions runs against the curve of binding energy; so while it is "sort of" easy to induce fusion with very light elements, or fission in very heavy elements, as you approach Iron things become more and more difficult (iron is right out; when the core of a supermassive star produces Iron there is no energy release and the gravitational forces collapse the star, triggering a supernova).
Your sort of serious solution would be to drop a slug of antimatter into the core of the moon, and the energy release would melt the body and you would have essentially a glowing ember in the sky (a big enough slug of antimatter compressed to neutronium density would consume the core and melt the rest; too big and you blow the moon into small pieces, too small and you simply get interesting earthquakes and volcanic eruptions).
Or you could just paint the surface of the moon with radioactive material and have it glow in the dark.... | An ordinary impact event makes quite a bright light. You could direct impacts to several points around the sphere to make it light up from all directions. |
13,267 | So, for reasons which may or may not pop up in a later question of mine, I need to light a small Moon-like moon on fire.
Well, sort of. See, I need a small object capable of emitting a lot of light - i.e. with a high luminosity. That could either be a large ball of gas on fire, or it could be something very, very hot - and thus very, very bright. So it actually doesn't have to be burning.
For undisclosed reasons, this thing must be a rocky moon, and it must radiate in all directions. I have access to all the materials that exist in our Solar System. Oh, and I have the capabilities of a Type II civilization (which I appear to be obsessed with).
To the smart-alecks who will say, "Hey, you've got a giant bloody star!": The moon needs to be in its own stable orbit, either around a planet or, most likely, the central star. For now. I can't crash it into the central star. I also don't care about what happens to any of the other bodies in the system.
. . . I need to know by Friday.1
---
1 Congratulations if you know what I'm referencing. | 2015/03/29 | [
"https://worldbuilding.stackexchange.com/questions/13267",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/627/"
] | If the moon was a watery moon like Europa, this might be easy (for certain values of easy); an intense beam of muons could be shot into the oceans and catalytically induce fusion in the molecules of D2 in the water. This would be fantastically inefficient and probably require a muon source emitting almost as much energy as the fusion reactions going on in the oceans would release, but if you are really determined to have a light show.....
For rocky or metallic bodies, the problem is much more difficult. Inducing nuclear reactions runs against the curve of binding energy; so while it is "sort of" easy to induce fusion with very light elements, or fission in very heavy elements, as you approach Iron things become more and more difficult (iron is right out; when the core of a supermassive star produces Iron there is no energy release and the gravitational forces collapse the star, triggering a supernova).
Your sort of serious solution would be to drop a slug of antimatter into the core of the moon, and the energy release would melt the body and you would have essentially a glowing ember in the sky (a big enough slug of antimatter compressed to neutronium density would consume the core and melt the rest; too big and you blow the moon into small pieces, too small and you simply get interesting earthquakes and volcanic eruptions).
Or you could just paint the surface of the moon with radioactive material and have it glow in the dark.... | Spoiler alert!
--------------
---
Actually Arthur C. Clarke has done this in his first published novel, "The Sands of Mars"
from [wikipedia](http://en.wikipedia.org/wiki/The_Sands_of_Mars):
>
> Hadfield reveals that scientists have been working on "Project Dawn", which
> involves the ignition of the moon Phobos and its use as a second “sun” for Mars.
> It will burn for at least one thousand years and the extra heat, together with
> mass production of the oxygen-generating plants, will eventually – it is hoped –
> make the Martian atmosphere breathable for humans.
>
>
>
The resulting fireball is not as bright as the sun but it provides additional energy for Mars' development. However it makes the day/night and seasons cycle very complicated.
The moon (made of rock) is somehow ignited using meson reaction. The technical details of how the moon was ignited are not discussed in the book. However Clarke sets the stage for how a society can attract the brightest nuclear scientists togather to do this massive project.
The book also has amazing descriptions of the moon rising. I suggest reading chapter 15 if you are interested to know the details. |
13,267 | So, for reasons which may or may not pop up in a later question of mine, I need to light a small Moon-like moon on fire.
Well, sort of. See, I need a small object capable of emitting a lot of light - i.e. with a high luminosity. That could either be a large ball of gas on fire, or it could be something very, very hot - and thus very, very bright. So it actually doesn't have to be burning.
For undisclosed reasons, this thing must be a rocky moon, and it must radiate in all directions. I have access to all the materials that exist in our Solar System. Oh, and I have the capabilities of a Type II civilization (which I appear to be obsessed with).
To the smart-alecks who will say, "Hey, you've got a giant bloody star!": The moon needs to be in its own stable orbit, either around a planet or, most likely, the central star. For now. I can't crash it into the central star. I also don't care about what happens to any of the other bodies in the system.
. . . I need to know by Friday.1
---
1 Congratulations if you know what I'm referencing. | 2015/03/29 | [
"https://worldbuilding.stackexchange.com/questions/13267",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/627/"
] | Depends on the color of the light. The easiest to achieve by Friday is lava-red. All you need to do is have a massive collision of your local moon with another moonlet: if the moonlet is large enough, that completely remelts the surface of the moon. The mantle remelting process has been [seriously](http://web.gps.caltech.edu/~sue/TJA_LindhurstLabWebsite/ListPublications/Papers_pdf/Seismo_1716.pdf) [studied](http://www.hou.usra.edu/meetings/lpsc2015/pdf/2263.pdf) in the past, so your basic equations are ready to go.
$$Q\_S = Q\_R (1 + M\_p/ M\_t) ( 1 − b ) $$
$M\_t$ and $M\_p$ are the target and projectile masses, respectively, and $Q\_R$ is the specific energy, while b is a variable that measures the directness of the impact. For more details, see the linked article above. Here are some calculations of fractional melt for an Earth-sized body (note that moons should be a lot easier to melt):

If we assume a basic ocean of lava, given that now we're getting on a full moon somewhere around $5mW/m^2$, that would make it at least 200 times more luminous. Moreover, with a mantle-remelting impact, you can get significant rock vaporization and (rather briefly) temperatures in the [3-7,000K range (See page 79, bottom right)](http://www.whoi.edu/science/GG/geodynamics/2005/images2005/melosh90_origin.pdf), which would be a nice white sun-like glow.
But let's face it, an ocean of lava [played straight](http://tvtropes.org/pmwiki/pmwiki.php/Main/PlayingWithATrope) is boring: we've all seen it.

Here's my suggestion: you can make it all more interesting by having a moon large enough to hold an atmosphere that **literally allows burning to happen**: you can then have your asteroid impactor generate an ocean of [burning sulfurous lava](http://lostininternet.com/the-spectacular-blue-lava-of-kawah-ijen/), with a nice eerie purple glow, the perfect setting for a final climactic boss confrontation.

Of course, it might be a bit **messy**.
PS:You can never have too many XKCD references. | An ordinary impact event makes quite a bright light. You could direct impacts to several points around the sphere to make it light up from all directions. |
13,267 | So, for reasons which may or may not pop up in a later question of mine, I need to light a small Moon-like moon on fire.
Well, sort of. See, I need a small object capable of emitting a lot of light - i.e. with a high luminosity. That could either be a large ball of gas on fire, or it could be something very, very hot - and thus very, very bright. So it actually doesn't have to be burning.
For undisclosed reasons, this thing must be a rocky moon, and it must radiate in all directions. I have access to all the materials that exist in our Solar System. Oh, and I have the capabilities of a Type II civilization (which I appear to be obsessed with).
To the smart-alecks who will say, "Hey, you've got a giant bloody star!": The moon needs to be in its own stable orbit, either around a planet or, most likely, the central star. For now. I can't crash it into the central star. I also don't care about what happens to any of the other bodies in the system.
. . . I need to know by Friday.1
---
1 Congratulations if you know what I'm referencing. | 2015/03/29 | [
"https://worldbuilding.stackexchange.com/questions/13267",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/627/"
] | Many answers linking cause and effect, that may not be necessary.
Consider, "How would you boil the ocean?"
Don't heat it of course, reduce the atmospheric pressure.
For your moon, use a set of Gravity Lens(s) to collect and focus ambient starglow.
. | Spoiler alert!
--------------
---
Actually Arthur C. Clarke has done this in his first published novel, "The Sands of Mars"
from [wikipedia](http://en.wikipedia.org/wiki/The_Sands_of_Mars):
>
> Hadfield reveals that scientists have been working on "Project Dawn", which
> involves the ignition of the moon Phobos and its use as a second “sun” for Mars.
> It will burn for at least one thousand years and the extra heat, together with
> mass production of the oxygen-generating plants, will eventually – it is hoped –
> make the Martian atmosphere breathable for humans.
>
>
>
The resulting fireball is not as bright as the sun but it provides additional energy for Mars' development. However it makes the day/night and seasons cycle very complicated.
The moon (made of rock) is somehow ignited using meson reaction. The technical details of how the moon was ignited are not discussed in the book. However Clarke sets the stage for how a society can attract the brightest nuclear scientists togather to do this massive project.
The book also has amazing descriptions of the moon rising. I suggest reading chapter 15 if you are interested to know the details. |
14,421 | Would it be worth to to add a badge for offering a certain amount of rep over time (say 1000) towards bounties? It could be called the `Sheriff` badge.
This sounds like a good idea to me now but I've been drinking.
### Update:
With the [introduction of the new bounty system](https://blog.stackoverflow.com/2010/06/improvements-to-bounty-system/), this request has become relevant again! Any other thoughts? | 2009/08/14 | [
"https://meta.stackexchange.com/questions/14421",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/44765/"
] | I think more importantly would be an badge for winning that much rep through bounties. Say bronze if you won your first bounty, silver for at least 1000 rep through bounties and gold for 5000 or so. And yes, I also think a badge for giving bounties could be a good thing. I don't think someone easily throw away his hard-earned reputation for a bounty only to win a badge. So such an badge wouldn't hurt the system. | Using the [Top Investors](https://data.stackexchange.com/stackoverflow/query/65683/top-investors) query written by [Jeremy Banks](https://data.stackexchange.com/users/6321) on the data explorer I've listed the amount of people on Stack Overflow who would are currently eligible for the proposed badges:
* 13 users have invested at least 5000 (0 users on sister sites Server Fault & Super User)
* 73 users have invested at least 2500
* 414 users have invested at least 1000
* 1404 users have invested at least 500
Gold badges on Stack Overflow range hugely from 25,691 users with the 'Famous Question' badge to the 79 users who have earned a Legendary badge. |
14,421 | Would it be worth to to add a badge for offering a certain amount of rep over time (say 1000) towards bounties? It could be called the `Sheriff` badge.
This sounds like a good idea to me now but I've been drinking.
### Update:
With the [introduction of the new bounty system](https://blog.stackoverflow.com/2010/06/improvements-to-bounty-system/), this request has become relevant again! Any other thoughts? | 2009/08/14 | [
"https://meta.stackexchange.com/questions/14421",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/44765/"
] | I think more importantly would be an badge for winning that much rep through bounties. Say bronze if you won your first bounty, silver for at least 1000 rep through bounties and gold for 5000 or so. And yes, I also think a badge for giving bounties could be a good thing. I don't think someone easily throw away his hard-earned reputation for a bounty only to win a badge. So such an badge wouldn't hurt the system. | I just won my first bounty... and was about to ask why there are no bounty related badges... I was hoping to get a `boba fett` badge. But reading TheTXI's answer I can see the logic in *not* offering a badge for offering a bounty.
So... come on Jeff, add a `status-?` tag so we know where you stand on this... |
14,421 | Would it be worth to to add a badge for offering a certain amount of rep over time (say 1000) towards bounties? It could be called the `Sheriff` badge.
This sounds like a good idea to me now but I've been drinking.
### Update:
With the [introduction of the new bounty system](https://blog.stackoverflow.com/2010/06/improvements-to-bounty-system/), this request has become relevant again! Any other thoughts? | 2009/08/14 | [
"https://meta.stackexchange.com/questions/14421",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/44765/"
] | I think more importantly would be an badge for winning that much rep through bounties. Say bronze if you won your first bounty, silver for at least 1000 rep through bounties and gold for 5000 or so. And yes, I also think a badge for giving bounties could be a good thing. I don't think someone easily throw away his hard-earned reputation for a bounty only to win a badge. So such an badge wouldn't hurt the system. | I believe the goal of the bounty system is to help users to provide additional incentive to a question they would really like an answer to. Therefore, I do not believe is this a feature that needs any additional encouragement placed on it, as a badge would do. Essentially badges should be awarded to users who are providing services or behavior that the system needs. I don't think that offering bounties falls into the category of a behavior the system needs. Its an available feature, but its available for you, not the system. Voting is something the system needs to function, so there are badges related to voting. The system needs editors, flaggers and retaggers; SO would be lesser without them. I do not think SO would be lesser if no one ever offered another bounty. |
14,421 | Would it be worth to to add a badge for offering a certain amount of rep over time (say 1000) towards bounties? It could be called the `Sheriff` badge.
This sounds like a good idea to me now but I've been drinking.
### Update:
With the [introduction of the new bounty system](https://blog.stackoverflow.com/2010/06/improvements-to-bounty-system/), this request has become relevant again! Any other thoughts? | 2009/08/14 | [
"https://meta.stackexchange.com/questions/14421",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/44765/"
] | Badges should be encouraging good behavior. It is still up for debate whether or not offering bounties counts as "good behavior" especially when you can just start making bounties for simple questions and throwing minimum rep at it.
I think a badge for winning bounties is a lot more logical than for offering up bounties. | I agree with TheTXI here. The theory of this seems nice, but the reality of it wouldn't work. Think about it, people just randomly tossing rep in bounties on random questions for a badge. It would throw a fork into the reputation and moderation system - people gaining rep left and right.
As a much better alternative to this, how about getting a badge when you *win* a certain amount of rep in bounties.
This way, you still need to uphold high-quality answers to get a bounty, and bounties will remain *special* because there won't be too many going on at a time.
You would get rewarded with a badge when people have found you so helpful, you gained X extra rep in bounties from them. |
14,421 | Would it be worth to to add a badge for offering a certain amount of rep over time (say 1000) towards bounties? It could be called the `Sheriff` badge.
This sounds like a good idea to me now but I've been drinking.
### Update:
With the [introduction of the new bounty system](https://blog.stackoverflow.com/2010/06/improvements-to-bounty-system/), this request has become relevant again! Any other thoughts? | 2009/08/14 | [
"https://meta.stackexchange.com/questions/14421",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/44765/"
] | Offering a bounty means you are willing to give up some reputation for the good of the community, as all reasons eventually lead to better content or rewarding existing good content.
The act of *offering* is what matters most in my opinion, not manually awarding and we already got [investor](https://stackoverflow.com/badges/219/investor) badge which is a good start - but I would like to see silver and gold badges as well.
* **Philanthropist** - Silver badge. *Offered at least 5 bounties worth total of at least 1000 reputation*.
* **Good Samaritan** - Gold badge. *Offered at least 50 bounties worth total of at least 5000 reputation*.
The limitations will protect the badges from gaming by offering minimum amount of reputation.
Edit: just noticed there is already pending feature request:
[Can we have a badge called "big spender" or "seeder"?](https://meta.stackexchange.com/questions/40090/can-we-have-a-badge-called-big-spender-or-seeder) | 1. I absolutely encourage posting while drunk. +1 to you.
2. And (soberly, sadly) I'm not sure this would be the best idea -- you could get folks offering up easy 100 points on questions they haven't selected an answer to just to get this badge. Bounties are meant to be sort of a last resort incentivizer, not something that we want everybody to aspire to. |
14,421 | Would it be worth to to add a badge for offering a certain amount of rep over time (say 1000) towards bounties? It could be called the `Sheriff` badge.
This sounds like a good idea to me now but I've been drinking.
### Update:
With the [introduction of the new bounty system](https://blog.stackoverflow.com/2010/06/improvements-to-bounty-system/), this request has become relevant again! Any other thoughts? | 2009/08/14 | [
"https://meta.stackexchange.com/questions/14421",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/44765/"
] | 1. I absolutely encourage posting while drunk. +1 to you.
2. And (soberly, sadly) I'm not sure this would be the best idea -- you could get folks offering up easy 100 points on questions they haven't selected an answer to just to get this badge. Bounties are meant to be sort of a last resort incentivizer, not something that we want everybody to aspire to. | I would like to see badges for placing bounty in unanswered questions, following which the question receives positive score answer(s), and finally one such answer is offered the bounty.
* For 10 such actions, a silver badge
* For 50 such actions, a gold badge
The names can be anything like Philanthropist (which someone suggested already here), Patron, etc. |
14,421 | Would it be worth to to add a badge for offering a certain amount of rep over time (say 1000) towards bounties? It could be called the `Sheriff` badge.
This sounds like a good idea to me now but I've been drinking.
### Update:
With the [introduction of the new bounty system](https://blog.stackoverflow.com/2010/06/improvements-to-bounty-system/), this request has become relevant again! Any other thoughts? | 2009/08/14 | [
"https://meta.stackexchange.com/questions/14421",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/44765/"
] | Offering a bounty means you are willing to give up some reputation for the good of the community, as all reasons eventually lead to better content or rewarding existing good content.
The act of *offering* is what matters most in my opinion, not manually awarding and we already got [investor](https://stackoverflow.com/badges/219/investor) badge which is a good start - but I would like to see silver and gold badges as well.
* **Philanthropist** - Silver badge. *Offered at least 5 bounties worth total of at least 1000 reputation*.
* **Good Samaritan** - Gold badge. *Offered at least 50 bounties worth total of at least 5000 reputation*.
The limitations will protect the badges from gaming by offering minimum amount of reputation.
Edit: just noticed there is already pending feature request:
[Can we have a badge called "big spender" or "seeder"?](https://meta.stackexchange.com/questions/40090/can-we-have-a-badge-called-big-spender-or-seeder) | Awarding a badge for offering bounties is a great way to promote this feature and help make users aware of it, as well as to encourage them to use this feature to help promote great questions.
However, I'm not 100% convinced that the name of the badge fits the actions, considering we already have existing badges named after peace officers and law enforcement that are awarded for flagging unwanted content.
As far as badge names go, I really like [Plutocrat](http://en.wiktionary.org/wiki/plutocrat) as a name for the badge. A plutocrat is:
>
> someone who rules by virtue of his or her wealth.
>
>
>
Does a huge bounty not determine what questions get the most attention in the StackExchange network? Is this not a form of ruling by virtue of one's reputational wealth?
I also like [Tycoon](http://thesaurus.com/browse/tycoon):
>
> person who has a lot of money, power.
>
>
>
**Below are reasons why "Sheriff" may not be the best name for a bounty badge:**
While I can definitely see the correlation between "Sheriff" badge and offering a "bounty", I feel like that could be confused with the two badges that are awarded to those who raise helpful flags.
Currently, the [Citizen Patrol](https://stackoverflow.com/badges/8/citizen-patrol) badge is awarded to a user who, for the first time, flags a post. The [Deputy](https://stackoverflow.com/badges/1002/deputy) badge is awarded for raising 80 helpful flags, and the [Marshal](https://stackoverflow.com/badges/1298/marshal) badge is awarded for raising 500 helpful flags. When we look at these three badges, it's clear that we're comparing apples to apples but in varying quantities.
The proposed Sheriff badge would likely be confused with other badges intended to recognize volunteers who help keep the site clean, free of spam, and who alert diamond moderators of potential problems. Awarding bounties, on the other hand, is more closely related to awarding the accepted answer than it is to blowing the whistle on a spammer.
Since we already have some badges for those who offer and award bounties, we should look to those existing badges when deriving inspiration for naming a new badge.
**Bounty Badges:**
The current badges awarded for bounties are the [Altruist](https://stackoverflow.com/badges/222/altruist), [Benefactor](https://stackoverflow.com/badges/221/benefactor), [Investor](https://stackoverflow.com/badges/219/investor), and [Promoter](https://stackoverflow.com/badges/220/promoter), with the first two badges being awarded for awarding bounties and the latter two badges being awarded for offering bounties.
Therefore, with this logic, it stands to reason that a question about a badge awarded to individuals who offer bounties over time should have a name that fits within the same categories as other existing badges related to offering bounties on questions.
Investor and Promoter are those two existing badges related to bounty offerings. Here are the synonyms for those:
**Investor:**
From [Thesaurus.com on investor](http://thesaurus.com/browse/investor):
>
> a financier
>
>
> Synonyms: backer, banker, capitalist, lender, shareholder, stockholder, venture capitalist
>
>
>
From [Thesaurus.com on promoter](http://thesaurus.com/browse/promoter):
**Promoter:**
>
> a supporter
>
>
> Synonyms: advertiser, advocate, ally, backer, booster, endorser, follower, organizer, publicist, sponsor
>
>
>
Tycoon and Plutocrat were words that are more closely related to investor, and are words I found on the same page. These are not names we've used before on badges. However, I noticed that promoter has two synonyms for two badges that we award for sharing links to questions, the [Booster](https://stackoverflow.com/badges/261/booster) badge and the elusive [Publicist](https://stackoverflow.com/badges/262/publicist) badge. Therefore, my logic may be somewhat flawed in ruling out "Sheriff" as the name for the badge.
Still, if we are going to promote the creation of this bounty badge, I'd be interested to see a unique name chosen that helps separate it from other types of badges that are awarded for unrelated activities and that emphasize wealth or sharing of wealth. |
14,421 | Would it be worth to to add a badge for offering a certain amount of rep over time (say 1000) towards bounties? It could be called the `Sheriff` badge.
This sounds like a good idea to me now but I've been drinking.
### Update:
With the [introduction of the new bounty system](https://blog.stackoverflow.com/2010/06/improvements-to-bounty-system/), this request has become relevant again! Any other thoughts? | 2009/08/14 | [
"https://meta.stackexchange.com/questions/14421",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/44765/"
] | I just won my first bounty... and was about to ask why there are no bounty related badges... I was hoping to get a `boba fett` badge. But reading TheTXI's answer I can see the logic in *not* offering a badge for offering a bounty.
So... come on Jeff, add a `status-?` tag so we know where you stand on this... | I would like to see badges for placing bounty in unanswered questions, following which the question receives positive score answer(s), and finally one such answer is offered the bounty.
* For 10 such actions, a silver badge
* For 50 such actions, a gold badge
The names can be anything like Philanthropist (which someone suggested already here), Patron, etc. |
14,421 | Would it be worth to to add a badge for offering a certain amount of rep over time (say 1000) towards bounties? It could be called the `Sheriff` badge.
This sounds like a good idea to me now but I've been drinking.
### Update:
With the [introduction of the new bounty system](https://blog.stackoverflow.com/2010/06/improvements-to-bounty-system/), this request has become relevant again! Any other thoughts? | 2009/08/14 | [
"https://meta.stackexchange.com/questions/14421",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/44765/"
] | Badges should be encouraging good behavior. It is still up for debate whether or not offering bounties counts as "good behavior" especially when you can just start making bounties for simple questions and throwing minimum rep at it.
I think a badge for winning bounties is a lot more logical than for offering up bounties. | I would like to see badges for placing bounty in unanswered questions, following which the question receives positive score answer(s), and finally one such answer is offered the bounty.
* For 10 such actions, a silver badge
* For 50 such actions, a gold badge
The names can be anything like Philanthropist (which someone suggested already here), Patron, etc. |
14,421 | Would it be worth to to add a badge for offering a certain amount of rep over time (say 1000) towards bounties? It could be called the `Sheriff` badge.
This sounds like a good idea to me now but I've been drinking.
### Update:
With the [introduction of the new bounty system](https://blog.stackoverflow.com/2010/06/improvements-to-bounty-system/), this request has become relevant again! Any other thoughts? | 2009/08/14 | [
"https://meta.stackexchange.com/questions/14421",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/44765/"
] | I just won my first bounty... and was about to ask why there are no bounty related badges... I was hoping to get a `boba fett` badge. But reading TheTXI's answer I can see the logic in *not* offering a badge for offering a bounty.
So... come on Jeff, add a `status-?` tag so we know where you stand on this... | I agree with TheTXI here. The theory of this seems nice, but the reality of it wouldn't work. Think about it, people just randomly tossing rep in bounties on random questions for a badge. It would throw a fork into the reputation and moderation system - people gaining rep left and right.
As a much better alternative to this, how about getting a badge when you *win* a certain amount of rep in bounties.
This way, you still need to uphold high-quality answers to get a bounty, and bounties will remain *special* because there won't be too many going on at a time.
You would get rewarded with a badge when people have found you so helpful, you gained X extra rep in bounties from them. |
52,782,153 | I am really struggling to add a new column with the line number in the terminal to a pipe delimited file
My current file looks like this:
```
ID|FirstName|LastName
12|John|Svernson
23|Mark|Wright
11|Chris|Watson
```
And I want the file to look like the following:
```
LN|ID|FirstName|LastName
1|12|John|Svernson
2|23|Mark|Wright
3|11|Chris|Watson
```
I have over 90k lines. I couldn't find a way to do this. Any help or guidance would be appreciated. Thanks | 2018/10/12 | [
"https://Stackoverflow.com/questions/52782153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5239781/"
] | could you please try following.
```
awk 'FNR==1{print "LN|"$0;next} {$1=++count "|" $1} 1' Input_file
```
To write output into Input\_file itself append `> temp_file && mv temp_file Input_file` in above code too. | Use awk variable NR (record number):
```
awk -F'|' 'NR==1{print "LN" FS $0}NR!=1{print NR-1 FS $0}' file
``` |
52,782,153 | I am really struggling to add a new column with the line number in the terminal to a pipe delimited file
My current file looks like this:
```
ID|FirstName|LastName
12|John|Svernson
23|Mark|Wright
11|Chris|Watson
```
And I want the file to look like the following:
```
LN|ID|FirstName|LastName
1|12|John|Svernson
2|23|Mark|Wright
3|11|Chris|Watson
```
I have over 90k lines. I couldn't find a way to do this. Any help or guidance would be appreciated. Thanks | 2018/10/12 | [
"https://Stackoverflow.com/questions/52782153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5239781/"
] | Use awk variable NR (record number):
```
awk -F'|' 'NR==1{print "LN" FS $0}NR!=1{print NR-1 FS $0}' file
``` | I would use `nl`. You may run into issues if your line number goes over 6 digits, but you can add a `-w` to increase the number width if you need to:
```
{ read line; echo "LN|$line"; cat | nl -w 10 -ba -s \|; } < input |
sed 's/^ *//';
``` |
52,782,153 | I am really struggling to add a new column with the line number in the terminal to a pipe delimited file
My current file looks like this:
```
ID|FirstName|LastName
12|John|Svernson
23|Mark|Wright
11|Chris|Watson
```
And I want the file to look like the following:
```
LN|ID|FirstName|LastName
1|12|John|Svernson
2|23|Mark|Wright
3|11|Chris|Watson
```
I have over 90k lines. I couldn't find a way to do this. Any help or guidance would be appreciated. Thanks | 2018/10/12 | [
"https://Stackoverflow.com/questions/52782153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5239781/"
] | A fun alternative:
```
{ echo LN; seq $(( $(wc -l < file) - 1 )); } | paste -d'|' - file
```
although in reality I'd use
```
awk '{print (NR==1 ? "LN" : NR-1), $0}' OFS="|" file
``` | Use awk variable NR (record number):
```
awk -F'|' 'NR==1{print "LN" FS $0}NR!=1{print NR-1 FS $0}' file
``` |
52,782,153 | I am really struggling to add a new column with the line number in the terminal to a pipe delimited file
My current file looks like this:
```
ID|FirstName|LastName
12|John|Svernson
23|Mark|Wright
11|Chris|Watson
```
And I want the file to look like the following:
```
LN|ID|FirstName|LastName
1|12|John|Svernson
2|23|Mark|Wright
3|11|Chris|Watson
```
I have over 90k lines. I couldn't find a way to do this. Any help or guidance would be appreciated. Thanks | 2018/10/12 | [
"https://Stackoverflow.com/questions/52782153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5239781/"
] | could you please try following.
```
awk 'FNR==1{print "LN|"$0;next} {$1=++count "|" $1} 1' Input_file
```
To write output into Input\_file itself append `> temp_file && mv temp_file Input_file` in above code too. | I would use `nl`. You may run into issues if your line number goes over 6 digits, but you can add a `-w` to increase the number width if you need to:
```
{ read line; echo "LN|$line"; cat | nl -w 10 -ba -s \|; } < input |
sed 's/^ *//';
``` |
52,782,153 | I am really struggling to add a new column with the line number in the terminal to a pipe delimited file
My current file looks like this:
```
ID|FirstName|LastName
12|John|Svernson
23|Mark|Wright
11|Chris|Watson
```
And I want the file to look like the following:
```
LN|ID|FirstName|LastName
1|12|John|Svernson
2|23|Mark|Wright
3|11|Chris|Watson
```
I have over 90k lines. I couldn't find a way to do this. Any help or guidance would be appreciated. Thanks | 2018/10/12 | [
"https://Stackoverflow.com/questions/52782153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5239781/"
] | could you please try following.
```
awk 'FNR==1{print "LN|"$0;next} {$1=++count "|" $1} 1' Input_file
```
To write output into Input\_file itself append `> temp_file && mv temp_file Input_file` in above code too. | A fun alternative:
```
{ echo LN; seq $(( $(wc -l < file) - 1 )); } | paste -d'|' - file
```
although in reality I'd use
```
awk '{print (NR==1 ? "LN" : NR-1), $0}' OFS="|" file
``` |
52,782,153 | I am really struggling to add a new column with the line number in the terminal to a pipe delimited file
My current file looks like this:
```
ID|FirstName|LastName
12|John|Svernson
23|Mark|Wright
11|Chris|Watson
```
And I want the file to look like the following:
```
LN|ID|FirstName|LastName
1|12|John|Svernson
2|23|Mark|Wright
3|11|Chris|Watson
```
I have over 90k lines. I couldn't find a way to do this. Any help or guidance would be appreciated. Thanks | 2018/10/12 | [
"https://Stackoverflow.com/questions/52782153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5239781/"
] | A fun alternative:
```
{ echo LN; seq $(( $(wc -l < file) - 1 )); } | paste -d'|' - file
```
although in reality I'd use
```
awk '{print (NR==1 ? "LN" : NR-1), $0}' OFS="|" file
``` | I would use `nl`. You may run into issues if your line number goes over 6 digits, but you can add a `-w` to increase the number width if you need to:
```
{ read line; echo "LN|$line"; cat | nl -w 10 -ba -s \|; } < input |
sed 's/^ *//';
``` |
15,783,938 | With `git rm <file>` a file can be deleted locally, removed from the versioning, and deleted on the repository. `git rm --cached <file>` does nearly the same, but keeps the file in the local working copy.
Is there possible, to remove a file/folder from the versioning (so its changes are ignored) keeping it in the repository, so that if somebody clones the repo, the file is also there, but cannot be changed with a simple `add` & `commit`? | 2013/04/03 | [
"https://Stackoverflow.com/questions/15783938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2019043/"
] | Files already under Git you can ignore using
```
git update-index --assume-unchanged filename
```
and unigtore
git update-index --no-assume-unchanged filename
but, there also some interesting features, [git - ignoring commited files and switch branch](https://stackoverflow.com/questions/15790390/git-ignoring-commited-files-and-switch-branch) | Try to add the file/folder to .gitignore |
15,783,938 | With `git rm <file>` a file can be deleted locally, removed from the versioning, and deleted on the repository. `git rm --cached <file>` does nearly the same, but keeps the file in the local working copy.
Is there possible, to remove a file/folder from the versioning (so its changes are ignored) keeping it in the repository, so that if somebody clones the repo, the file is also there, but cannot be changed with a simple `add` & `commit`? | 2013/04/03 | [
"https://Stackoverflow.com/questions/15783938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2019043/"
] | The short answer is no. The `.gitignore` facilities only prevent files from being tracked in the first place. In other words, it prevents files from entering the repository for the first time. However, once a file is tracked, it is tracked forever. All changes to that file will be tracked.
There are two general solutions. (1) Avoid adding that file to the index ever. This is just a matter of policy. (2) Place all such ignored files in an archive like `UnzipMeRightAfterCloning.zip`. It's an extra step for people getting into the repo, but at least the target files will never be committed. | Try to add the file/folder to .gitignore |
15,783,938 | With `git rm <file>` a file can be deleted locally, removed from the versioning, and deleted on the repository. `git rm --cached <file>` does nearly the same, but keeps the file in the local working copy.
Is there possible, to remove a file/folder from the versioning (so its changes are ignored) keeping it in the repository, so that if somebody clones the repo, the file is also there, but cannot be changed with a simple `add` & `commit`? | 2013/04/03 | [
"https://Stackoverflow.com/questions/15783938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2019043/"
] | The short answer is no. The `.gitignore` facilities only prevent files from being tracked in the first place. In other words, it prevents files from entering the repository for the first time. However, once a file is tracked, it is tracked forever. All changes to that file will be tracked.
There are two general solutions. (1) Avoid adding that file to the index ever. This is just a matter of policy. (2) Place all such ignored files in an archive like `UnzipMeRightAfterCloning.zip`. It's an extra step for people getting into the repo, but at least the target files will never be committed. | Files already under Git you can ignore using
```
git update-index --assume-unchanged filename
```
and unigtore
git update-index --no-assume-unchanged filename
but, there also some interesting features, [git - ignoring commited files and switch branch](https://stackoverflow.com/questions/15790390/git-ignoring-commited-files-and-switch-branch) |
55,985 | I was reading up on something called the PRAM model without bit operations.
What exactly does it mean that this PRAM model cannot do bit operations?
I can't find a straightforward definition anywhere.
Surely the different processors will still be able to do all sorts of stuff with bits. The reason why I am asking is that the max-flow problem (which is in P cannot be solved in this model using a polynomial number of processors. So in fact it is a non-trivial implication of the conjecture
that $P \neq NC$. So it is further "evidence" of the $P \neq NC$ conjecture. | 2016/04/15 | [
"https://cs.stackexchange.com/questions/55985",
"https://cs.stackexchange.com",
"https://cs.stackexchange.com/users/49599/"
] | Without further information, it's hard to tell exactly. However, to the best of my knowledge, bit operations may be intended as follows. Consider the problem of finding the maximum element in an array of $n$ real numbers. This problem can be solved by an EREW algorithm in $\Omega(\lg n)$; moreover, no CREW algorithm can do any better.
However, this problem can be solved in $O(1)$ time with $n^2$ processors using a common-CRCW algorithm (in this model, when several processors write to the same location, they all write the same value). The key point here is that a CRCW PRAM is capable of performing a boolean AND of $n$ variables in $O(1)$ time with $n$ processors (which allows overcoming the $\Omega(\lg n)$ lower bound). I think that bit operations may refer to this powerful AND capability of a common-CRCW.
Additional information regarding the FAST-MAX algorithm can be found in the first edition of CLRS Introduction to Algorithms, chapter 30 (ALGORITHMS FOR PARALLEL COMPUTERS). | On page 1461 of ["Lower Bounds in a Parallel Model without Bit Operations,"](https://doi.org/10.1137/S0097539794282930) Mulmuley says:
>
> It is like the usual PRAM model, the main difference being that it does not provide instructions for any bit operations such as $\land$,$\lor$,or *extract-bit*.
>
>
>
The model is explicitly specified in section 2.1.
The reason I think this result ($\textsf{P}\neq\textsf{NC}$) in this model is interesting is---although this model does not allow bit-operations---it still allows the time to depend on bitlengths. Also, this model is powerful enough to compute the determinant (see paragraph "Arithmetic PRAM model." on page 1469)! |
6,620,898 | Im running Aptana IDE for developing on a lamp setup. I have looked all over the place in the options to try and find if I can move the text editors file tabs to the side instead of lined up along the top. Any googling I attempt for this just gives me results for changing tab widths and stuff like that, so im having to ask the question here instead. | 2011/07/08 | [
"https://Stackoverflow.com/questions/6620898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/834879/"
] | User [CSS Reset](http://meyerweb.com/eric/tools/css/reset/), and everything should be solved. The reason you're getting the `weird artifact` is that, browsers by default apply some style on HTML elements. To nullify those default styles, designers usually use **CSS Reset**. A CSS Reset is a CSS file that tries to remove all default styles applied by browsers.
To debug your CSS margins and paddings, use Firebug with Firefox. Here is an image of how to do that:
 | You may be getting the browser's default styling here. I would recommend grabbing a CSS reset and seeing if that helps |
6,620,898 | Im running Aptana IDE for developing on a lamp setup. I have looked all over the place in the options to try and find if I can move the text editors file tabs to the side instead of lined up along the top. Any googling I attempt for this just gives me results for changing tab widths and stuff like that, so im having to ask the question here instead. | 2011/07/08 | [
"https://Stackoverflow.com/questions/6620898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/834879/"
] | 1. Images are inline elements.
2. Inline elements are rendered like characters.
3. Characters sit on a line.
4. There is space below that line for descenders (which you find on letters like g, j and y but not a, b, and c.)
5. That space is what you are seeing.
You could twiddle the [vertical-alignment](http://www.w3.org/TR/CSS21/visudet.html#line-height) of the images or [stop using layout tables](http://www.hotdesign.com/seybold/) | You may be getting the browser's default styling here. I would recommend grabbing a CSS reset and seeing if that helps |
6,620,898 | Im running Aptana IDE for developing on a lamp setup. I have looked all over the place in the options to try and find if I can move the text editors file tabs to the side instead of lined up along the top. Any googling I attempt for this just gives me results for changing tab widths and stuff like that, so im having to ask the question here instead. | 2011/07/08 | [
"https://Stackoverflow.com/questions/6620898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/834879/"
] | OK, guys, I got the bottom of it. The following style should be added to the tag that hosts the image. I don't know why, but it helps:
td{ font-size:0; }
Thanks everyone for your help! | You may be getting the browser's default styling here. I would recommend grabbing a CSS reset and seeing if that helps |
54,874,052 | Now i have code like this:
```
var object = {
a: 'a',
b: 'b',
c: {
d: 'd'
}
}
_.get(object).pick(['a', 'b']).value();
```
How to deep pick property 'd' like:
```
_.get(object).pick(['a', 'b', 'c.d']).value();
``` | 2019/02/25 | [
"https://Stackoverflow.com/questions/54874052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10885808/"
] | you can deep destructure without lodash :
```js
var object = {
a: 'a',
b: 'b',
c: {
d: 'd'
}
}
const { a, b, c :{ d }} = object;
console.log(a,b,d);
const obj = {a, b, d};
console.log(obj);
``` | You can create a `flatPick()` function. The function iterates the array of paths. and uses `_.get()` to get the value of the `path`, and `_.set()` to add the last part of the path as property on the result object:
```js
function flatPick(object, paths) {
const o = {};
paths.forEach(path => _.set(
o,
_.last(path.split('.')),
_.get(object, path)
));
return o;
}
var object = {
a: 'a',
b: 'b',
c: {
d: 'd',
e: {
f: 'f'
}
}
};
var result = flatPick(object, ['a', 'b', 'c.d', 'c.e.f']);
console.log(result);
```
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
``` |
54,874,052 | Now i have code like this:
```
var object = {
a: 'a',
b: 'b',
c: {
d: 'd'
}
}
_.get(object).pick(['a', 'b']).value();
```
How to deep pick property 'd' like:
```
_.get(object).pick(['a', 'b', 'c.d']).value();
``` | 2019/02/25 | [
"https://Stackoverflow.com/questions/54874052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10885808/"
] | you can deep destructure without lodash :
```js
var object = {
a: 'a',
b: 'b',
c: {
d: 'd'
}
}
const { a, b, c :{ d }} = object;
console.log(a,b,d);
const obj = {a, b, d};
console.log(obj);
``` | This can work for `lodash`:
```
function pickNested(object: Json, fields: string[]) {
const shallowFields = fields.filter((field) => !field.includes('.'));
const deepFields = fields.filter((field) => field.includes('.'));
const initialValue = _.pick(object, shallowFields) as Json;
return deepFields.reduce((output, field) => {
const key = _.snakeCase(field);
output[key] = _.get(object, field);
return output;
}, initialValue);
}
```
and:
```
const json = {
id: '10',
user: {
email: 'david.i@example.com',
},
};
const newData = pickNested(json, ['id', 'user.email']);
console.log('newData ->', newData);
/*
{
id: '10',
user_email: 'david.i@example.com',
};
*/
``` |
54,874,052 | Now i have code like this:
```
var object = {
a: 'a',
b: 'b',
c: {
d: 'd'
}
}
_.get(object).pick(['a', 'b']).value();
```
How to deep pick property 'd' like:
```
_.get(object).pick(['a', 'b', 'c.d']).value();
``` | 2019/02/25 | [
"https://Stackoverflow.com/questions/54874052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10885808/"
] | In case you insist in using Lodash, consider using the [\_.get()](https://lodash.com/docs/4.17.11#get) function:
```
_.get(object, 'c.d');
```
So, for the properties you want to get:
```js
const selectedProps = {
..._.pick(object, ['a', 'b']),
_.get(object, 'c.d')
}
``` | You can create a `flatPick()` function. The function iterates the array of paths. and uses `_.get()` to get the value of the `path`, and `_.set()` to add the last part of the path as property on the result object:
```js
function flatPick(object, paths) {
const o = {};
paths.forEach(path => _.set(
o,
_.last(path.split('.')),
_.get(object, path)
));
return o;
}
var object = {
a: 'a',
b: 'b',
c: {
d: 'd',
e: {
f: 'f'
}
}
};
var result = flatPick(object, ['a', 'b', 'c.d', 'c.e.f']);
console.log(result);
```
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
``` |
54,874,052 | Now i have code like this:
```
var object = {
a: 'a',
b: 'b',
c: {
d: 'd'
}
}
_.get(object).pick(['a', 'b']).value();
```
How to deep pick property 'd' like:
```
_.get(object).pick(['a', 'b', 'c.d']).value();
``` | 2019/02/25 | [
"https://Stackoverflow.com/questions/54874052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10885808/"
] | In case you insist in using Lodash, consider using the [\_.get()](https://lodash.com/docs/4.17.11#get) function:
```
_.get(object, 'c.d');
```
So, for the properties you want to get:
```js
const selectedProps = {
..._.pick(object, ['a', 'b']),
_.get(object, 'c.d')
}
``` | This can work for `lodash`:
```
function pickNested(object: Json, fields: string[]) {
const shallowFields = fields.filter((field) => !field.includes('.'));
const deepFields = fields.filter((field) => field.includes('.'));
const initialValue = _.pick(object, shallowFields) as Json;
return deepFields.reduce((output, field) => {
const key = _.snakeCase(field);
output[key] = _.get(object, field);
return output;
}, initialValue);
}
```
and:
```
const json = {
id: '10',
user: {
email: 'david.i@example.com',
},
};
const newData = pickNested(json, ['id', 'user.email']);
console.log('newData ->', newData);
/*
{
id: '10',
user_email: 'david.i@example.com',
};
*/
``` |
54,874,052 | Now i have code like this:
```
var object = {
a: 'a',
b: 'b',
c: {
d: 'd'
}
}
_.get(object).pick(['a', 'b']).value();
```
How to deep pick property 'd' like:
```
_.get(object).pick(['a', 'b', 'c.d']).value();
``` | 2019/02/25 | [
"https://Stackoverflow.com/questions/54874052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10885808/"
] | You can create a `flatPick()` function. The function iterates the array of paths. and uses `_.get()` to get the value of the `path`, and `_.set()` to add the last part of the path as property on the result object:
```js
function flatPick(object, paths) {
const o = {};
paths.forEach(path => _.set(
o,
_.last(path.split('.')),
_.get(object, path)
));
return o;
}
var object = {
a: 'a',
b: 'b',
c: {
d: 'd',
e: {
f: 'f'
}
}
};
var result = flatPick(object, ['a', 'b', 'c.d', 'c.e.f']);
console.log(result);
```
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
``` | This can work for `lodash`:
```
function pickNested(object: Json, fields: string[]) {
const shallowFields = fields.filter((field) => !field.includes('.'));
const deepFields = fields.filter((field) => field.includes('.'));
const initialValue = _.pick(object, shallowFields) as Json;
return deepFields.reduce((output, field) => {
const key = _.snakeCase(field);
output[key] = _.get(object, field);
return output;
}, initialValue);
}
```
and:
```
const json = {
id: '10',
user: {
email: 'david.i@example.com',
},
};
const newData = pickNested(json, ['id', 'user.email']);
console.log('newData ->', newData);
/*
{
id: '10',
user_email: 'david.i@example.com',
};
*/
``` |
21,994,404 | I've got a surfaceview and a gameThread class.
The gameThread keeps updating and painting on the SurfaceView class.
Now when I exit the app (By pressing the home or back button) I get a message that the app force closed. That's because the GameThread still tries to draw on the erased surfaceview...
So how do i properly end the app without getting this force close notification? I would like the GameThread class to stop when the back button is pressed. It should pause when pressing on home and running in the background. When re-entering the still running game it should resume....
Any ideas?
This is my GameThread class:
```
public class GameThread extends Thread{
private GameView view;
public boolean isRunning = false;
public GameThread(GameView view) {
this.view = view;
}
public void setRunning(boolean setRunning) {
isRunning = setRunning;
}
public void run() {
while(isRunning) {
Canvas c = null;
view.update();
try {
c = view.getHolder().lockCanvas();
synchronized (view.getHolder()) {
view.draw(c);
}
}finally {
if(c != null) {
view.getHolder().unlockCanvasAndPost(c);
}
}
}
}
```
It keeps updating my GameView class:
public class GameView extends SurfaceView{
```
private GameThread gameThread;
public GameView(Context context, Activity activity) {
super(context);
gameThread = new GameThread(this);
init();
holder = getHolder();
holder.addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
gameThread.setRunning(true);
gameThread.start();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
});
}
public void init() {
}
public void update() {
}
public void draw(Canvas canvas) {
super.draw(canvas);
}
}
```
When pressing home my logcat shows this up:
```
02-24 18:24:59.336: E/SurfaceHolder(839): Exception locking surface
02-24 18:24:59.336: E/SurfaceHolder(839): java.lang.IllegalStateException: Surface has already been released.
02-24 18:24:59.336: E/SurfaceHolder(839): at android.view.Surface.checkNotReleasedLocked(Surface.java:437)
02-24 18:24:59.336: E/SurfaceHolder(839): at android.view.Surface.lockCanvas(Surface.java:245)
02-24 18:24:59.336: E/SurfaceHolder(839): at android.view.SurfaceView$4.internalLockCanvas(SurfaceView.java:872)
```
Main activity:
```
public class MainActivity extends Activity {
private RelativeLayout relativeLayout;
private GameView gameView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gameView = new GameView(this, this);
setContentView(R.layout.activity_main);
relativeLayout = (RelativeLayout)findViewById(R.id.mainView);
relativeLayout.addView(gameView);
}
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
gameView.onBackPressed();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
``` | 2014/02/24 | [
"https://Stackoverflow.com/questions/21994404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2410644/"
] | Here's the same code rewritten with transaction support:
```
// Start transaction
pool.startTransaction().then((trans) {
// Delete all from table
trans.query('DELETE FROM myTable WHERE 1=1').then((r) {
// Prepare statement
trans.prepare('REPLACE INTO myTable (Id, Name, Description) VALUES (?,?,?)').then((query) {
// Execute query inserting multiple rows
query.executeMulti(myArrayValues).then((results) {
// Stuff here
// Commit
trans.commit().then((r) { ...
``` | Use `ConectionPool.startTransaction()`.
```
* You
* must use this method rather than `query('start transaction')` otherwise
* subsequent queries may get executed on other connections which are not
* in the transaction.
```
Haven't tried it myself yet. |
12,871,492 | In our team we are evaluating to use the kanban board as an organization tool for software development. The development phase will take about 6 months with a team of 5.
We have as input all the functional requirements agreed with the client, business rules and use cases - in other words, macroscopic requirements. We will convert these rules in stories to be "atomic" process units for the kanban board. The kanban itself will be used as a performance evaluation tool and progress roadmap.
The Kanban "prescribes" to have a fixed amount of stories for each stage, but as the software is new and complex, the "stories" will be probably some hundreds - so I guess that putting all the stories in the backlog at the beginning of the development wouldn't be a smart move.
What would it be the best practice for this case? | 2012/10/13 | [
"https://Stackoverflow.com/questions/12871492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/273567/"
] | First, few teams set limits for backlog. Kanban advises work in progress (WIP) limits. Items in backlog are rarely considered "in progress."
Second, considering you, more or less, know the scope of the project it wouldn't make much sense of forcing yourself to artificially limit number of items in backlog.
At the same time you're right that putting a few hundreds items in backlog makes no sense. The board would be overcrowded and its usefulness would drop significantly.
Typical strategies to organize backlog is such cases include:
* Keeping epic stories/features in backlog and splitting them into detailed stories/tasks only when you start working in them. This way you have far fewer items, while you're still able to deal with detailed tasks on development stages.
* Stacking stories which are going to be a part of the same part of an app. If you already split your scope, there's no point in artificially hiding this information. You can, however, stack work items that are connected or will be done at the same time. It makes backlog cleaner and, once you start building the items, you can unstack them totally easy.
* Staging backlog. If you have a rough plan how your development will be going you can have a couple of stages of your backlog. Early one which is a box where you store all the features you will build (it can be even a physical box attached to the board) and later one which shows only work for the very next time period. This way you see fewer items on the board, yet still, technically all the work is there.
Of course mixing all these ideas is possible, and even encouraged, whenever it seems reasonable.
BTW: You can see visualization of a couple of these techniques in [this presentation](http://www.slideshare.net/pawelbrodzinski/kanban-basics-5834758) (slide 21). | Henrik Kniberg in his free book about Kanban describes how setting WIP limit to backlog helps focus on most important functionality first.
I think this is good strategy especially for product owner. Backlog contains only stories to be developed in upcoming period while other stories might be in mind map or 'wishlist'. |
12,871,492 | In our team we are evaluating to use the kanban board as an organization tool for software development. The development phase will take about 6 months with a team of 5.
We have as input all the functional requirements agreed with the client, business rules and use cases - in other words, macroscopic requirements. We will convert these rules in stories to be "atomic" process units for the kanban board. The kanban itself will be used as a performance evaluation tool and progress roadmap.
The Kanban "prescribes" to have a fixed amount of stories for each stage, but as the software is new and complex, the "stories" will be probably some hundreds - so I guess that putting all the stories in the backlog at the beginning of the development wouldn't be a smart move.
What would it be the best practice for this case? | 2012/10/13 | [
"https://Stackoverflow.com/questions/12871492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/273567/"
] | First, few teams set limits for backlog. Kanban advises work in progress (WIP) limits. Items in backlog are rarely considered "in progress."
Second, considering you, more or less, know the scope of the project it wouldn't make much sense of forcing yourself to artificially limit number of items in backlog.
At the same time you're right that putting a few hundreds items in backlog makes no sense. The board would be overcrowded and its usefulness would drop significantly.
Typical strategies to organize backlog is such cases include:
* Keeping epic stories/features in backlog and splitting them into detailed stories/tasks only when you start working in them. This way you have far fewer items, while you're still able to deal with detailed tasks on development stages.
* Stacking stories which are going to be a part of the same part of an app. If you already split your scope, there's no point in artificially hiding this information. You can, however, stack work items that are connected or will be done at the same time. It makes backlog cleaner and, once you start building the items, you can unstack them totally easy.
* Staging backlog. If you have a rough plan how your development will be going you can have a couple of stages of your backlog. Early one which is a box where you store all the features you will build (it can be even a physical box attached to the board) and later one which shows only work for the very next time period. This way you see fewer items on the board, yet still, technically all the work is there.
Of course mixing all these ideas is possible, and even encouraged, whenever it seems reasonable.
BTW: You can see visualization of a couple of these techniques in [this presentation](http://www.slideshare.net/pawelbrodzinski/kanban-basics-5834758) (slide 21). | I must disagree: limits in backlog is a possibility. Probably not in the input column, but for instance if process has some prioritization columns, highest priority column can contain a limit thus saying that one may not push to many high priority tasks, because WIP cannot maintain such pace and they will be hanging dead there.
[Kanban board looks like this](http://www.eylean.com/Images/backlog_limits.jpg)
 |
12,871,492 | In our team we are evaluating to use the kanban board as an organization tool for software development. The development phase will take about 6 months with a team of 5.
We have as input all the functional requirements agreed with the client, business rules and use cases - in other words, macroscopic requirements. We will convert these rules in stories to be "atomic" process units for the kanban board. The kanban itself will be used as a performance evaluation tool and progress roadmap.
The Kanban "prescribes" to have a fixed amount of stories for each stage, but as the software is new and complex, the "stories" will be probably some hundreds - so I guess that putting all the stories in the backlog at the beginning of the development wouldn't be a smart move.
What would it be the best practice for this case? | 2012/10/13 | [
"https://Stackoverflow.com/questions/12871492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/273567/"
] | I must disagree: limits in backlog is a possibility. Probably not in the input column, but for instance if process has some prioritization columns, highest priority column can contain a limit thus saying that one may not push to many high priority tasks, because WIP cannot maintain such pace and they will be hanging dead there.
[Kanban board looks like this](http://www.eylean.com/Images/backlog_limits.jpg)
 | Henrik Kniberg in his free book about Kanban describes how setting WIP limit to backlog helps focus on most important functionality first.
I think this is good strategy especially for product owner. Backlog contains only stories to be developed in upcoming period while other stories might be in mind map or 'wishlist'. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.