source
sequence | text
stringlengths 99
98.5k
|
---|---|
[
"latin.stackexchange",
"0000009444.txt"
] | Q:
Switches Between Direct & Indirect Speech in Suetonius-Supplemental
Suetonius, Caius (Caligula) 58: concerns the assassination of Emperor Caius (Caligula) on January 21st., AD 41. At this point, the assassins have struck the first blows and Caius, still alive, collapses to the floor:
...alii...iacentem contractisque membris clamitantem se vivere ceteri vulneribus triginta confecerunt; nam erat omnium: "repete!" quidam etiam per obscaena ferrum adegerunt.
The passage is narrated by the others (alii) and is therefore written indirectly.
As Caligula lies on the floor, with writhing limbs, crying out that he was still alive (indirect, accusative-infinitive, speech) they (the assassins) finished the job with thirty wounds—given as confecerunt, the perfect tense.
Why the switch from indirect speech? The others (alii) are still narrating the story: they-said-that-they (the assassins) finished the job—confecisse?
A:
I need a bit more context to come up with an explanation:
Cum in crypta, per quam transeundum erat, pueri nobiles ex Asia ad edendas in scaena operas evocati praepararentur, ut eos inspiceret hortareturque restitit, ac nisi princeps gregis algere se diceret, redire ac repraesentare spectaculum (2) voluit. Duplex dehinc fama est: alii tradunt [here begins indirect speech] adloquenti pueros a tergo Chaeream cervicem gladio caesim graviter percussisse praemissa voce: “Hoc age!” dehinc Cornelium Sabinum, alterum e coniuratis, tribunum ex adverso traiecisse pectus; alii Sabinum summota per conscios centuriones turba signum more militiae petisse et Gaio “Iovem” dante Chaeream exclamasse: “Accipe ratum!” (3) respicientique maxillam ictu discidisse [here ends indirect speech]. Iacentem contractisque membris clamitantem se vivere ceteri vulneribus triginta confecerunt; nam signum erat omnium: “Repete!”. Quidam etiam per obscaena ferrum adegerunt.
First Suetonius uses direct speech, voluit, to narrate what happened. He presents it as fact. Then he says, "from hereon, there are two different stories: some say that ..." (alii tradunt). He proceeds to give both versions in a.c.i., the second one introduced by another alii. When he continues with direct speech (confecerunt), we must assume that he is finished with the uncertain alternative stories and returns to a factual narration about which there is no doubt (modern historians have a lot to say about that, though).
The infinitive vivere is part of the confecerunt sentence and indirectly depends upon it: "they killed him lying down and...crying out that he was alive ( vivere )". So vivere depends on clamitantem, which in turn belongs to the object ("him when he was crying out") of confecerunt. You couldn't read vivere etc. as yet another a.c.i., for then the finite verb confecerunt would be left dangling.
|
[
"stackoverflow",
"0014248949.txt"
] | Q:
Your login attempt was not successful. Please try again. in asp.net although password is reset
I have a problem with one account in asp.net, although I reset the password I still get this error when I am trying to login: "Your login attempt was not successful. Please try again"
How can I see the real message why this is happening? According to the database table for aspnet membership everything looks good:
Every advice is appreciated.
Thanks in advance, Laziale
A:
put break point right at the very statement that authenticate your login information. Then debug and see if there's any exception. Remember to wrap with try..catch statement and put another breakpoint inside catch statement.
|
[
"scifi.stackexchange",
"0000095866.txt"
] | Q:
What is the title of this story about settlers who have to give back cells to a sentient species?
Settlers land on a supposedly unoccupied planet, and raise livestock on an early life stage of a sentient species. The early stage looks like grass. After the sentient species begins its next stage of life, they realize that they have to give back the cells they took from the species.
A:
Sounds like Velvet Fields, by Anne McCaffrey, first published in the speculative fiction magazine "Worlds of If" in its November-December 1973 issue and then in "The Girl Who Heard Dragons", a collection of McCaffrey's short stories.
The planet is apparently deserted:
Although Survey had kept a watch on the planet for more than thirty years standard and the cities were obviously on a standby directive, the owners remained conspicuous by their absence.
The settlers raise livestock on the grass:
We pastured the cattle in neatly separated velvet fields. Martin Chavez worried when close inspection disclosed that each velvet field was underpinned by its own ten-meter-thick foundation of ancient, rock-hard clay. Those same foundations housed what seemed to be a deep irrigation system.
But the grass turns out to be the first stage of the native sentient species:
“You mean, the plants are the people?”
“What else have I been saying? They are born from the Trees.”
And in the end, the settlers who took nutrition from the planet give back parts of their bodies:
We had to give back to the soil what we had taken from it. The handless Zobranoirundisi, recognizing his missing member from the cells now incorporated into the fingers of a young colony child nurtured on milk from cattle fed in the velvet fields, had every right to reclaim what was undeniably his own flesh. The legless Zobranoirundisi could not be condemned to a crippled existence when the Terran child had used the same cells to run freely for seven years on land where previously only Zobranoirundisi had trod.
|
[
"ru.stackoverflow",
"0000416696.txt"
] | Q:
Xcode 1.3 ,I use first instead any object.Cannot invoke>
Cannot invoke 'locationInView' with an argument list of type '(AnyObject!)'
override func touchesMoved(touches: Set, withEvent event: UIEvent) {
var newPoint = touches.first.locationInView(self.drawView)
lines.append(Line(start: lastPoint, end: newPoint! , color :drawColor))
lastPoint = newPoint
self.setNeedsDisplay()
}
A:
Нужно привести тип, по умолчанию в Set лежат объекты NSObject:
if let newPoint = (touches.first as? UITouch)?.locationInView(self.drawView) {
//...
}
|
[
"stackoverflow",
"0017640502.txt"
] | Q:
Couldn't add dependency to pom.xml
I coudn't add new dependency to pom.xml.
My steps :
I use Spring Template Project MVC.
Open in Eclise pom.xml.
Open "Dependency" tab.
Add my required dependency: spring-tx.
Save my changes. But my changes didn't affect Dependency "Hierarchy" and "Effective POM" tabs.
Clean and Build Project.
In my pom.xml dependency spring-tx disappeared. So my problem still here.
How can I add dependency to pom.xml and save it into when project Build?
A:
Use the pom "editor" tab instead.
|
[
"stackoverflow",
"0058149958.txt"
] | Q:
how to remove horizontal line in circumference with plot()
I want to plot a circumference.
The function to draw points on the circumference is:
d_cir = function (a=1){
x = seq(-a,a,.005)
y = sqrt(a^2-x^2)
x = matrix(c(x,x), ncol=1)
y = matrix(c(y,-y), ncol=1)
matrix(c(x, y), ncol = 2)
}
Then i plot:
plot(d_cir(), asp = 1, type="l")
How to remove the horizontal line from plot?
Thank you, Manuel
A:
One tiny adjustment. You want c(x, x) to go from -1 to 1 to 1 to -1 so you need to reverse the order of x the second time. Since y is symmetrical y and rev(y) are the same so you don't need to reverse that one:
d_cir = function (a){
x = seq(-a,a,.005)
y = sqrt(a^2-x^2)
x = matrix(c(x, rev(x)), ncol=1)
y = matrix(c(y,-y), ncol=1)
matrix(c(x, y), ncol = 2)
}
plot(d_cir(1), asp = 1, type="l")
This does the same thing but the code is a bit simpler:
d_cir <- function (a){
x <- seq(-a, a, .005)
y <- sqrt(a^2 - x^2)
x <- c(x, rev(x))
y <- c(y, -y)
cbind(x, y)
}
plot(d_cir(1), asp = 1, type="l")
|
[
"stackoverflow",
"0048221762.txt"
] | Q:
Error compiling VS Code extension with dependency on another extension
I've built a VS Code extension that wants to re-use some code from another extension. It doesn't compile because of duplicate vscode declarations on the build path. Any idea if this is a real issue or if I can tweak my build path to make it work?
The error is as follows:
lerna ERR! > [email protected] build /.../import-cost/packages/vscode-sample-with-dependency
lerna ERR! > tsc -p ./
lerna ERR!
lerna ERR! node_modules/vscode/vscode.d.ts(11,15): error TS2451: Cannot redeclare block-scoped variable 'version'.
lerna ERR! node_modules/vscode/vscode.d.ts(239,15): error TS2300: Duplicate identifier 'Position'.
lerna ERR! node_modules/vscode/vscode.d.ts(358,15): error TS2300: Duplicate identifier 'Range'.
lerna ERR! node_modules/vscode/vscode.d.ts(459,15): error TS2300: Duplicate identifier 'Selection'.
lerna ERR! node_modules/vscode/vscode.d.ts(504,3): error TS2300: Duplicate identifier 'Keyboard'.
... and many more ...
Sample project is available here:
https://github.com/guw/import-cost (commit c184a4c2)
To reproduce:
clone
npm install
npm run build
A:
Try adding this mapping into your tsconfig.json
"baseUrl": "",
"paths": {
"vscode": ["node_modules/vscode"]
}
This problem seems to be a result of this issue. See here for reference.
https://github.com/Microsoft/TypeScript/issues/6496#issuecomment-351435136
|
[
"stackoverflow",
"0041740402.txt"
] | Q:
How to inline display file input?
How do I set multiple file input on the same line ? Like radio-inline sets radio buttons on the same line. Is there any way to do this for file input ?
input[type="file"] {
display: none;
}
.custom-file-upload {
border: 1px solid #ccc;
display: inline-block;
padding: 6px 12px;
cursor: pointer;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"/>
<div class = "form-inline">
<label for="file-upload" class="custom-file-upload">
<i class="fa fa-cloud-upload"></i> Custom Upload
</label>
<input id="file-upload" type="file"/>
</div>
<div class = "form-inline">
<label for="file-upload" class="custom-file-upload">
<i class="fa fa-cloud-upload"></i> Custom Upload
</label>
<input id="file-upload" type="file"/>
</div>
A:
Use inline-block on form-inline.
input[type="file"] {
display: none;
}
.custom-file-upload {
border: 1px solid #ccc;
display: inline-block;
padding: 6px 12px;
cursor: pointer;
}
.form-inline{
display:inline-block;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"/>
<div class = "form-inline">
<label for="file-upload" class="custom-file-upload">
<i class="fa fa-cloud-upload"></i> Custom Upload
</label>
<input id="file-upload" type="file"/>
</div>
<div class = "form-inline">
<label for="file-upload" class="custom-file-upload">
<i class="fa fa-cloud-upload"></i> Custom Upload
</label>
<input id="file-upload" type="file"/>
</div>
A:
Cover both of those inputs withing single div tag with class form-inline.
Do you mean something like this. Check your fiddle. Its updated. --
<div class = "form-inline">
<label for="file-upload" class="custom-file-upload">
<i class="fa fa-cloud-upload"></i> File1
</label>
<input id="file-upload" type="file"/>
<label for="file-upload" class="custom-file-upload">
<i class="fa fa-cloud-upload"></i> File1
</label>
<input id="file-upload" type="file"/>
</div>
|
[
"stackoverflow",
"0019764208.txt"
] | Q:
Avoid space between DOM when using pseudo class :before
I must be doing some basic thing wrong since I don't want the space between each letters below.
HTML:
<i class="icon icon1"></i>
<i class="icon icon2"></i>
<i class="icon icon3"></i>
CSS:
.icon {
display: inline-block;
position: relative;
padding: 3px;
background: yellow;
margin: 0;
}
.icon1:before {
content: "A";
}
.icon2:before {
content: "B";
}
.icon3:before {
content: "C";
}
Link: http://jsfiddle.net/qhoc/rkRBY/
I believe the space is automatically there between each character unless font-size:0. My requirements are:
All chars must be on same line
There will be more icon4, icon5, etc..
No space between them without changing font-size
OK to add HTML wrapper but would not touch JS or changing <i> to something else. I am using Bootstrap by the way.
Let me know if there is workaround! Thanks.
A:
There are two good ways afaik,
Don't give space in HTML markup between the elements (or)
add display: table-cell to that element.
Try this:
.icon {
display: table-cell;
/* removed padding: 3px; */
position: relative;
background: yellow;
margin: 0px;
}
.icon1:before {
content: "A";
}
.icon2:before {
content: "B";
}
.icon3:before {
content: "C";
}
Working Fiddle
|
[
"stackoverflow",
"0059752798.txt"
] | Q:
Detect if NODE.JS script is called direct via bash (unix) / cmd (windows) or imported (ESM module loader)
How can I detect whether my node.js file was called directly from console (windows and unix systems) or loaded using the ESM module import (import {foo} from 'bar.js')
The question was already answered for regular node.js files (Detect if called through require or directly by command line) but since require is not available in .mjs files with --experimental-modules turned on, I am in need of a different solution.
A:
Node.js does not currently expose that information to es modules, and it is not certain whether it ever will[0]. I'd say the safest option for now is to put your CLI logic into a separate file.
0: https://github.com/nodejs/modules/issues/274
|
[
"stackoverflow",
"0056369247.txt"
] | Q:
How to add new widget in GridLayout without resizing older widgets?
I have added GridLayout to ScrollView, and I'm adding widgets in GridLayout dynamically from python program.Instead of using more space of window it's resizing height of older widgets.What am i doing wrong here?
I tried putting BoxLayout inside GridLayout but it's not working.
I also tried to add widgets directly to ScrollView but i found out ScrollView only supports one widget.
My kv code:
<Downloading>:
my_grid: mygrid
GridLayout:
cols: 1
size_hint_y : None
hight: self.minimum_height
id: mygrid
My python code:
class Downloading(ScrollView):
set_text = ObjectProperty()
my_grid = ObjectProperty()
def __init__(self, select, link, path, username, password):
self.select = select
self.link = link
self.path = path
self.username = username
self.password = password
self.p_bar = []
self.stat = []
self.parent_conn, self.child_conn = Pipe()
p = Process(target=main, args=(self.child_conn, self.select,
self.link, self.path,
self.username, self.password))
p.start()
super().__init__()
self.event = Clock.schedule_interval(self.download_GUI, 0.1)
def newFile(self, title):
# self.newId = "stat" + str(len(self.p_bar) + 1)
self.stat.append(Label(text=''))
self.p_bar.append(ProgressBar())
self.my_grid.add_widget(Label(text=title))
self.my_grid.add_widget(self.stat[-1])
self.my_grid.add_widget(self.p_bar[-1])
def download_GUI(self, a):
temp = self.parent_conn.recv()
print(temp)
if temp == "new":
self.downloading = True
return
if self.downloading:
self.newFile(temp)
self.downloading = False
return
if type(temp) == type({}):
self.complete = temp['complete']
if not self.complete:
status = "{0}//{1} @ {2} ETA: {3}".format(temp['dl_size'],
temp['total_size'],temp['speed'],temp['eta'])
self.stat[-1].text = status
self.p_bar[-1].value = temp['progress']
return
if temp == "end":
self.event.cancel()
Clock.schedule_once(exit, 3)
A:
I believe you just need to set the height for each widget that you add to your GridLayout. For example:
self.my_grid.add_widget(Label(text=title, size_hint=(1, None), height=50))
You might need to do the same for the other widgets you are adding. The GridLayout may give the initially added widgets more space than that, but will not squeeze them any any tighter than your specified height.
|
[
"stackoverflow",
"0059910561.txt"
] | Q:
How to rename files in a folder with ".csv" at the end??[R]
setwd("C:\\Users\\Note\\Documents\\Folder")
n <- dir(pattern = ".csv")
names<-as.character(c(1:length(n)))
file.rename(n,names)
I am trying to rename several worksheets to an id 1,2,3,4,5,6 etc But when I do this the worksheets are no longer ".csv" files. How to add ".csv" to the rename function?
Is there any way to make "n" stay in sequence 1,2,3,4,5,6, so that if I add a new spreadsheet it will be the last one in "n"?
n = https://imgur.com/Z1KVqh2
A:
Try this instead of your third line
names <- paste0(1:length(n), ".csv")
The numbers will be automatically coerced to character format.
|
[
"math.stackexchange",
"0001440085.txt"
] | Q:
Calculating the limit of two unusually hard functions
I'm working my way through a single-variable analysis book right now, and the past limit problems have been no problem at all. But I got stuck at these two:
$$ \lim_{x\to-\infty} \frac{x}{1 + \sqrt{x^2 + x + 1}}$$
\\
$$ \lim_{x\to 0 } \frac{\ln(\cos x)}{x}$$
Direct insertion of the limit value results in undefined expressions, so the correct path must be to rewrite the functions right? My attempt at the first one went something like this:
$$\lim_{x\to-\infty} \frac{x}{1 + \sqrt{x^2 + x + 1}} = \lim_{x\to-\infty} \frac{x * (1 - \sqrt{x^2 + x + 1})}{1 - (x^2 + x + 1)}$$
But then I got completely stuck, and the second one I cannot even get anywhere with. What am I missing? What's the trick?
EDIT: I should add, I am not allowed to use L'hospitals rule.
A:
Divide the numerator and denominator by $x$ to get
$\frac{1}{\frac{1+\sqrt{x^2+x+1}}{x}} = \frac{1}{\frac{1}{x} + \sqrt{1+\frac{1}{x} + \frac{1}{x^2}}}$
Now, taking the limit gives 1.
|
[
"rus.stackexchange",
"0000456378.txt"
] | Q:
Вид сказуемого: ПГС или СГС
Как бы вы охарактеризовали вид сказуемого в этом предложении?
Он почувствовал необходимость расчесться единожды навсегда со своею
молодостью и круто поворотить свою жизнь.
A:
Он почувствовал необходимость расчесться единожды навсегда со своею молодостью и круто поворотить свою жизнь.
Однородные составные глагольные сказуемые:
Вспомогательная часть - почувствовал необходимость - фразеологизм (=захотел, решил).Грамматическое значение необходимости.
2 инфининива - расчесться и поворотить.Лексическое значение СГС.
|
[
"askubuntu",
"0000623796.txt"
] | Q:
How to disable xubuntu touchpad
I have a Lenovo T410, and the touchpad acts 'quirky' occasionally (cursor jumps around screen).
Is a toggle function that allows me to disable the touchpad when I want (and use the eraser pad), and re enable it when I want?
A:
You can look for your touchpad id using "xinput" command.
Then disable touchpad by
xinput disable <id>
|
[
"stackoverflow",
"0014784566.txt"
] | Q:
python, how to modify a dict attribute of a class instance
I have an instance that has a dict. how can i modify the dict in a function, by the key from the dict?
class myclass:
def __init__(self):
self.mydict = {'number':0}
def myfunction(foo):
foo.mydict[number] += 10 #<- doesnt work gives me 'global name number not defined'
instance = myclass()
myfunction(instance)
hope you can help me,
thanks!
A:
Actually, this has nothing to do with it being a class attribute:
foo.mydict['number'] += 10
The key need to be a string.
|
[
"blender.stackexchange",
"0000163777.txt"
] | Q:
How to enlarge dynamic paint cache size (Blender 2.8)?
I try to create 900-frame animation using dynamic paint in Blender 2.8.
When I try to play animation or bake all dynamics calculations are made until frame #250 and that's all.
Does anyone know where the cache size settings for dynamic paint are (if there are any)?
Or maybe there is some workaround to calculate and bake all the animation?
A:
In the Dynamic paint controls you have Frame Start and End.
|
[
"stackoverflow",
"0007822739.txt"
] | Q:
Error: Invalid character in name at (1)
I am trying to compile a fortran file along with some .h files in FORTRAN. The .h files contain definition for common blocks of variable. When I compile them in Fortran, I get the following error:
integer knue,ke,knumu,kmu,knutau,ktau,ku,kd,kc,ks,kt,kb,kgamma,
1
Error: Invalid character in name at (1)
The code where this error occurs is,
Now my question is, does this "1" point where the error is?
The lines of code which this errors points is,
integer knue,ke,knumu,kmu,knutau,ktau,ku,kd,kc,ks,kt,kb,kgamma,
& kw,kz,kgluon,kh1,kh2,kh3,khc,ksnue,kse1,kse2,ksnumu,ksmu1,
& ksmu2,ksnutau,kstau1,kstau2,ksu1,ksu2,ksd1,ksd2,ksc1,ksc2,
& kss1,kss2,kst1,kst2,ksb1,ksb2,kn1,kn2,kn3,kn4,kcha1,kcha2,
& kgluin,kgold0,kgoldc
Also, is there something wrong with the way continuation are used. I am using gfortran to compile this file.
A:
It looks like you are using Fortran 77 style line continuations and trying to compile with Fortran 90 style free format code. You either need to compile using the gfortran -ffixed-form option, or format the code using Fortran 90 style line continuations:
integer knue,ke,knumu,kmu,knutau,ktau,ku,kd,kc,ks,kt,kb,kgamma, &
kw,kz,kgluon,kh1,kh2,kh3,khc,ksnue,kse1,kse2,ksnumu,ksmu1, &
ksmu2,ksnutau,kstau1,kstau2,ksu1,ksu2,ksd1,ksd2,ksc1,ksc2, &
kss1,kss2,kst1,kst2,ksb1,ksb2,kn1,kn2,kn3,kn4,kcha1,kcha2, &
kgluin,kgold0,kgoldc
|
[
"physics.stackexchange",
"0000197515.txt"
] | Q:
A particle in a 1D box: what is the meaning of velocity?
In the box $x = 0$ to $x = L$, $V = 0$, and for $x < 0$ and $x > L$, $V = \infty$ (infinite potential well).
The eigenvalues of the Hamiltonian are:
$$E_n = \frac{n^2 h^2}{8L^2} \, .$$
Since as $V = 0$ in the box, this is kinetic energy only, so:
\begin{align}
\frac{p^2}{2m} &= \frac{n^2 h^2}{8L^2} \\
p^2 &= \frac{n^2 h^2 m}{4L^2} \, .
\end{align}
This is in fact the expectation value of the squared momentum $\langle p^2 \rangle$.
With $\langle p^2 \rangle = m^2\langle v^2 \rangle$ then
$$\langle v^2 \rangle = \frac{n^2 h^2}{4m L^2} \, .$$
We know that for eigenstates of bound particles $\langle v \rangle = 0$, so the average velocity of the particle in the well is $0$, which makes perfect sense.
So what is the physical meaning of
$$\sqrt{\langle v^2 \rangle} = \sqrt{ \frac{n^2 h^2}{4m L^2}} = \frac{1}{\sqrt{m}} \frac{nh}{2L} \, ?$$
Or am I thinking too "classical"?
A:
Consider a molecule of oxygen in a balloon.
You know that at nonzero temperature all those molecules are bouncing around in all directions.
Of course, the mass of air doesn't have any net motion in any direction.
Indeed, the average velocity of each molecule is zero:
$$\langle v \rangle = 0 \, .$$
Of course, the average energy of any particular molecule is (from the equipartition theorem) $\langle E \rangle = (3/2) k_b T$.
We can rewrite this as
\begin{align}
\left\langle \frac{p^2}{2m} \right\rangle &= \frac{3}{2} k_b T \\
\left\langle v^2 \right\rangle &= \frac{3 k_b T}{m} \neq 0 \, .
\end{align}
The point here is that having zero average velocity definitely doesn't mean you have zero average squared velocity.
Zero average velocity just means you go left as often as you go right.
You can still be bouncing around all over the place.
You probably have an intuitive idea that there should be something with dimensions of velocity, not velocity squared, which represents the "typical" speed of a particle.
That's precisely what
$$\sqrt{\langle v^2 \rangle}$$
is.
Think of it like this: if half the particles are moving at velocity $v$ and the other half are moving at $-v$, then you get
$$\sqrt{\langle v^2 \rangle} = v \, .$$
So in this simple case the square root of the mean square velocity really is just the average speed.
You might think a simpler definition of "typical speed" is
$$\langle | v | \rangle$$
because this is literally the average speed.
In a sense this is simpler, but the root mean square is more useful because, as you can see from your own post, it's directly related to the energy.
Being related to the energy means that the root mean square velocity is also easily related to things like pressure, etc. which is why we often use it instead of the average absolute value of velocity (although both are useful).
Of course, this was all a classical picture, but in some ways the quantum case is similar.
For example, if you could cook up an experiment to directly measure the square momentum of the particle in the box, the result averaged over an ensemble of particles would be the result from the original post (I use velocity and momentum interchangeably as they differ only by a scale factor $m$).
In that sense, the expression calculated for $\langle p^2 \rangle$ is just exactly what it sounds like: it's the average you would find if you measured the squared momentum on an ensemble of particle in a box quantum systems.
Taking the square root to get $\sqrt{\langle p^2 \rangle}$ you just have, like the classical case, a measure of the typical momentum that happens to be really useful because it easily connects to energy, pressure, etc.
Of course, the average here is over an ensemble of quantum systems, so by "typical" we mean typical as averaged over the ensemble, not necessarily as averaged over time for a single particle.
There is at least one important difference though: a quantum system in the ground state has nonzero mean square momentum, but cannot give off any energy.
This is very different from the classical case where nonzero mean square momentum means there's internal energy which can be transferred to another system (i.e. measured).
This is related to the uncertainty principle.
Quantum systems have "fluctuations"$^{[a]}$ which are not thermal in nature.
$[a]$: Calling the fact that quantum systems have nonzero mean square momentum in the ground state "fluctuations" is a dangerous game because it can make the reader think those "fluctuations" are just like classical ones.
However, they are not.
For example, classical fluctuations have finite bandwidth because the underlying microscopic processes have internal time scales.
Quantum "fluctuations" do not.
What we typically call "quantum fluctuations" are really the manifestation of sampling a wave function as it shows up in the classical measurement apparatus.
|
[
"electronics.stackexchange",
"0000193012.txt"
] | Q:
Question about the registers of an ADC
There are two things that confuses me in the below text:
"The ADC uses the successive-approximation method to perform the
conversion.The HCS12 uses two 8-bit registers to hold a ananlog to digital conversion result. The result can be stored either right- or left-justified. The A/D conversion is performed in a sequence from one to eight samples."
1- I always thought that registers are storage locations in the CPU. So ADCs would have their own registers too?
2- What are the functionality and meaning of the right- or left-justified registers?
A:
I always thought that registers are storage locations in the CPU. So
ADCs would have their own registers too?
Registers can be storage locations in any device. You'll find the in ADCs, accelerometers, EEPROMs, etc.
What are the functionality and meaning of the right- or left-justified
registers?
This implies that the result is less than the 16 bits allocated to it. Suppose the ADC produces a 12 bit result. In the left justified case, it would be shifted to the so the MSB is in the MSB of the 16 bit space, like so:
16 |3|2|1|0
MSB|...|LSB|X|X|X|X
Right justified is the reverse, where the LSB is in the LSB of the 16 bit space.
16|15|14|13|12 | |0
X | X| X| X|MSB|...|LSB
|
[
"stackoverflow",
"0056679232.txt"
] | Q:
How to read output file for collecting stats (post) processing
Summary
I need to build a set of statistics during a Camel server in-modify-out process, and emit those statistics as one object (a single json log line).
Those statistics need to include:
input file metrics (size/chars/bytes and other, file-section specific measures)
processing time statistics (start/end/duration of processing time, start/end/duration of metrics gathering time)
output file metrics (same as input file metrics, and will be different numbers, output file being changed)
The output file metrics are the problem as I can't access the file until it's written to disk, and
its not written to disk until 'process'ing finishes
Background
A log4j implementation is being used for service logging, but after some tinkering we realised it really doesn't suit the requirement here as it would output multi-line json and embed the json into a single top-level field. We need varying top level fields, depending on the file processed.
The server is expected to deal with multiple file operations asynchronously, and the files vary in size (from tiny to fairly immense - which is one reason we need to iterate stats and measures before we start to tune or review)
Current State
input file and even processing time stats are working OK, and I'm using the following technique to get them:
Inside the 'process' override method of "MyProcessor" I create a new instance of my JsonLogWriter class. (shortened pseudo code with ellipsis)
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
...
@Component
public class MyProcessor implements Processor {
...
@Override
public void process(Exchange exchange) throws Exception {
...
JsonLogWriter jlw = new JsonLogWriter();
jlw.logfilePath = jsonLogFilePath;
jlw.inputFilePath = inFilePath;
jlw.outputfilePath = outFilePath;
...
jlw.metricsInputFile(); //gathers metrics using inputFilePath - OK
...
(input file is processed / changed and returned as an inputstream:
InputStream result = myEngine.readAndUpdate(inFilePath);
... get timings
jlw.write
}
From this you can see that JsonLogWriter has
properties for file paths (input file, output file, log output),
a set of methods to populate data:
a method to emit the data to a file (once ready)
Once I have populated all the json objects in the class, I call the write() method and the class pulls all the json objects together and
the stats all arrive in a log file (in a single line of json) - OK.
Error - no output file (yet)
If I use the metricsOutputFile method however:
InputStream result = myEngine.readAndUpdate(inFilePath);
... get timings
jlw.metricsOutputFile(); // using outputfilePath
jlw.write
}
... the JsonLogWriter fails as the file doesn't exist yet.
java.nio.file.NoSuchFileException: aroute\output\a_long_guid_filename
when debugging I can't see any part of the exchange or result objects which I might pipe into a file read/statistics gathering process.
Will this require more camel routes to solve? What might be an alternative approach where I can get all the stats from input and output files and keep them in one object / line of json?
(very happy to receive constructive criticism - as in why is your Java so heavy-handed - and yes it may well be, I am prototyping solutions at this stage, so this isn't production code, nor do I profess deep understanding of Java internals - I can usually get stuff working though)
A:
Use one route and two processors: one for writing the file and the next for reading the file, so one finishes writing before the other starts reading
Or , also you can use two routes: one for writing the file (to:file) and other that listens to read the file(from:file)
You can check for common EIP patterns that will solve most of this questions here:
https://www.enterpriseintegrationpatterns.com/patterns/messaging/
|
[
"stackoverflow",
"0059589793.txt"
] | Q:
Assigning default value to variable in destructing nested array
I am wondering how to assign default values when destructing a nested array.
I have myArr array which has a nested array [12, 25, 1, 6]
let myArr = [11, 100, 33, [12, 25, 1, 6], 77]
I want to assign a default value to four when destructing myArr as below
const[ one = 999, two = 999, three = 999, four = [ ], five = 999] = myArr
And I also want to destructure elements of the nested array.
const[ one = 999, two = 999, three = 999, [innerOne = 1, ...rest ], five = 999] = myArr
Is it possible to assign a default value to variable four and destructure the elements of the nested array [12, 25, 1, 6] concurrently in one line?
A:
You can do this by destructuring the array as an object. When destructuring an object, you can assign aliases, and destructure a property more than once (index 3 in this case).
const myArr = [11, 100, 33, [12, 25, 1, 6], 77]
const {
0: one = 999,
1: two = 999,
2: three = 999,
3: four = [],
3: [innerOne = 1, ...rest ],
4: five = 999
} = myArr
console.log(one, two, three, four, innerOne, rest, five)
|
[
"stackoverflow",
"0007086267.txt"
] | Q:
Optimal strategy to make a C++ hash table, thread safe
(I am interested in design of implementation NOT a readymade construct that will do it all.)
Suppose we have a class HashTable (not hash-map implemented as a tree but hash-table)
and say there are eight threads.
Suppose read to write ratio is about 100:1 or even better 1000:1.
Case A) Only one thread is a writer and others including writer can read from HashTable(they may simply iterate over entire hash table)
Case B) All threads are identical and all could read/write.
Can someone suggest best strategy to make the class thread safe with following consideration
1. Top priority to least lock contention
2. Second priority to least number of locks
My understanding so far is thus :
One BIG reader-writer lock(semaphore).
Specialize the semaphore so that there could be eight instances writer-resource for case B, where each each writer resource locks one row(or range for that matter).
(so i guess 1+8 mutexes)
Please let me know if I am thinking on the correct line, and how could we improve on this solution.
A:
With such high read/write ratios, you should consider a lock free solution, e.g. nbds.
EDIT:
In general, lock free algorithms work as follows:
arrange your data structures such that for each function you intend to support there is a point at which you are able to, in one atomic operation, determine whether its results are valid (i.e. other threads have not mutated its inputs since they have been read) and commit to them; with no changes to state visible to other threads unless you commit. This will involve leveraging platform-specific functions such as Win32's atomic compare-and-swap or Cell's cache line reservation opcodes.
each supported function becomes a loop that repeatedly reads the inputs and attempts to perform the work, until the commit succeeds.
In cases of very low contention, this is a performance win over locking algorithms since functions mostly succeed the first time through without incurring the overhead of acquiring a lock. As contention increases, the gains become more dubious.
Typically the amount of data it is possible to atomically manipulate is small - 32 or 64 bits is common - so for functions involving many reads and writes, the resulting algorithms become complex and potentially very difficult to reason about. For this reason, it is preferable to look for and adopt a mature, well-tested and well-understood third party lock free solution for your problem in preference to rolling your own.
Hashtable implementation details will depend on various aspects of the hash and table design. Do we expect to be able to grow the table? If so, we need a way to copy bulk data from the old table into the new safely. Do we expect hash collisions? If so, we need some way of walking colliding data. How do we make sure another thread doesn't delete a key/value pair between a lookup returning it and the caller making use of it? Some form of reference counting, perhaps? - but who owns the reference? - or simply copying the value on lookup? - but what if values are large?
Lock-free stacks are well understood and relatively straightforward to implement (to remove an item from the stack, get the current top, attempt to replace it with its next pointer until you succeed, return it; to add an item, get the current top and set it as the item's next pointer, until you succeed in writing a pointer to the item as the new top; on architectures with reserve/conditional write semantics, this is enough, on architectures only supporting CAS you need to append a nonce or version number to the atomically manipulated data to avoid the ABA problem). They are one way of keeping track of free space for keys/data in an atomic lock free manner, allowing you to reduce a key/value pair - the data actually stored in a hashtable entry - to a pointer/offset or two, a small enough amount to be manipulated using your architecture's atomic instructions. There are others.
Reads then become a case of looking up the entry, checking the kvp against the requested key, doing whatever it takes to make sure the value will remain valid when we return it (taking a copy / increasing its reference count), checking the entry hasn't been modified since we began the read, returning the value if so, undoing any reference count changes and repeating the read if not.
Writes will depend on what we're doing about collisions; in the trivial case, they are simply a case of finding the correct empty slot and writing the new kvp.
The above is greatly simplified and insufficient to produce your own safe implementation, especially if you are not familiar with lock-free/wait-free techniques. Possible complications include the ABA problem, priority inversion, starvation of particular threads; I have not addressed hash collisions.
The nbds page links to an excellent presentation on a real world approach that allows growth / collisions. Others exist, a quick Google finds lots of papers.
Lock free and wait free algorithms are fascinating areas of research; I encourage the reader to Google around. That said, naive lock free implementations can easily look reasonable and behave correctly much of the time while in reality being subtly unsafe. While it is important to have a solid grasp on the principles, I strongly recommend using an existing, well-understood and proven implementation over rolling your own.
|
[
"stackoverflow",
"0014686701.txt"
] | Q:
Playing youtube video fullscreen in UIWebView on iOS 6
I have a problem playing youtube videos in fullscreen mode within UIWebView. By default video is inlined. When I switch to fullscreen (native player button), video player is resized to fullscreen and after that is quits playing and page gets refreshed.
This works just fine is iOS5 but not iOS6.
This is more obvious on iPhone cos player goes fullscreen mode as soon as video starts playing. As a results this videos can not be played on iPhone device using iOS6.x.
I know that Apple change its policy about youtube videos. But how does this helps me? How can I assure videos are also playing in fullscreen mode?
A:
-(void)viewWillDisappear is now (iOS6) called if you play a video in fullscreen mode
try registering for UIMoviePlayerControllerDidEnter*(/Exit)*FullscreenNotification
and modifying viewWillDisappear like UIWebView Movie Player getting dismissed iOS 6 bug
|
[
"stackoverflow",
"0017921313.txt"
] | Q:
Reference query results with outerjoin in Flask/SQLAlchemy/jinja
I have the following query:
last_entry = Table.query \
.group_by(Table.email) \
.order_by(Table.date) \
.subquery()
results = db.session.query(User, last_entry.c.id) \
.outerjoin(last_entry, User.email == last_entry.c.email)
This gets the the needed data, however I am unable to access this "last_entry" row data. How to get that to show in the template?
I am rendering it with this line:
return render_template('users.html', users=results.all())
I have tried some solutions with user['last_entry'] and similar things, but without success. I can access the data from the User table, by just using fields from User table, like user['first_name'], but can't do the same for the joined table.
A:
In the session.query() you should specify a list of entities that you want to see in the results:
results = db.session.query(User, last_entry).outerjoin(last_entry, User.email == last_entry.c.email)
Or, you can make use of add_entity():
results = session.query(User).outerjoin(last_entry, User.email == last_entry.c.email).add_entity(last_entry)
Hope that helps.
|
[
"stackoverflow",
"0021299439.txt"
] | Q:
Clipping images into different shapes like triangle, pentagon in html5 canvas?
I am developing a game in html 5 canvas where I have to clip images into many shapes. I also want to join these clipped images using mouse events. Can I only clip a square shape? Also, is it necessary to save x and y co-ordinates of each clipped image to know its position or is there any alternate way?
A:
Here is an example to illustrate how to:
clip an image into 4 triangle pieces,
hit-test the pieces,
move the pieces using your mouse
Here's code and a Fiddle: http://jsfiddle.net/m1erickson/r59ch/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
#canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var $canvas=$("#canvas");
var canvasOffset=$canvas.offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var scrollX=$canvas.scrollLeft();
var scrollY=$canvas.scrollTop();
var isDown=false;
var startX;
var startY;
var parts=[];
var selectedPart=-1;
var img=new Image();
img.onload=function(){
var cx=img.width/2;
var cy=img.height/2;
var w=img.width;
var h=img.height;
parts.push({x:25,y:25,points:[{x:0,y:0},{x:cx,y:cy},{x:0,y:h}]});
parts.push({x:25,y:25,points:[{x:0,y:0},{x:cx,y:cy},{x:w,y:0}]});
parts.push({x:125,y:25,points:[{x:w,y:0},{x:cx,y:cy},{x:w,y:h}]});
parts.push({x:25,y:25,points:[{x:0,y:h},{x:cx,y:cy},{x:w,y:h}]});
drawAll();
}
img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house100x100.png";
function drawAll(){
ctx.clearRect(0,0,canvas.width,canvas.height);
for(var i=0;i<parts.length;i++){
draw(parts[i]);
}
}
function draw(part){
ctx.save();
define(part);
ctx.clip();
ctx.drawImage(img,part.x,part.y);
ctx.stroke();
ctx.restore();
}
function hit(part,x,y){
define(part);
return(ctx.isPointInPath(x,y))
}
function move(part,x,y){
part.x+=x;
part.y+=y;
draw(part);
}
function define(part){
ctx.save();
ctx.translate(part.x,part.y);
ctx.beginPath();
var point=part.points[0];
ctx.moveTo(point.x,point.y);
for(var i=0;i<part.points.length;i++){
var point=part.points[i];
ctx.lineTo(point.x,point.y);
}
ctx.closePath();
ctx.restore();
}
function handleMouseDown(e){
e.preventDefault();
startX=parseInt(e.clientX-offsetX);
startY=parseInt(e.clientY-offsetY);
// Put your mousedown stuff here
for(var i=0;i<parts.length;i++){
if(hit(parts[i],startX,startY)){
isDown=true;
selectedPart=i;
return;
}
}
selectedPart=-1;
}
function handleMouseUp(e){
e.preventDefault();
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// Put your mouseup stuff here
isDown=false;
}
function handleMouseOut(e){
e.preventDefault();
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// Put your mouseOut stuff here
isDown=false;
}
function handleMouseMove(e){
if(!isDown){return;}
e.preventDefault();
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// Put your mousemove stuff here
var dx=mouseX-startX;
var dy=mouseY-startY;
startX=mouseX;
startY=mouseY;
//
var part=parts[selectedPart];
move(part,dx,dy);
drawAll();
}
$("#canvas").mousedown(function(e){handleMouseDown(e);});
$("#canvas").mousemove(function(e){handleMouseMove(e);});
$("#canvas").mouseup(function(e){handleMouseUp(e);});
$("#canvas").mouseout(function(e){handleMouseOut(e);});
}); // end $(function(){});
</script>
</head>
<body>
<h4>Drag the right triangle-image into place</h4>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>
|
[
"stackoverflow",
"0009317174.txt"
] | Q:
What are the causes of a "operation performed with inactive user" error when *creating* a Salesforce object?
Using C# and the Salesforce API, I can successfully update records, and I can create in certain tables. However, when I attempt to add an Account object, the create method reports failure, with the error INACTIVE_OWNER_OR_USER, message "operation performed with inactive user". What might this error indicate?
The only user that I see involved is the account I'm using to authenticate, which is certainly active, at least I can log in with it and update records. It appears to have full rights.
My understanding is that one should not explicitly specify the owner for an object, as Salesforce will set that automatically, so I'm leaving the Owner and OwnerId fields null in the passed object. I get the same error if I do explicitly set OwnerId, anyway.
I've gone over the docs (create, accounts), but they offer little troubleshooting advice. Google offers very little on this error message in relation to inserts, though it's clearly an issue for updates. Can anyone tell me what I'm missing?
I'm using our corporate Enterprise WSDL, API v24.0. I could share code, but I'm not sure it would help, as it's virtually identical to working update code, it's just a different method called in the end.
A:
Check in the Account setup, you might have automatic account assignment rules which end up assigning the account to a now inactive user.
If its not that, another place to look at are before insert and before update triggers on Account object. check if there are any and if any of them reassign ownership.
|
[
"pt.stackoverflow",
"0000059154.txt"
] | Q:
Declarar as variáveis no topo ou perto de onde são usadas?
É melhor declarar todas as variáveis logo no início do arquivo, mesmo que só venham a ser utilizadas, sei lá, mil linhas depois? Ou é melhor ir declarando conforme o programa evolui?
O meu caso é que vou unir vários scripts em apenas um (estou criando cada função separadamente porque estava ficando muito grande e confuso), e quero em dúvida se devo apenas copiar e colar esses arquivos, com as variáveis onde estão (o que está funcionando), ou se é pego todas as variáveis e jogo no início deste arquivo grande, e depois vou colocando apenas as funções.
Quais são as vantagens e desvantagens de cada uma dessas opções? Isso faz diferença no desempenho? Existe um caminho considerado mais correto?
Tipo, é melhor isso:
// variáveis e função 1
$reds = $_POST ["Tredsalim"];
$redvalan = $_POST ["Treds4"];
$redvalan2 = $_POST ["Treds9"];
if ($reds == "sim") {
$remmes += $redvalan + $redvalan2;
}
// variáveis e função 2
$difsal = $_POST ["Tdifsalim"];
$saldev = $_POST ["Tdate5"];
$saldev2 = $_POST ["Tdate9"];
$saldev3 = $_POST ["Tdate13"];
if ($saldev > 1) {
$remmes = $saldev;
}
if ($saldev2 > 1) {
$remmes = $saldev2;
}
if ($saldev3 > 1) {
$remmes = $saldev3;
Ou isso:
// variáveis caso 1
$reds = $_POST ["Tredsalim"];
$redvalan = $_POST ["Treds4"];
$redvalan2 = $_POST ["Treds9"];
// variáveis caso 2
$difsal = $_POST ["Tdifsalim"];
$saldev = $_POST ["Tdate5"];
$saldev2 = $_POST ["Tdate9"];
$saldev3 = $_POST ["Tdate13"];
// função 1
if ($reds == "sim") {
$remmes += $redvalan + $redvalan2;
}
// função 2
if ($saldev > 1) {
$remmes = $saldev;
}
if ($saldev2 > 1) {
$remmes = $saldev2;
}
if ($saldev3 > 1) {
$remmes = $saldev3;
A:
Provavelmente o melhor é garantir que todas as variáveis devem ser declaradas no começo. Isto vai contra o que se costuma recomendar. Mas juntar vários códigos também não é recomendado. Então já que vai fazer algo não recomendado que pelo menos tente minimizar o dano e ele será minimizado se tiver que analisar todo o código para descobrir todas as variáveis para declarar no início. Quem sabe descobre que alguns bugs seriam causados por sobreposição de variáveis ou outro conflitos.
Neste exemplo específico fica ainda mais óbvio que deveria fazer isto porque no fundo as variáveis são bem relacionadas, no fundo um grupo é continuação do outro.
Isto deve ser feito só por uma questão de organização, não influencia a performance.
Claro que em outra situação a mudança pode mudar a lógica do código.
Se estiver criando várias funções no mesmo arquivo, aí fica mais simples porque as variáveis viram locais, e tem que ser tudo perto mesmo, não dá para agrupar as variáveis sem criar novos possíveis problemas.
|
[
"stackoverflow",
"0007215818.txt"
] | Q:
Why does redefining a static global variable give a compile-time error when redefining a global variable does not?
Compiling code 1 gives an error 'i redefined', but code 2 shows no similar error. Why is it so?
Code 1
static int i; //Declaring the variable i.
static int i=25; //Initializing the variable.
static int i; //Again declaring the variable i.
int main(){
return 0;
}
Code 2
int i; //Declaring the variable i.
int i=25; //Initializing the variable.
int i; //Again declaring the variable i.
int main(){
return 0;
}
A:
Both should compile.
Both int i; and static int i; are tentative definitions in C as they do not have an initializer and are not extern. You are allowed multiple tentative declarations and at most one non-tentative definition for any object in a translation unit so long as the definitions don't conflict in type or linkage.
ISO/IEC 9899:1999 6.9.2:
A declaration of an identifier for an object that has file scope without an initializer, and without a storage-class specifier or with a storage-class specifier static, constitutes a tentative definition. If a translation unit contains one or more tentative definitions for an identifier, and the translation unit contains no external definitions for that identifier, then the behavior is exactly as if the translation unit contains a file scope declaration of that identifier, with the composite type as of the end of the translation unit, with an initializer equal to 0.
|
[
"tex.stackexchange",
"0000139367.txt"
] | Q:
How should I add a file in my LaTeX document?
I am creating my BE project report using LaTeX and in that I have to add my sponsorship letter. Is there any solution to do this?
A:
If your sponsorship letter is a pdf, then you can use the following package:
\usepackage{pdfpages}
And then use the following where you want to insert the letter:
\includepdf[pages={1}]{letter.pdf}
A:
In menu bar select LaTex menu, in that select \include{file} and then browse to find the file you want to include (and file should be Tex file).
(If file to be include is a pdf file) and james Shaeffer is right if u want to add pdf file.
first include package
\usepackage{pdfpages}
and then to include file
\includepdf[pages={1}]{letter.pdf}`
|
[
"stackoverflow",
"0012871766.txt"
] | Q:
HTML5 placing image where i want it on screen
I have a little start screen running and i want the image, which is acting as a button, to placed at a certain point, but when i try to it stays in the same place, and i don't know how i can get it to stay in the place i want it. Here is my code, its is HTML with some css:
<style>
#SplashScreen{
position:relative;
overflow:hidden;
}
#StartButton
{
cursor:pointer;
position:absoloute;
left:100px;
top:100px;
}
</style>
<div id="SplashScreen" width="400" height="400">
<h1>Game Title</h1>
<img id="StartButton" src="play.png"/>
</div>
The image just draws underneath the title and not where i want it. Any help?
A:
It is because your absolute spelling is wrong
#StartButton
{
cursor:pointer;
position:absolute;
left:100px;
top:100px;
}
And don't use height/width attributes, specify them in your #SplashScreen instead My Fiddle
<style>
#SplashScreen{
position:relative;
overflow:hidden;
height: 400px;
width: 400px;
}
#StartButton
{
cursor:pointer;
position:absolute;
left:100px;
top:100px;
}
</style>
<div id="SplashScreen">
<h1>Game Title</h1>
<img id="StartButton" src="http://www.alfresco.com/community/images/windows-icon.png"/>
</div>
|
[
"stackoverflow",
"0000945288.txt"
] | Q:
Saving current directory to bash history
I'd like to save the current directory where the each command was issued alongside the command in the history. In order not to mess things up, I was thinking about adding the current directory as a comment at the end of the line. An example might help:
$ cd /usr/local/wherever
$ grep timmy accounts.txt
I'd like bash to save the last command as:
grep timmy accounts.txt # /usr/local/wherever
The idea is that this way I could immediately see where I issued the command.
A:
One-liner version
Here is a one-liner version. It's the original. I've also posted a short function version and a long function version with several added features. I like the function versions because they won't clobber other variables in your environment and they're much more readable than the one-liner. This post has some information on how they all work which may not be duplicated in the others.
Add the following to your ~/.bashrc file:
export PROMPT_COMMAND='hpwd=$(history 1); hpwd="${hpwd# *[0-9]* }"; if [[ ${hpwd%% *} == "cd" ]]; then cwd=$OLDPWD; else cwd=$PWD; fi; hpwd="${hpwd% ### *} ### $cwd"; history -s "$hpwd"'
This makes a history entry that looks like:
rm subdir/file ### /some/dir
I use ### as a comment delimiter to set it apart from comments that the user might type and to reduce the chance of collisions when stripping old path comments that would otherwise accumulate if you press enter on a blank command line. Unfortunately, the side affect is that a command like echo " ### " gets mangled, although that should be fairly rare.
Some people will find the fact that I reuse the same variable name to be unpleasant. Ordinarily I wouldn't, but here I'm trying to minimize the footprint. It's easily changed in any case.
It blindly assumes that you aren't using HISTTIMEFORMAT or modifying the history in some other way. It would be easy to add a date command to the comment in lieu of the HISTTIMEFORMAT feature. However, if you need to use it for some reason, it still works in a subshell since it gets unset automatically:
$ htf="%Y-%m-%d %R " # save it for re-use
$ (HISTTIMEFORMAT=$htf; history 20)|grep 11:25
There are a couple of very small problems with it. One is if you use the history command like this, for example:
$ history 3
echo "hello world" ### /home/dennis
ls -l /tmp/file ### /home/dennis
history 3
The result will not show the comment on the history command itself, even though you'll see it if you press up-arrow or issue another history command.
The other is that commands with embedded newlines leave an uncommented copy in the history in addition to the commented copy.
There may be other problems that show up. Let me know if you find any.
How it works
Bash executes a command contained in the PROMPT_COMMAND variable each time the PS1 primary prompt is issued. This little script takes advantage of that to grab the last command in the history, add a comment to it and save it back.
Here it is split apart with comments:
hpwd=$(history 1) # grab the most recent command
hpwd="${hpwd# *[0-9]* }" # strip off the history line number
if [[ ${hpwd%% *} == "cd" ]] # if it's a cd command, we want the old directory
then # so the comment matches other commands "where *were* you when this was done?"
cwd=$OLDPWD
else
cwd=$PWD
fi
hpwd="${hpwd% ### *} ### $cwd" # strip off the old ### comment if there was one so they
# don't accumulate, then build the comment
history -s "$hpwd" # replace the most recent command with itself plus the comment
A:
hcmnt - long function version
Here is a long version in the form of a function. It's a monster, but it adds several useful features. I've also posted a one-liner (the original) and a shorter function. I like the function versions because they won't clobber other variables in your environment and
they're much more readable than the one-liner. Read the entry for the one-liner and the commments in the function below for additional information on how it works and some limitations. I've posted each version in its own answer in order to keep things more organized.
To use this one, save it in a file called hcmnt in a location like /usr/local/bin (you can chmod +x it if you want) then source it in your ~/.bashrc like this:
source /usr/local/bin/hcmnt
export hcmntextra='date "+%Y%m%d %R"'
export PROMPT_COMMAND='hcmnt'
Don't edit the function's file where PROMPT_COMMAND or hcmntextra are set. Leave them as is so they remain as defaults. Include them in your .bashrc as shown above and edit them there to set options for hcmnt or to change or unset hcmntextra. Unlike the short function, with this one you must both have the hcmntextra variable set and use the -e option to make that feature work.
You can add several options which are documented (with a couple of examples) in the comments in the function. One notable feature is to have the history entry with appended comment logged to a file and leave the actual history untouched. In order to use this function, just
add the -l filename option like so:
export PROMPT_COMMAND="hcmnt -l ~/histlog"
You can use any combination of options, except that -n and -t are mutually exclusive.
#!/bin/bash
hcmnt() {
# adds comments to bash history entries (or logs them)
# by Dennis Williamson - 2009-06-05 - updated 2009-06-19
# http://stackoverflow.com/questions/945288/saving-current-directory-to-bash-history
# (thanks to Lajos Nagy for the idea)
# the comments can include the directory
# that was current when the command was issued
# plus optionally, the date or other information
# set the bash variable PROMPT_COMMAND to the name
# of this function and include these options:
# -e - add the output of an extra command contained in the hcmntextra variable
# -i - add ip address of terminal that you are logged in *from*
# if you're using screen, the screen number is shown
# if you're directly logged in, the tty number or X display number is shown
# -l - log the entry rather than replacing it in the history
# -n - don't add the directory
# -t - add the from and to directories for cd commands
# -y - add the terminal device (tty)
# text or a variable
# Example result for PROMPT_COMMAND='hcmnt -et $LOGNAME'
# when hcmntextra='date "+%Y%m%d %R"'
# cd /usr/bin ### mike 20090605 14:34 /home/mike -> /usr/bin
# Example for PROMPT_COMMAND='hcmnt'
# cd /usr/bin ### /home/mike
# Example for detailed logging:
# when hcmntextra='date "+%Y%m%d %R"'
# and PROMPT_COMMAND='hcmnt -eityl ~/.hcmnt.log $LOGNAME@$HOSTNAME'
# $ tail -1 ~/.hcmnt.log
# cd /var/log ### dave@hammerhead /dev/pts/3 192.168.1.1 20090617 16:12 /etc -> /var/log
# INSTALLATION: source this file in your .bashrc
# will not work if HISTTIMEFORMAT is used - use hcmntextra instead
export HISTTIMEFORMAT=
# HISTTIMEFORMAT still works in a subshell, however, since it gets unset automatically:
# $ htf="%Y-%m-%d %R " # save it for re-use
# $ (HISTTIMEFORMAT=$htf; history 20)|grep 11:25
local script=$FUNCNAME
local hcmnt=
local cwd=
local extra=
local text=
local logfile=
local options=":eil:nty"
local option=
OPTIND=1
local usage="Usage: $script [-e] [-i] [-l logfile] [-n|-t] [-y] [text]"
local newline=$'\n' # used in workaround for bash history newline bug
local histline= # used in workaround for bash history newline bug
local ExtraOpt=
local LogOpt=
local NoneOpt=
local ToOpt=
local tty=
local ip=
# *** process options to set flags ***
while getopts $options option
do
case $option in
e ) ExtraOpt=1;; # include hcmntextra
i ) ip="$(who --ips -m)" # include the terminal's ip address
ip=($ip)
ip="${ip[4]}"
if [[ -z $ip ]]
then
ip=$(tty)
fi;;
l ) LogOpt=1 # log the entry
logfile=$OPTARG;;
n ) if [[ $ToOpt ]]
then
echo "$script: can't include both -n and -t."
echo $usage
return 1
else
NoneOpt=1 # don't include path
fi;;
t ) if [[ $NoneOpt ]]
then
echo "$script: can't include both -n and -t."
echo $usage
return 1
else
ToOpt=1 # cd shows "from -> to"
fi;;
y ) tty=$(tty);;
: ) echo "$script: missing filename: -$OPTARG."
echo $usage
return 1;;
* ) echo "$script: invalid option: -$OPTARG."
echo $usage
return 1;;
esac
done
text=($@) # arguments after the options are saved to add to the comment
text="${text[*]:$OPTIND - 1:${#text[*]}}"
# *** process the history entry ***
hcmnt=$(history 1) # grab the most recent command
# save history line number for workaround for bash history newline bug
histline="${hcmnt% *}"
hcmnt="${hcmnt# *[0-9]* }" # strip off the history line number
if [[ -z $NoneOpt ]] # are we adding the directory?
then
if [[ ${hcmnt%% *} == "cd" ]] # if it's a cd command, we want the old directory
then # so the comment matches other commands "where *were* you when this was done?"
if [[ $ToOpt ]]
then
cwd="$OLDPWD -> $PWD" # show "from -> to" for cd
else
cwd=$OLDPWD # just show "from"
fi
else
cwd=$PWD # it's not a cd, so just show where we are
fi
fi
if [[ $ExtraOpt && $hcmntextra ]] # do we want a little something extra?
then
extra=$(eval "$hcmntextra")
fi
# strip off the old ### comment if there was one so they don't accumulate
# then build the string (if text or extra aren't empty, add them plus a space)
hcmnt="${hcmnt% ### *} ### ${text:+$text }${tty:+$tty }${ip:+$ip }${extra:+$extra }$cwd"
if [[ $LogOpt ]]
then
# save the entry in a logfile
echo "$hcmnt" >> $logfile || echo "$script: file error." ; return 1
else
# workaround for bash history newline bug
if [[ $hcmnt != ${hcmnt/$newline/} ]] # if there a newline in the command
then
history -d $histline # then delete the current command so it's not duplicated
fi
# replace the history entry
history -s "$hcmnt"
fi
} # END FUNCTION hcmnt
# set a default (must use -e option to include it)
export hcmntextra='date "+%Y%m%d %R"' # you must be really careful to get the quoting right
# start using it
export PROMPT_COMMAND='hcmnt'
update 2009-06-19: Added options useful for logging (ip and tty), a workaround for the duplicate entry problem, removed extraneous null assignments
A:
You could install Advanced Shell History, an open source tool that writes your bash or zsh history to a sqlite database. This records things like the current working directory, the command exit code, command start and stop times, session start and stop times, tty, etc.
If you want to query the history database, you can write your own SQL queries, save them and make them available within the bundled ash_query tool. There are a few useful prepackaged queries, but since I know SQL pretty well, I usually just open the database and query interactively when I need to look for something.
One query I find very useful, though, is looking at the history of the current working directory. It helps me remember where I left off when I was working on something.
vagrant@precise32:~$ ash_query -q CWD
session
when what
1
2014-08-27 17:13:07 ls -la
2014-08-27 17:13:09 cd .ash
2014-08-27 17:16:27 ls
2014-08-27 17:16:33 rm -rf advanced-shell-history/
2014-08-27 17:16:35 ls
2014-08-27 17:16:37 less postinstall.sh
2014-08-27 17:16:57 sudo reboot -n
And the same history using the current working directory (and anything below it):
vagrant@precise32:~$ ash_query -q RCWD
session
where
when what
1
/home/vagrant/advanced-shell-history
2014-08-27 17:11:34 nano ~/.bashrc
2014-08-27 17:12:54 source /usr/lib/advanced_shell_history/bash
2014-08-27 17:12:57 source /usr/lib/advanced_shell_history/bash
2014-08-27 17:13:05 cd
/home/vagrant
2014-08-27 17:13:07 ls -la
2014-08-27 17:13:09 cd .ash
/home/vagrant/.ash
2014-08-27 17:13:10 ls
2014-08-27 17:13:11 ls -l
2014-08-27 17:13:16 sqlite3 history.db
2014-08-27 17:13:43 ash_query
2014-08-27 17:13:50 ash_query -Q
2014-08-27 17:13:56 ash_query -q DEMO
2014-08-27 17:14:39 ash_query -q ME
2014-08-27 17:16:26 cd
/home/vagrant
2014-08-27 17:16:27 ls
2014-08-27 17:16:33 rm -rf advanced-shell-history/
2014-08-27 17:16:35 ls
2014-08-27 17:16:37 less postinstall.sh
2014-08-27 17:16:57 sudo reboot -n
FWIW - I'm the author and maintainer of the project.
|
[
"stackoverflow",
"0050048195.txt"
] | Q:
Mixing Composition and Inheritance in Java
Is it possible to mix composition and inheritance in Java? Fist I have some generic classes is a HAS-A (or HAS-MANY) relationship (Composition).
Generic classes:
Structure, TypeA, TypeB, TypeC, etc., where Structure is in a HAS-A relationship with TypeA, TypeB and TypeC.
But then I also have several sets of subclasses which inherit from the generic classes (Inheritance) and are in the same relationship.
Sets of subclasses:
Set 1:
Structure1, TypeA1, TypeB1, TypeC1, etc., where Structure1 is in the same HAS-A relationship with TypeA1, TypeB1 and TypeC1, just like the generic classes.
And: Structure1 extends Structure, TypeA1 extends TypeA, ..., TypeC1 extends TypeC, etc.
... until Set X:
StructureX, TypeAX, TypeBX, TypeCX, etc.
Each special structure has exactly ONE specific sub-TypeA, sub-TypeB and sub-TypeC, etc. The generic classes define some code (attributes and methods) which I would like ot reuse when dealing with special structures. The problems I am facing are best explained by the code below. (I do not know if this can somehow be solved by Java "generics" but I think not.)
/***********************************************************************************************
/ Generic Structure of Structure-Class with Instances of Generic other classes (Composition)
/***********************************************************************************************/
class Structure {
// Substructures
TypeA instanceA;
TypeB instanceB;
// Defining many methods using the instances of other generic classes like TypeA
void setGenericAttributeOfA(int value) {
instanceA.genericAttribute = value;
}
void setGenericAttributeOfB(int value) {
instanceB.genericAttribute = value;
}
}
class TypeA {
int genericAttribute;
}
class TypeB {
int genericAttribute;
}
/***********************************************************************************************
/ Specific implementation of a Structure-Class with specific implementation of the other classes (Inheritance)
/***********************************************************************************************/
// In the specific implementations I want to use the generic methods, because I do not want to
// rewrite the code for each and every specific implementation. But they should
class Structure1 extends Structure {
// This will create an additional attribute instanceA of specific TypeA1, so I will end up with two instances:
// (1) TypeA super.instanceA and (2) TypeA1 this.instanceA. But what I would like is to have only
// one instanceA of type TypeA1 that can also be used by the global methods of the generic Structure.
TypeA1 instanceA;
Structure1() {
// This creates an instance of type TypeA1, but it cannot be used in the generic methods
// because it is hold in a separate "local" variable that is not known to the generic Structure methods
instanceA = new TypeA1();
// This creates an instance of type TypeB1, but it cannot access the "local" specific attributes,
// because it is hold in a varable which is statically types as TypeB
instanceB = new TypeB1();
}
void specificMethod() {
setGenericAttributeOfA(42); // would fail, because instanceA of type generic TypeA is null
instanceA.specificAttribute = 13; // works only for "local" specific attributes
setGenericAttributeOfB(42); // works only for generic attributes
instanceB.specificAttribute = 13; // would fail, because instanceB is statically typed as generic TypeB which does not have this attribute
((TypeB1)instanceB).specificAttribute = 13; // works but is an ugly work-around and over-complicated if to be used many times
}
}
class TypeA1 extends TypeA {
int specificAttribute;
}
class TypeB1 extends TypeB {
int specificAttribute;
}
A:
Maybe Generics can help?
Declare Structure as generic:
class Structure<T1 extends TypeA, T2 extends TypeB, T3 extends TypeC> {
T1 instanceA;
T2 instanceB;
T3 instanceC;
}
And your specific structures will just inherit from the generic Structure by specifying type arguments:
class Structure1 extends Structure<TypeA1, TypeB1, TypeC1> {
// here instanceA will be of type TypeA1, instanceB will be TypeB1 etc.
}
|
[
"serverfault",
"0000252942.txt"
] | Q:
How do install Apache mods in Tomcat?
I have a web app which can run inside a servlet container (I use Tomcat). Now I want to use load balancing because I have 2 of these servers. But, if I want to use mod_proxy_balancer, do I need to be running an Apache Server instance too? Can you load mods in Tomcat or do you have to set an Apache Server (with mod_proxy, mod_proxy_balancer) + Apache Tomcat Connector + Tomcat to use the load balancing mod?
Thank you
A:
Yes, you'll need to run an instance of Apache; Apache modules run only in Apache. But you want that, anyway - mod_proxy_balancer is only gonna help you if it gets to distribute requests before they hit Tomcat!
|
[
"stackoverflow",
"0007519375.txt"
] | Q:
How to automatically overwrite the output file when running `gpg` (i.e. without being prompted)?
If I have the same filename in the target directory, decryption fails.
The command I'm using to decrypt:
gpg --passphrase-fd 0 -o D:/Notification/mytest.txt --batch \
--passphrase-file D:/passphrase.txt -d D:/Notification/mytest.gpg
It doesn't overwrite the mytest.txt file so each time I need to delete the file before I execute the script.
Is there any option to overwrite the output fie?
A:
Adding --batch --yes
Example:
gpg --batch --yes -u [email protected] -r "[email protected]" \
--output "OUTPUTFILENAME.xls.pgp" -a -s -e "FILE.xls"
Complete example with passphrase file:
gpg --batch --yes --passphrase-fd 0 -u [email protected] -r "[email protected]" \
--output "OUTPUTFILENAME.xls.pgp" -a -s -e "FILE.xls"< \
passphrase.txt
A:
Just add the --yes option to you command line. The --yes option assumes yes for most questions which gpg will prompt for.
Source: http://www.gnupg.org/gph/de/manual/r1023.html
|
[
"biology.stackexchange",
"0000007967.txt"
] | Q:
What factors govern the variable age of onset in Huntington's Disease?
"Huntington's disease (HD) is a neurodegenerative genetic disorder that affects muscle coordination and leads to cognitive decline and psychiatric problems." As we all know, this genetic disease exhibits a generally late age of onset. It has been shown that a increase in the number of CAG repeats in the hungtingtin gene is negatively correlated to the age of onset of the disease. However, patients having a particular number of CAG repeats still have an extremely variable age of onset, which leads to believe that other factors are contributing to the Huntington phenotype.(reference)
(reference)
What other genetic or environmental factors have been shown to vary the age of onset of Huntington's disease?
References
Andrew, S. E. et al. The relationship between trinucleotide (CAG) repeat length and clinical features of Huntington’s disease. Nature Genetics 4, 398–403 (1993).
A:
There is quite a bit of data available from Venezuelan HD families, but they haven't identified the factors themselves. From the abstract of the paper, emphasis mine:
Analysis of the 83 kindreds that comprise the Venezuelan HD kindreds
demonstrates that residual variability in age of onset has both
genetic and environmental components. We created a residual age of
onset phenotype from a regression analysis of the log of age of onset
on repeat length. Familial correlations (correlation +/- SE) were
estimated for sibling (0.40 +/- 0.09), parent-offspring (0.10 +/-
0.11), avuncular (0.07 +/- 0.11), and cousin (0.15 +/- 0.10) pairs, suggesting a familial origin for the residual variance in onset*. By
using a variance-components approach with all available familial
relationships, the additive genetic heritability of this residual age
of onset trait is 38%. A model, including shared sibling environmental
effects, estimated the components of additive genetic (0.37), shared
environment (0.22), and nonshared environment (0.41) variances,
confirming that approximately 40% of the variance remaining in onset
age is attributable to genes other than the HD gene and 60% is
environmental.
*This paper also suggests the same, with a smaller (but different) samples.
A recent study of an Italian sample suggests that a polymorphism in Atg7 (autophagy-related gene) is a modifier of age-of-onset, but this result does not generalize to a European cohort.
What is apparently not linked to age of onset in HD? β-defensin copy number variation.
Also, CTCF doesn't appear to be linked to the CAG repeat instability (mutations in CTCF have previously implicated in triplet repeat instability).
Mutations in PGC-1α, mitochondrial regulator, were previously associated with age of onset, but a more recent study suggests that this might have been due to stratification of the sample.
Similarly, a polymorphism in HAP-1 was previously associated with age of onset, but a subsequent study found no evidence of association.
Altogether, these results suggest that population stratification needs to be taken into account when evaluating associations between age of onset and genetic polymorphisms. It is also possible that there are population-specific genetic factors that affect age of onset.
|
[
"stackoverflow",
"0012126358.txt"
] | Q:
Double negative IF statements
While reviewing code, I have come across a few if staments using ! followed by an != in the assessment e.g.
if (!(fs.ReadByte() != (byte)'D' ||
fs.ReadByte() != (byte)'I' ||
fs.ReadByte() != (byte)'C' ||
fs.ReadByte() != (byte)'M'))
{
Console.WriteLine("Not a DCM");
return;
}
Is there any reason to use a double negative over assessing positive e.g.
if ((fs.ReadByte() == (byte)'D' ||
fs.ReadByte() == (byte)'I' ||
fs.ReadByte() == (byte)'C' ||
fs.ReadByte() == (byte)'M'))
{
Console.WriteLine("Not a DCM");
return;
}
Thanks
A:
Those two are different. The first says "None of these are not equal", the second says "any of these are equal".
If you applied the ! operator across them, you'd have to change the || to an &&:
if ((fs.ReadByte() == (byte)'D' &&
fs.ReadByte() == (byte)'I' &&
fs.ReadByte() == (byte)'C' &&
fs.ReadByte() == (byte)'M'))
{
Console.WriteLine("Not a DCM");
return;
}
|
[
"stackoverflow",
"0020290020.txt"
] | Q:
Tornado next query string URL parameter
Question
Since Tornado append a next query string parameter, which contain the URL of the resource building the redirect URL, sometimes we can redirect the user back to the referring page after login or logout applying line self.redirect(self.get_argument("next", "/"))
But when I use this in the following code, It didn't work.
Without login, when visiting Page /test, it will redirect to /login?next=%2Ftest, but the parameter next is always null and it will be redirect to root page instead of /test.
How can I fix this problem?
code
import os
import tornado.wsgi
import tornado.web
import tornado.options
import tornado.ioloop
class BaseHandler(tornado.web.RequestHandler):
def get_current_user(self):
return self.get_secure_cookie("user")
class MainHandler(BaseHandler):
@tornado.web.authenticated
def get(self):
self.render('index.html', user = self.current_user)
class LoginHandler(BaseHandler):
def get(self):
if self.get_current_user():
self.redirect('/')
return
self.render('login.html')
def post(self):
self.set_secure_cookie("user", self.get_argument("username"))
self.redirect(self.get_argument('next', '/'))
class LogoutHandler(BaseHandler):
def get(self):
if not self.get_current_user():
self.redirect('/')
return
self.clear_cookie("user")
self.redirect(self.get_argument("next", "/"))
class TestHandler(BaseHandler):
@tornado.web.authenticated
def get(self):
self.write("Testing!)
settings = {
"static_path" : os.path.join(os.path.dirname(__file__), "static"),
"template_path" : os.path.join(os.path.dirname(__file__), "templates"),
"login_url" : "/login",
"cookie_secret" : "61oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=",
"gzip" : True,
"debug" : True,
}
application = tornado.web.Application([
(r"/", MainHandler),
(r"/login", LoginHandler),
(r"/logout", LogoutHandler),
(r"/test", TestHandler),
], **settings)
if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()
A:
In the get method of LoginHandler, use the next argument for the redirect
...
class LoginHandler(BaseHandler):
def get(self):
if self.get_current_user():
self.redirect(self.get_argument('next', '/')) # Change this line
return
self.render('login.html')
...
|
[
"stackoverflow",
"0004546923.txt"
] | Q:
how to bind/update Whole InstanceList in Controller?
I am new bie in grails and i have following query.
Problem Domain:
Parent Domain Class has a boolean
transient property "isValid".
Child Domain has a boolean property
"isValid".
Parent/list.gsp allow users to alter
isValid property of Parent Instance
in ParentInstanceList, over an update
function in ParentController, which i
can further use to set each Parents
children's property "isValid".
Parent Domain Class
class Parent {
String name
boolean isValid = false
static hasMany = [children:Child]
static transients =['isValid']
}
Child Domain Class
class Child {
String name
boolean isValid
Parent parent
static belongsTo = [parent:Parent]
}
parent/list.gsp
<g:form method="post" action="update" >
<div class="list">
<table>
<thead>
<tr>
<g:sortableColumn property="id" title="${message(code: 'parent.id.label', default: 'Id')}" />
<g:sortableColumn property="name" title="${message(code: 'parent.name.label', default: 'Name')}" />
<g:sortableColumn property="isValid" title="${message(code: 'parent.isvalid.label', default: 'isValid?')}" />
</tr>
</thead>
<tbody>
<g:hiddenField name="parentInstanceList" value="${parentInstanceList }"/>
<g:each in="${parentInstanceList}" status="i" var="parentInstance">
<tr class="${(i % 2) == 0 ? 'odd' : 'even'}">
<td><g:link action="show" id="${parentInstance.id}">${fieldValue(bean: parentInstance, field: "id")}</g:link></td>
<td>${fieldValue(bean: parentInstance, field: "name")}</td>
<td>
<g:checkBox name="isValid" value="${parentInstance?.isValid }"/>
</td>
</tr>
</g:each>
</tbody>
</table>
</div>
<div class="paginateButtons">
<g:paginate total="${parentInstanceTotal}" />
</div>
<div class="buttons">
<span class="button">
<g:actionSubmit class="update" action="update" value="${message(code: 'default.button.update.label', default: 'update')}" />
</span>
</div>
Parent/list.gsp snapshot : http://img156.imageshack.us/i/parentlistview.png/
Query:
how can i track down which parentInstance's property "isValid" is not checked/unchecked that i can easily set parent's children property "isvalid" .
def parentInstanceList = params.parentInstanceList
parentInstanceList.each {
Parent parent = it
parent.children.each{
Child child = it
child.isValid=parent.isValid
}
}
So far i am able to retrieve ids of all parents over params.parentInstanceList but i can not figure it out how can i bind changed properties of each parentInstance.
if there is a single parentInstance then one can easily do it
Parent parentInstance = Parent.get(params.id)
parentInstance.properties = params
thanks in advance
Rehman
A:
I prefer to render for each line a specifically named checkbox:
<g:checkBox
name="Parent_${parentInstance.id}"
value="${parentInstance.isValid ? 'on' : 'off'}" />
and then collect all the checked checkboxes:
def update = {
Collection<Parent> checked = params.collect{ Map.Entry that ->
that.value != "on" ? null : getParentForCheckbox(that.key)
}.findAll{ it != null }
... // and then assign 'isValid' by hand
}
You could use array properties, that it, name the checkboxes like parentInstanceList[0], and then assign properties = params to some object with parentInstanceList property, but it's error prone: you have no guarantee that the parentInstanceList you rendered in HTML will be the same as the that you assign properties to.
|
[
"raspberrypi.stackexchange",
"0000099367.txt"
] | Q:
How do I boot a Compute Module 3+ Lite?
I bought a Raspberry Pi "Compute Module 3+ Development Kit" which includes a Compute Module 3+ Lite (CM3l). Unlike the standard Compute Module 3+ that's included in the kit, this has no on-board eMMC storage to flash a bootable image to.
There's an SD card slot on the Compute Module IO board, but despite inserting an imaged card with Raspbian into it and powering it on, it still doesn't boot?!?!?
A:
The instructions that ship with the kit are a bit opaque for the Compute Module 3+ Dev Kit. I gleaned enough however from them to arrive at the following solution to boot a CM3+ Lite using an SD card I imaged using Balena Etcher (highly recommended for imaging SD cards for either standard Pi's or the Pi Compute Module's with eMMC onboard memory).
First, as there's (2) compute Modules in the kit, let's identify the CM 3+ Lite (the one with no eMMC on-board storage) so there's no confusion:
The kit ships with 4x pairs of jumper wires. We will use one of these to enable the Compute Module 3+ Lite to see the storage on the IO board that it's plugged into.
Next picture is with the Compute Module 3+ Lite inserted into the Compute Module IO board with an imaged SD card in the IO board's SD slot. Connecting the jumper wire to the 2nd pair of pins in GPIO Bank 0 enable the Compute Module 3 Lite to boot from the SD card on the IO board when micro USB power lead is connected to the "Power In" micro USB socket:
I achieved a correct result from the above procedure, but if there's any observed imperfections please advise and I'll update it.
If you need help imaging the Compute Module 3+ with eMMC on-board storage that ships with your kit, please follow these instructions which are quick, painless and proven to work:
How do I Flash (install) Raspbian on Raspberry Pi Compute Module 3 / 3+?
Hope this gets folks up and running with their new Compute Module 3+ Dev Kits which just started shipping yesterday-
|
[
"math.stackexchange",
"0001634988.txt"
] | Q:
On Simple Algebraic Groups
I was skimming a paper and got stuck in the middle. As you see in the underlined parts, the authors first assumed that $\mathcal{G}$ is a simple algebraic group. Then $\mathcal{G}$ is defined to be $SL_n(\mathbb{F})$.
But according to the descriptions of this MO question, $SL_n(\mathbb{F})$ is almost-simple but not simple algebraic group. I'm not so familiar with theory of algebraic groups and got so confused. How should I explain this? I would be grateful for any guide.
A:
A algebraic group over a field k is simple if it is non-commutative and has no closed connected normal subgroups other than itself and e. The word "almost simple" is used if we wish to emphasize that the group need not be simple as an abstract group).(see, J. E. Humphreys, Linear algebraic group (1998), pp168).
|
[
"stackoverflow",
"0010660610.txt"
] | Q:
Checkbox and page reload
I have an asp.net CheckBox, now I want to reload page after check or uncheck and use CheckBox.Checked information to choose sql query for gridview. I have put code like this in Page_Load method:
if (CheckBox1.Checked)
{
query = "select ...";
}
But nothing happen. I set AutoPostBack also. Tried to use event. Don;t know how this system works:/
EDIT:
Checkbox works ok, but the problem is in something different. After I click checkbox, in Page_Load method I will use my query to setup SqlDataSource. Looks like page is reloaded, but gridview is not refreshed. When i click on gridview's column mame (to sort this column), gridview is refreshed by new sql query. So i need to think how to refresh grid view after click check box.
A:
It seems that you are not using IsPostBack property on page load event. If you not use this your CheckBox will be reset on every page load
Try this way
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Here do your stuff.
}
}
|
[
"stackoverflow",
"0023879482.txt"
] | Q:
autocomplete mixed with keydown
I do an autocomplete with jQuery/Ajax and I want to bind to events,when I fill the input to get some displayed values(autocomplete) or when I hit the submit button as well:
$('input[type='text']').on('keydown',function() {
displayFunction();
});
OR
$('input[type='submit']').on('click',function() {
displayFunction();
});
I want to have something which can mix the 2 events:
$('').on('keydown click',function() {//Here in the 2 differents input...
displayFunction();
});
Thanks for your help!!!!
A:
Separe both selector with ,:
$("input[type='text'], input[type='submit']").on('keydown click',function() {//Here in the 2 differents input...
displayFunction();
});
Live Demo
|
[
"stackoverflow",
"0039406997.txt"
] | Q:
How to convert response to another type before it handled by MessageConverter in Spring MVC
For example, here's a method which returns a User:
@RequestMapping(method = GET, value = "/user")
public User getUser() {
return new Users();
}
For some reasons, the client expect an other type
class CommonResponse<T> {
int code;
T data;
}
So I need to convert all return value from T(User for this e.g.) to CommonResponse<T> before it handled by the MessageConverter.
Cause there're many request hanlders should be modified, is there any way to write the convert data just once?
A:
Finally I find ResponseBodyAdvice to do such work.
Here the sample code:
@RestControllerAdvice
public class CommonAdvice implements ResponseBodyAdvice<Object> {
@Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
return returnType.getDeclaringClass().getPackage().getName().startsWith("foo.bar.demo");
// you can change here to your logic
}
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
return new CommonResponse<Object>().setCode(200).setData(body);
}
}
|
[
"mathematica.stackexchange",
"0000207809.txt"
] | Q:
How to export a cell in Messages console to PDF?
Using V12 on windows.
This is the problem. I am calling an external function (Rubi in this case, but it could be anything), which ends up printing a cell (image) to the Console. I simply want to capture this cell and export it to PDF file.
Even if I redirect the output to the current notebook, I can't use the command Export["image.pdf", NotebookRead[PreviousCell[]]]; to do what I want, since the code which call the external function runs in a loop.
Is there a way to do the same as Export["image.pdf", NotebookRead[PreviousCell[]]]; but to use the Message console as the notebook instead of the current notebook?
To make it more clear, here is a MWE.
CurrentValue[$FrontEnd, {"PrintAction"}] = {"PrintToConsole"};
(*a function which prints an image to console*)
externalFunction[max_] := Print[Plot[Sin[x], {x, -max, max}]];
(*run a loop calling the function, and export its output*)
Do[
externalFunction[n];
(*need something like this*)
(*Export["t.pdf",MessagesNotebookRead[PreviousCell[]]]; ??*)
,
{n, 1, 5}
]
Directing the Print to the current notebook does not work
CurrentValue[$FrontEnd, {"PrintAction"}] = {"PrintToNotebook"};
externalFunction[max_] := Print[Plot[Sin[x], {x, -max, max}]];
Do[
externalFunction[n];
Export["t.pdf", NotebookRead[PreviousCell[]]];
,
{n, 1, 5}
]
Since PreviousCell[] in the above is not what I want, it will read the cell before the actual loop itself.
Also this does not work
CurrentValue[$FrontEnd, {"PrintAction"}] = {"PrintToNotebook"};
externalFunction[max_] := Print[Plot[Sin[x], {x, -max, max}]];
Do[
Export["t.pdf", externalFunction[n]]
,
{n, 1, 5}
]
I could not find a way to tell Mathematica to use the Messages console notebook as the notebook to the PreviousCell[]
What is the best way export a cell in Messages console to pdf file? It will be the last cell each time, as in the above example. This is done in a loop. Each iteration generates one Rubi cell in the Messages console and I need to capture that cell as an image.
Appendix
If someone would like to try this with the actual Rubi output, here is a MWE
<< Rubi`
CurrentValue[$FrontEnd, {"PrintAction"}] = {"PrintToConsole"};
Do [
Steps[Int[x Sin[x], x]];
(*save output in console to image, how?*)
Steps[Int[x Cos[x], x]]
(*save output in console to image, how?*)
,
{n, 2}
]
A:
For your MWE the simplest solution is to dynamically redefine the Print function in the Block scope:
Do[
Block[{Print := (Export[ToString[n] <> ".pdf", Echo@#, OverwriteTarget -> "KeepBoth"];) &},
externalFunction[n];
]
, {n, 1, 5}]
This will print every output in the evaluation notebook and immediately Export it after this. With this solution externalFunction may print any number of outputs which will be correctly saved as separate PDF files according to the new in version 12 OverwriteTarget -> "KeepBoth" option. If Rubi uses for printing other function than Print you can redefine it in the same way. If you have high requirements you may need to apply Internal`InheritedBlock and the Villegas-Gayley trick instead of simple Block showed above. But I don't think it is really necessary in your case.
Another approach (which more directly answers the question as it is stated in the title) is suggested in the comment by Gerli:
Do[
externalFunction[n];
Export[ToString[n] <> ".pdf", Last[Cells[MessagesNotebook[]]]]
, {n, 1, 5}]
It assumes that every evaluation of externalFunction results in printing of exactly one Cell in the MessagesNotebook[].
|
[
"stackoverflow",
"0038014401.txt"
] | Q:
One-To-one Database First EF
Dear fellow programmers,
I'm stuck on this basic concept within EF and can't find any solution on stackoverflow.
I want to have One-to-One optional relation between: FluxLocation and Address.
(Normal words: a flux location could be provided with a physical address)
Note the database is already present and final.
SQL TABLES:
CREATE TABLE sales.sales_flux_location(
id serial PRIMARY KEY,
-- Many unusefull properties
sales_address_id integer REFERENCES sales_address
);
CREATE TABLE sales.sales_address(
id serial PRIMARY KEY,
-- Many unusefull properties
);
EF Mapping:
public partial class FluxLocation
{
public int Id { get; set; }
//Many unusefull properties.
[ForeignKey("Address")]
public int? AddressId { get; set; }
public Address Address { get; set; }
}
internal partial class FluxLocationConfiguration : EntityTypeConfiguration<FluxLocation>
{
public FluxLocationConfiguration()
{
//PK
HasKey(x => x.Id);
ToTable("sales_flux_location", "sales");
Property(a => a.Id)
.HasColumnName("id")
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
//FK
HasOptional(l => l.Address)
.WithOptionalDependent(a => a.FluxLocation);
Property(l => l.AddressId)
.HasColumnName("sales_address_id")
.IsOptional();
// + mapping other properties.
}
public partial class Address
{
public int Id { get; set; }
// other properties
public FluxLocation FluxLocation { get; set; }
}
internal partial class AddressConfiguration : EntityTypeConfiguration<Address>
{
public AddressConfiguration()
{
//PK
HasKey(a => a.Id);
ToTable("sales_address", "sales");
Property(a => a.Id)
.HasColumnName("id")
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
//FK
HasOptional(a => a.FluxLocation).WithOptionalPrincipal(l=>l.Address);
// mapping many unusefull properties
}
TEST CASE:
var dbAddress = Context.AddressSet.Add(new Address {Country = "BEL", CityName="Brussel", Street = Guid.NewGuid().ToString() });
var dbLocation = Context.FluxLocationSet.Add(new FluxLocation { AddressId = dbAddress.Id, Country = "BEL", Type = "MARKET", ExtId = Guid.NewGuid().ToString() });
Context.SaveChanges();
Error on Context.SaveChanges():
"42703: column \"Address_Id\" of relation \"sales_flux_location\" does not exist"}
Which is correct because the column name is "sales_address_id".
If any one could help why he is ignoring the propery columnname mapping?
I'm happy to provide more code if needed.
A:
EF is not picking up that you want sales_address_id as the FK so it tried to create Address_Id. Also, there is some weirdness in how EF does 0:1 - essentially you need to fool it with a 1:M
So try this:
//FK
HasOptional(l => l.Address)
.WithMany()
.HasForeignKey(d => d.AddressId);
Link
|
[
"superuser",
"0000454751.txt"
] | Q:
How to grab Cmd-Tab on Macintosh instead of sending to Screen Sharing?
I am using the Screen Sharing application on a Macintosh running OS X Lion. I use Command-Tab to rotate between applications similarly to Alt-Tab on a Windows machine. However, when the Screen Sharing application has focus, the Command-Tab is being interpreted by the target screen instead of my local Macintosh.
How can I override this behavior and have my Macintosh see the Command-Tab instead of the remote screen?
A:
If you press optioncommandx, then the screen sharing window will go into 'observe mode', and won't accept any mouse or keyboard input. Then you can press commandtab and switch apps. I know this doesn't really fix your problem, but it's at least a quick workaround...
A:
Realize this is old but I have found that killing the 'RFBEventHelperd' process using the Activity Monitor app allows Command-Tab to work properly with Screen Sharing. I have not seen any side effects in killing this process.
Only issue is that you have to kill this process every time you launch a new instance of Screen Sharing.
Here is the link where I found this solution: http://hints.macworld.com/article.php?story=20120221065822722
|
[
"stackoverflow",
"0015920303.txt"
] | Q:
Different methods to generate binary choice
I'm currently reading through the Advanced Bash-Scripting Guide and found the following:
# Generate binary choice, that is, "true" or "false" value.
BINARY=2
T=1
number=$RANDOM
let "number %= $BINARY"
# Note that let "number >>= 14" gives a better random distribution
#+ (right shifts out everything except last binary digit).
if [ "$number" -eq $T ]
then
echo "TRUE"
else
echo "FALSE"
fi
echo
Why is it recommended to take bit 15 instead of bit 1? A couple of runs with binary decisions revealed no significant difference between the two.
// UPDATE
Since i was asked how i calculated the distribution, here we go. I generated a couple of $RANDOM numbers, took bit 15 and bit 1 of each number and created two binary sequences. Afterwards i looped through those sequences, checked for chains of 1 and 0 (runs), calculated how many of those runs a maximum length sequence would generate (for reference) and printed everything into a confusing table. Here's the code in all it's glory (sorry for the dirty code...):
#! /bin/bash
COUNT=10000
RUN=1
# generate 2 sequences based on the same $RANDOM numbers
# seq1 = modulo 2, seq2 = bitshift 14
while [ $RUN -le $COUNT ]
do
number=$RANDOM
let 'var1=number%2'
var2=$number
let 'var2 >>= 14'
seq1="${seq1}${var1}"
seq2="${seq2}${var2}"
(( RUN+=1 ))
done
# loop through sequences and check for chains of 1 and 0 (runs)
length=${#seq1}
prevSym=${seq1:0:1}
currRun="${prevSym}"
for (( i=1; i<length; i++ )); do
currSym=${seq1:$i:1}
if (( currSym==prevSym )); then
currRun="${currRun}${currSym}"
(( i!=length-1 )) && continue
(( runStat1[${#currRun}]++ )) #case: ends with run length > 1
break
fi
(( runStat1[${#currRun}]++ ))
(( prevSym=currSym ))
(( i==length-1 )) && (( runStat1[1]++ )) #case: ends with run length = 1
currRun="${currSym}"
done
length=${#seq2}
prevSym=${seq2:0:1}
currRun="${prevSym}"
for (( i=1; i<length; i++ )); do
currSym=${seq2:$i:1}
if (( currSym==prevSym )); then
currRun="${currRun}${currSym}"
(( i!=length-1 )) && continue
(( runStat2[${#currRun}]++ )) #case: ends with run length > 1
break
fi
(( runStat2[${#currRun}]++ ))
(( prevSym=currSym ))
(( i==length-1 )) && (( runStat2[1]++ )) #case: ends with run length = 1
currRun="${currSym}"
done
# print results and expected frequency
# number of expected runs with runlength k:
# 1/2**k if k<n, 1/2**(k-1) if k=n
# $RANDOM generates random numbers in the range 0 to 32768 thus n=15
n=15
echo -e "Length L of run | # of runs with %2 | # of runs with >>14 | # of runs with MLS (calculated)\n "
echo -e "L\t|%2\t|>>14\t|MLS"
echo -e "-----------------------------------\n"
sorted="${!runStat1[*]} ${!runStat2[*]}"
sorted=$(echo $sorted | tr ' ' '\n' | sort -n | uniq)
for a in $sorted; do
k=${a}
(( ${a}==${n} )) && (( k=a-1 ))
prob=$(awk -v k=${a} -v c=${COUNT} 'BEGIN { print (((1/2)**k)*c)/k}')
echo -e "${a} \t| ${runStat1[$a]} \t| ${runStat2[$a]} \t| ${prob} "
done
Running it will print out something along those lines:
Length L of run | # of runs with %2 | # of runs with >>14 | # of runs with MLS (calculated)
L |%2 |>>14 |MLS
-----------------------------------
1 | 2495 | 2450 | 5000
2 | 1219 | 1212 | 1250
3 | 638 | 621 | 416.667
4 | 300 | 329 | 156.25
5 | 162 | 166 | 62.5
6 | 75 | 81 | 26.0417
7 | 46 | 34 | 11.1607
8 | 23 | 26 | 4.88281
9 | 13 | 7 | 2.17014
10 | 2 | 6 | 0.976562
11 | 1 | 1 | 0.443892
13 | 3 | | 0.0939002
15 | | 2 | 0.0203451
21 | | 1 | 0.000227065
Which leads me to the conclusion that, unsurprisingly and also mentioned in all bash references, $RANDOM is a terrible source for randomness... But also "number >>= 14" doesn't have a better random distribution than "number %=2" for a binary choice.
... or i made huge mistake somewhere in this huge mess of silly calculations. You tell me.
A:
The recommendation to use the high-order bits is because many random number generators are implemented as linear congruential generators, which generate poor randomness in the low-order bits.
For example, the following RNG implementation used to be very common. (I believe it was given as an example in the C89 standard.)
unsigned old_rand() {
next = next * 1103515245 + 12345;
return next;
}
Now check out what kind of numbers this generates.
2140733074 // even
3902869603 // odd
4012135520 // even
2255314201 // odd
3913576926 // even
2626310079 // odd
4159329932 // even
1903014357 // odd
Bit 1 is not random at all.
Even a higher-quality LCG, like the one used in Java, suffers from this effect, as this nice graphical demonstration shows. So don't trust the low-order bits of unknown RNGs.
|
[
"stackoverflow",
"0048990296.txt"
] | Q:
Move milliseconds by one position value
as a result of "incorrect" java parsing date (my fault) I now have several thousands of entries in oracle DB with incorrect timestamp.
The issue is as follows:
Timestamp of 2018-06-26 11:15:43.950 has been inserted into DB as
26-FEB-18 11.15.43.095000000 AM
Is there any function for narrowing the milliseconds? I only figured out that with some to_char , to_date functions combined with substring i could "remove" the 0 in front of the miliseconds but it seems to me as not good enough resolution.
Thanks in advance!
EDIT: Unfortunatelly, I can not re-upload data with corrected algorithm.
A:
Best option: reload data from original source, after you fix your code.
If you no longer have access to the original data, and you must fix it all in place, use the UPDATE statement below (shown in context):
create table tbl ( ts timestamp );
insert into tbl ( ts ) values ( timestamp '2018-06-26 11:15:43.0950' );
commit;
select ts from tbl;
TS
----------------------------------------
2018-06-26 11.15.43.095000000
update tbl set ts = ts + 9 * (ts - cast(ts as timestamp(0)));
1 row updated.
commit;
select ts from tbl;
TS
----------------------------------------
2018-06-26 11.15.43.950000000
Explanation:
If your original timestamp was of the form X + w where X is down to whole seconds, and w is the fractional second part, the current value is X + z, where z = w/10. (You added an errant 0 right after the decimal point, which means you divided w by ten). So: you currently have X + z but you want X + w, or in other words, X + 10 * z. So, you must add 9 * z to what you already have.
To get z (the fractional part of the timestamp) you need to subtract X (the integral part) from the timestamp. X itself is the truncation of the timestamp to whole seconds. There is no TRUNC() function to truncate to whole seconds, but the CAST function to TIMESTAMP(0) does that job quite well.
To use your sample data: X is the timestamp '2018-06-26 11:15:43.000000'. This is also the result of cast(ts as timestamp(0)). w is .9500 and z is what made it into your table, .0950. Your current value is X + z, but you want X + w. That is X + 10 * z = (X + z) + 9 * z, and now remember that (X + z) is just ts (the value you have in the table currently) so you only need to add nine times the value z, which is the difference (ts - X).
|
[
"stackoverflow",
"0013864930.txt"
] | Q:
Java - Access For Loop Counter From Inside Anonymous Class
i have a for loop which is adding menuItems to a menu. After adding each menu item, i want to add an actionlistener to it, so when clicked in the menu it will load the corresponding index item from an array. The problem is java will not allow me to call arraylist.get(i) from the anonymous action listener class, as it sais i must be final. i cannot make i final as it increments on each iteration. can anybody help? cheers
A:
Why not extract the element as a final reference outside the anonymous class ?
for (int i = 0: i < list.size(); i++) {
final elem = list.get(i);
// now use it...
}
Note this is safer for another reason. In your original solution you're going back to the list and that could potentially change, such that your anonymous class could extract a different object on each callback. In this variant it's given the final reference to the actual instance.
|
[
"math.stackexchange",
"0001922626.txt"
] | Q:
May conjecture AM-GM without positivity $a_{1}a_{2}a_{3}\cdots a_{2n} \le\left(\frac{a_{1}+a_{2}+\cdots+a_{2n}}{2n}\right)^{2n}$
Let $a_{1},a_{2},\cdots,a_{2n-1},a_{2n}$be real numbers,I conjecture
$$a_{1}a_{2}a_{3}\cdots a_{2n}=\prod_{i=1}^{2n}a_{i}=\le\left(\dfrac{a_{1}+a_{2}+\cdots+a_{2n}}{2n}\right)^{2n}\tag{1}$$
I have know if $a_{i}$ be postive real numbers,It's AM-GM inequality,but it seem for any real numbers,$(1)$ also hold?right?
basis $n=2$ it is for any real $a_{1},a_{2}$,then have
$$a_{1}a_{2}\le\left(\dfrac{a_{1}+a_{2}}{2}\right)^2\Longleftrightarrow 4a_{1}a_{2}\le (a_{1}+a_{2})^2\Longleftrightarrow (a_{1}-a_{2})^2\ge 0$$
A:
This is incorrect. Set $a_1 = a_2 = -1, a_3 = a_4 = 1$.
A:
The case of $2$ numbers does not generalize, because for $k \geq 3$ any pair $(S,P)$ can be attained as the values of $S = a_1 + a_2 + \dots + a_k$ and $P = a_1a_2 \cdots a_k$.
|
[
"stackoverflow",
"0029154929.txt"
] | Q:
android post json, app engine gives 404
Im trying to learn more about webbbservices and python at the same time.
So if you got ideas or solution, explain to me like Im 5. :)
So I want to send a string to the server and just store it in a database (guestbook).
I've managed to do this with a webpage but now I want to access and store a string by phone, this is the python code:
import os
import urllib
import json
from google.appengine.ext import ndb
import jinja2
import webapp2
JINJA_ENVIRONMENT = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
extensions=['jinja2.ext.autoescape'],
autoescape=True)
DEFAULT_GUESTBOOK_NAME = 'default_guestbook'
GUESTBOOKS_NAME = 'guestbook'
def guestbook_key(guestbook_name=DEFAULT_GUESTBOOK_NAME):
return ndb.Key('Guestbook', guestbook_name)
class Guestbook(ndb.Model):
identity = ndb.StringProperty(indexed=True
class Chat(webapp2.RequestHandler):
def get(self):
guestbook = Guestbook(parent=guestbook_key(GUESTBOOKS_NAME))
guestbook.identity=self.request.get("content")
guestbook.put()
self.response.headers['Content-Type'] = "text/plain"
self.response.out.write("ok")
application = webapp2.WSGIApplication([
(r'/chat', Chat),
], debug=True)
and this is the android code:
private void sendData(){
try {
JSONObject jsonobj = new JSONObject();
jsonobj.put("content", "asdf1234");
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppostreq = new HttpPost("http://<myappid>.appspot.com/chat/");
StringEntity se = new StringEntity(jsonobj.toString());
se.setContentType("application/json;charset=UTF-8");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
httppostreq.setEntity(se);
HttpResponse httpresponse = httpclient.execute(httppostreq);
Log.d("Debug", "Response: " + EntityUtils.toString(httpresponse.getEntity()));
} catch (JSONException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e){
Log.d("Debug", "Exception: " + e.getMessage());
}
}
A:
In your routing table : (r'/chat/(\d+)', Chat), this line maps the url to the handler.
which is handled by mapping the (\d+) to product_id in the get function of the handler.
valid urls
/chat/1
/chat/302490205
invalid urls
/chat
/chat/jedi
edit
since your posting your need a post method in your handler
def post(self):
#do stuff
|
[
"stackoverflow",
"0042060424.txt"
] | Q:
IntelliJ can not find dependencies added to compileClasspath
I'm writing some Spark code and compiling into an uber-jar. As is typical for that application you don't want the Spark libraries to be in the jar as they will be provided on the cluster and they're big. The typical trick is that your build.gradle looks something like:
configurations {
provided
}
sourceSets {
main {
compileClasspath += configurations.provided
}
}
dependencies {
compile 'some.library:lib:0.1'
provided 'org.apache.spark:spark-core_2.11:2.1.0'
}
This works from the command line fine. Everything compiles and I can deploy to the Spark cluster without issues. However, IntelliJ gets confused and reports "unresolved reference: spark" for things like import org.apache.spark.api.java.JavaRDD.
How do I keep the dependency out of my jar and keep IntelliJ happy?
A:
I think I found the solution: the idea plugin:
configurations {
provided
}
sourceSets {
main {
compileClasspath += configurations.provided
}
}
idea.module {
scopes.PROVIDED.plus += [ configurations.provided ]
}
dependencies {
compile 'some.library:lib:0.1'
provided 'org.apache.spark:spark-core_2.11:2.1.0'
}
it's annoying to have to add an extra plugin and more code the build for this kind of thing but it seems to work.
|
[
"stackoverflow",
"0026589684.txt"
] | Q:
Python 3.4.2 compile py to exe with images and sounds
I have my python script (battleships.py) and also along with them I have a couple of images and a few wav sound files.
How can I compile it all into one exe file setup so it installs on the users pc and they can then run it with a shortcut, let's say from the desktop.
I've looked around at py2exe and cx_freeze but I can't seem to get them to work.
I'm using python 3.4.2
Thanks :)
A:
You have no other choice than py2exe or cx_freeze.
But I think only cx_freeze works in Python3. You should install it manually. After downloading it and having unzipped it you may run:
python3 setup.py install
(you can do this in a virtualenv)
EDIT:
It seems that it is no more necessary to install it manually for Python3.
You can get directly a Windows installer for Python3.4 version there.
|
[
"stackoverflow",
"0048290157.txt"
] | Q:
How to understand C++ function/data structs?
'strToDouble' was not declared in this scope Lab1-3.cpp /Lab1-3/src line 65 C/C++ Problem
A:
The first problem, as @SoronelHaetir pointed out, is that you were trying to assign title to variable which can only hold one character. Instead, you should use char array, char pointer, or even string object to contain your multi-letter value. In my code example below, I used char array with fixed size of 25, to store the title. Beware that you can store only up to 24 characters in it, because char arrays need special character which will denote the end of char array. Otherwise it would end up writing junk after your desired value. That special character is null-terminating character which is written like '\0'.
Using return; statement in your void displayBid(Info itemOne); function was completely unnecesary. While you can use return; to stop function from executing, you placed it at the end of function which was just about to end itself in normal way, but you forced it with no reason. Besides, you do not need any return; statements for functions which return void – nothing.
Then, fund and bidAmount are representing money value, which may or may not be of integer value, so you should consider float or double data types to store money value.
Next thing is your function Info getBid();. First, I have to say that naming may be a bit confusing. If you read the name of that function without seeing its actual code, how would you understand what it may do? For me, it sounded like it is about to get me information about a bid, while actually it is setting it up. Second, you could simplify code for entering values, in the way I did it in my code example. The way you tried to use different techniques for getting values from user input was a bit wrong. getline is member function which is used with istream objects. Your istream object is cin. In order to access that member function you shall write it as cin.getline(to be discussed);. That function only works with characters. Its first parameter accepts pointer to the first character (address of the first character) in sequence of characters.
Second parameter is of integer data type and specifies how much characters you want to be extracted from your input and stored in an argument which is in place of the first parameter. Beware not to write, for example, 25, because in char array you have to leave one place for '\0' character, which is automatically placed where it needs to be. getline member function has also default delimiter '\n', which denotes new line. It means that you can enter less characters than function can extract, because extraction will stop as soon as it reads that delimiter value from user input. Although, if you want your specific delimiter, getline member function has its overloaded version which third parameter is one where you enter desired delimiter as an argument. (Overloaded functions are basically functions with the same name, but different parameters. They provide same functionality with different implementation.)
Even if you had set up values for a bid, you never returned it from function. You correctly said that its return value is Info, but you did not return it. Actually, you again exited just before its normal exit. Instead, you should have written return itemOne; In my code example, I passed the variable created in int main(); function by reference, which means it is not a copy as usually, so I do not have to return it and assign to another variable of the same type to appropriately apply desired changes.
Finally, in the int main(); function, you could just declare int choice, without initializing it and use do-while loop in the way I did it. Also, switch statement provides defining what will happen if none of the cases are true, in the way that after all cases you write default:, and below it whatever you want to happen. In your code example, your function will continue executing even if user enters anything but 1, 2 except for 9 defined to stop its execution. In my code example, whatever user enters besides 1 and 2, including zero, function will exit. Well, except for new line.
And, let us discuss again the naming. Your data structure name has to directly imply what it is. Info does not do that. That name would actually be more appropriate for your void displayBid(Info itemOne); function to be called. In my code example, I renamed it to Bid.
#include <iostream>
using namespace std;
struct Bid
{
char title[25];
int vehicleID;
double fund;
double bidAmount;
};
void GetBid(Bid item)
{
cout << "Title: " << item.title << endl;
cout << "Fund: " << item.fund << endl;
cout << "Vehicle: " << item.vehicleID << endl;
cout << "Bid Amount: " << item.bidAmount << endl;
}
void SetBid(Bid & item)
{
cout << "Enter title: ";
cin >> item.title;
cout << "Enter fund: ";
cin >> item.fund;
cout << "Enter vehicle ID: ";
cin >> item.vehicleID;
cout << "Enter amount: ";
cin >> item.bidAmount;
}
int main()
{
Bid item;
int choice;
do {
cout << "Menu:" << endl;
cout << " 1. Enter Bid" << endl;
cout << " 2. Display Bid" << endl;
cout << " 0. Exit" << endl;
cout << "Enter choice: ";
cin >> choice;
switch (choice)
{
case 1:
SetBid(item);
break;
case 2:
GetBid(item);
break;
default:
choice = 0;
cout << "Goodbye." << endl;
break;
}
} while (choice != 0);
return 0;
}
|
[
"stackoverflow",
"0014269599.txt"
] | Q:
Trouble with CSV formatting
Having problems with formatting CSV created from C# code. In the notepad file the output scrolls vertically down one row (the values seen in the structs below are output in one row. There is a row of numbers as well that appears directly below the struct values but the numbers should be in a new row beside the structs). When I open in excel it's a similar story only the output from the structs is where it should be however the row of numbers appears directly below the struct values but one row to the right if that makes sense, and the numbers should appear directly beside their corresponding struct values. The code I'm using is below.
Here are the structs for the dictionaries im working with.
public enum Genders
{
Male,
Female,
Other,
UnknownorDeclined,
}
public enum Ages
{
Upto15Years,
Between16to17Years,
Between18to24Years,
Between25to34Years,
Between35to44Years,
Between45to54Years,
Between55to64Years,
Between65to74Years,
Between75to84Years,
EightyFiveandOver,
UnavailableorDeclined,
}
the csv file that does the outputting using a streamwriter and stringbuilder.
public void CSVProfileCreate<T>(Dictionary<T, string> columns, Dictionary<T, int> data)
{
StreamWriter write = new StreamWriter("c:/temp/testoutputprofile.csv");
StringBuilder output = new StringBuilder();
foreach (var pair in columns)
{
//output.Append(pair.Key);
//output.Append(",");
output.Append(pair.Value);
output.Append(",");
output.Append(Environment.NewLine);
}
foreach (var d in data)
{
//output.Append(pair.Key);
output.Append(",");
output.Append(d.Value);
output.Append(Environment.NewLine);
}
write.Write(output);
write.Dispose();
}
And finally the method to feed the dictionaries into the csv creator.
public void RunReport()
{
CSVProfileCreate(genderKeys, genderValues);
CSVProfileCreate(ageKeys, ageValues);
}
Any ideas?
UPDATE
I fixed it by doing this:
public void CSVProfileCreate<T>(Dictionary<T, string> columns, Dictionary<T, int> data)
{
StreamWriter write = new StreamWriter("c:/temp/testoutputprofile.csv");
StringBuilder output = new StringBuilder();
IEnumerable<string> col = columns.Values.AsEnumerable();
IEnumerable<int> dat = data.Values.AsEnumerable();
for (int i = 0; i < col.Count(); i++)
{
output.Append(col.ElementAt(i));
output.Append(",");
output.Append(dat.ElementAt(i));
output.Append(",");
output.Append(Environment.NewLine);
}
write.Write(output);
write.Dispose();
}
}
A:
You write Environment.NewLine after every single value that you output.
Rather than having two loops, you should have just one loop that outputs
A "pair"
A value
Environment.NewLine
for each iteration.
Assuming columns and data have the same keys, that could look something like
foreach (T key in columns.Keys)
{
pair = columns[key];
d = data[key];
output.Append(pair.Value);
output.Append(",");
output.Append(d.Value);
output.Append(Environment.NewLine);
}
Note two complications:
If pair.Value or d.Value contains a comma, you need to surround the output of that cell with double quotes.
If If pair.Value or d.Value contains a comma and also contains a double-quote, you have to double up the double-quote to escape it.
Examples:
Smith, Jr
would have to be output
"Smith, Jr"
and
"Smitty" Smith, Jr
would have to be output
"""Smitty"" Smith, Jr"
UPDATE
Based on your comment about the keys...
For purposes of enumeration, each item in the dictionary is treated as a KeyValuePair structure representing a value and its key. The order in which the items are returned is undefined.
http://msdn.microsoft.com/en-us/library/xfhwa508.aspx
If you cannot use the key to associate the right pair with the right data, how do you make that association?
If you are iterating the dictionary and they happen to be in the order you hope, that is truly undefined behavior that could change with the next .NET service pack.
You need something reliable to relate the pair with the correct data.
About the var keyword
var is not a type, but rather a shortcut that frees you from writing out the entire type. You can use var if you wish, but the actual type is KeyValuePair<T, string> and KeyValuePair<T, int> respectively. You can see that if you write var and hover over that keyword with your mouse in Visual Studio.
About disposing resources
Your line
write.Dispose();
is risky. If any of your code throws an Exception prior to reaching that line, it will never run and write will not be disposed. It is strongly preferable to make use of the using keyword like this:
using (StreamWriter write = new StreamWriter("c:/temp/testoutputprofile.csv"))
{
// Your code here
}
When the scope of using ends (after the associated }), write.Dispose() will be automatically called whether or not an Exception was thrown. This is the same as, but shorter than,
try
{
StreamWriter write = new StreamWriter("c:/temp/testoutputprofile.csv");
// Your code here
}
finally
{
write.Dispose();
}
|
[
"crypto.stackexchange",
"0000079681.txt"
] | Q:
Diffie–Hellman key exchange, why it's hard to break it?
I'm a bit confused why it's hard to break Diffie–Hellman
Let's take the example
ALICE has G, a, and n
BOB had G, b and n
Eve (the third party) succeded to intercept G, n, $G^a, G^b$
ALICE generate the key G^(ab) mod n
BOB generate same key G^ba mod n
What I don't understand is why Eve cant' get a or b by knowing G^a and G^b.?
For me he can just use dichotomy:
Eve will take a random number r_a.
if G^r_a$ < G^a /* already known */
increase(r_a); /* by power ietration for example, +1 +100, +1000, +10000 */
else
decrease(r_a);
adjust(r_a);
A:
The straight-forward method you outlined doesn't work, because $G^a$ is not monotonic in $a$; we can have $G^{r_a} < G^a$ even though $r_a > a$. This happens because we're working modulo $n$, rather than doing exponentiation in the real numbers or integers.
For example, if we have $n=101$ and $G=2$ (for a toy example), then we have:
$$G^8 = 54 > G^{10} = 14$$
even though $8 < 10$
In fact, a practical method for doing probabilistic [1] evaluation of whether $a < b$ given $G^a \bmod n, G^b \bmod n$ (for the values of $n$ we actually use in cryptography) would be of great interest (and would essentially break all crypto based on modular exponentation)
[1] By probabilistic evaluation, I mean that the method doesn't have to give us the correct answer in all cases; it would be sufficient if it was correct with some probability somewhat more than 0.5
|
[
"stackoverflow",
"0029453816.txt"
] | Q:
How to obtain metadata about the current executor(s), Apache-Spark?
I would like to get as much information as possible from within the executor, while it is executing, but can't seem to find any information on how to accomplish that other than by using the Web UI. For example, it would be useful to know which file is being processed by which executor, and when.
I need this flexibility for debugging, but cannot find any information about it.
Thank you
A:
One of the ways to accomplish it is to mapPartitionsWithContext
Example code:
import org.apache.spark.TaskContext
val a = sc.parallelize(1 to 9, 3)
def myfunc(tc: TaskContext, iter: Iterator[Int]) : Iterator[Int] = {
tc.addOnCompleteCallback(() => println(
"Partition: " + tc.partitionId +
", AttemptID: " + tc.attemptId
)
)
iter.toList.filter(_ % 2 == 0).iterator
}
a.mapPartitionsWithContext(myfunc)
a.collect
API: https://spark.apache.org/docs/latest/api/scala/#org.apache.spark.TaskContext
However, this does not answer the question about how to see which file was processed, and when.
|
[
"gamedev.stackexchange",
"0000007157.txt"
] | Q:
How do I have to take into account the direction in which the camera is facing when creating a first person strafe (left/right) movement
This is the code I am currently using, and it works great, except for the strafe always causes the camera to move along the X axis which is not relative to the direction in which the camera is actually facing. As you can see currently only the x location is updated: [delta * -1, 0, 0]
How should I take into account the direction in which the camera is facing (I have the camera's target x,y,z) when creating a first person strafe (left/right) movement?
case 'a':
var eyeOriginal = g_eye;
var targetOriginal = g_target;
var viewEye = g_math.subVector(g_eye, g_target);
var viewTarget = g_math.subVector(g_target, g_eye);
viewEye = g_math.addVector([delta * -1, 0, 0], viewEye);
viewTarget = g_math.addVector([delta * -1, 0, 0], viewTarget);
g_eye = g_math.addVector(viewEye, targetOriginal);
g_target = g_math.addVector(viewTarget, eyeOriginal);
break;
case 'd':
var eyeOriginal = g_eye;
var targetOriginal = g_target;
var viewEye = g_math.subVector(g_eye, g_target);
var viewTarget = g_math.subVector(g_target, g_eye);
viewEye = g_math.addVector([delta, 0, 0], viewEye);
viewTarget = g_math.addVector([delta, 0, 0], viewTarget);
g_eye = g_math.addVector(viewEye, targetOriginal);
g_target = g_math.addVector(viewTarget, eyeOriginal);
break;
A:
Code quality first and foremost
That's a lot of duplicated code you've got going on there. If you've got duplicated code, you need to do it differently - duplicated code is dangerous (you'll change one side but forget to change the other and get logic errors).
If you've got duplicated code down both ends of a conditional, take it out of the conditional.
If you still need to only execute it conditionally (e.g. when the key is a or d) wrap it all in its own conditional.
Consider helper methods.
Now the answer
What you need is to get the Camera's rotation matrix: the exact direction it's pointing.
If the classes you're working with can return that from the camera itself, great! If it can't, you can calculate it based on the camera position and target - see here for one way to do that.
Once you have the camera's rotation matrix, you can just set up the movement vector then rotate it to point in the camera's direction using its rotation matrix.
The advantage of this approach is you can instantiate one general movement matrix, throw in all the vertical, horizontal and forward movement for your character in that update, do all the calculations you'd like on all of it then you do one rotation to face the camera and make that movement happen all at once.
I have no idea which language or framework you're using so I'm going to be using some C# and XNA here.
var keys = Keyboard.GetState();
if (MovementKeysPressed())
{
var eyeOriginal = g_eye;
var targetOriginal = g_target;
var viewEye = g_math.subVector(g_eye, g_target);
var viewTarget = g_math.subVector(g_target, g_eye);
// The important camera rotation stuff happens here
// Determine camera rotation. I am assuming that:
// g_eye is the camera's location,
// g_target is where it's looking,
// and they are both Vector3s
var up = [0, g_up[1]*-1, 0];
var cameraRotationMatrix4 = g_math.matrix4.lookAt(g_eye, g_target, up);
// The rotation component of a 4D transformation matrix is always
// the upper-left 3x3
var cameraRotation = g_math.getUpper3x3(cameraRotationMatrix4);
// Right now we're only doing *direction* of movement - working with 1s only.
// Speed comes after rotation.
var xMovement = 0;
if (keys.A.Down) xMovement -= 1;
if (keys.D.Down) xMovement += 1;
var movementVector = [xMovement, 0, 0];
// Note that holding both A and D is possible and gets you nowhere.
// Sets the vector's length to 1. You'll understand why this is important
// after we introduce speed.
var movementVector = g_math.normalize(movementVector);
// rotate movement to face camera.
var realMovementVector = g_math.rowMajor.mulVectorMatrix(movementVector, cameraRotation);
// Now for speed.
// We earlier normalized movementVector to give it a magnitude (length) of 1.
// After we rotated it, it still only had magnitude of 1.
// Any movement would always create only 1 unit of movement in any direction.
// Let's say you want your character to move faster than that though!
// What if you want your character to move at 4.2 units per update?
// By multiplying it by a scalar (aka integer), we multiplied its magnitude,
// which is now (1 x 4.2) = 4.2. It will now move 4.2 units either left or right
// of the camera (unless the player has both 'a' and 'd' held down).
var speed = 4.2;
var speedThisStep = delta * speed;
realMovementVector = g_math.mulVectorScalar(realMovementVector, speedThisStep);
viewEye = g_math.addVector(realMovementVector, viewEye);
viewTarget = g_math.addVector(realMovementVector, viewTarget);
// End important camera stuff
g_eye = g_math.addVector(viewEye, targetOriginal);
g_target = g_math.addVector(viewTarget, eyeOriginal);
}
MovementKeysPressed = function() {
// current state of the keyboard, stores for each key
// whether it's pressed or not
var keys = Keyboard.GetState();
return (keys.A.State == KeyState.Down || keys.D.State == KeyState.Down);
}
Changes:
Complete refactor
Did camera-rotatey things in the code.
Changed the first argument in the last two occurrences of viewEye and viewTarget
|
[
"stackoverflow",
"0026325625.txt"
] | Q:
How to add a dependency to a module and import the static files (public folder)
I have a NodeJS project and need to add a dependency to another module with some static contents in the public folder, such as js libraries, css, etc.
I want to automatically link the public folder to also use all the static contents from the other module. Is it possible?
Since I'm going to maintain both projects, I don't want to copy/paste the public folder from the main project, because every change I make on the main project I should copy/paste over and over again (this is a terrible idea).
The dependent module will also have a public folder.
A:
Create npm module of you public folder, upload it to github, then you can create dependency of this folder, install it by npm install and ln -s ./public ./node_modules/whatever_your_module_is_called or even to bind this folder as public inside your project
|
[
"stackoverflow",
"0036452236.txt"
] | Q:
How to randomly move an image around a table in Javascript
I have an image in the cell of a table and I want it to move from one cell to another at random. I was planning on using the setInterval and Math.random() to move the image around randomly every two seconds but I cannot get the image to move around at all
<html>
<head>
<style>
tr { width: 300px; height: 100px }
td { width: 100px; height: 100px }
img { width: 100px; height: 100px }
</style>
<script>
function moveImgRandomly()
{
}
</script>
</head>
<body bgcolor="lightblue">
<table border=1 id="myTable">
<tr>
<td></td>
<td></td>
<td><img src="http://graemehobbs93.files.wordpress.com/2012/01/ape-1.jpg" id="img"></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</body>
This is what I have so far that works. I have been trying for hours to get the image to move and it will not. I also cannot use jQuery.
A:
This should do it.
var img = document.getElementById("img");
var tds = document.getElementsByTagName("td");
setInterval(function(){
var randomNumber = Math.floor(Math.random() * tds.length);
tds[randomNumber].appendChild(img);
}, 2000);
tr { width: 300px; height: 100px }
td { width: 100px; height: 100px }
img { width: 100px; height: 100px }
<body bgcolor="lightblue">
<table border=1 id="myTable">
<tr>
<td></td>
<td></td>
<td><img src="http://graemehobbs93.files.wordpress.com/2012/01/ape-1.jpg" id="img"></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</body>
|
[
"stackoverflow",
"0058582189.txt"
] | Q:
How to input many letters and stop after a certain one (q or Q)?
I was assigned a homework to input as many letters as the user wants and stop after input q or Q. Then the programs should output how many vowels there were in such string. We're supposed to use _getche() function but I have MacBook so it doesn't work.
I've tried making conio.h.
I've tried also using cin.get() and getchar() but none work.
A:
#include <iostream> // getchar(), std::cout
#include <cctype> // tolower()
int main()
{
int count = 0;
for (;;) // infinite loop
{
char c = getchar(); // read a single char from stdin
if (tolower(c) == 'q') // if input is 'q' or 'Q'
break; // break out of the loop
// check for vowel here
{
count++;
}
}
std::cout << "You typed in " << count << " vowels!\n";
return 0;
}
|
[
"stackoverflow",
"0008709261.txt"
] | Q:
How to perform Redo Undo operation in EditText
I want to know is there any method or any link or tutorial to perform redo undo operation in Android edittext. If any one knows than please let me know.
A:
Quick note on the Antti-Brax/Divers(Kidinov) solution. It works great, except if you try to use it with a TextView post-API 23, you'll run into problems, because guess-what, Google actually added a hidden UndoManager (android.content.UndoManager) and didn't document it or make it obvious it was there. But if you have a hard/bluetooth keyboard in Marshmallow or Nougat and hit ^Z or SHIFT-^Z, you'll get undo/redo.
The problem comes if you're already using Antti-Brax's class with an EditText, and you also hook it to ^Z and shift-^Z, you'll run into problems with anyone using a hard keyboard. Namely the ^Z will trigger BOTH the native and Antti-Brax's undo, leading to two undos simultaneously, which isn't good. And after a few of them, you'll probably get a Spannable out of bounds crash.
A possible solution I found is to subclass the TextView/TextEdit/whatever and intercept the undo/redo calls from the TextView so they don't run as follows:
@Override
public boolean onTextContextMenuItem(int id) {
int ID_UNDO, ID_REDO;
try {
ID_UNDO = android.R.id.undo;
ID_REDO = android.R.id.redo;
} catch (Resources.NotFoundException e) {
ID_UNDO = 16908338; // 0x1020032
ID_REDO = 16908339; // 0x1020033
}
return !((id == ID_UNDO) || (id == ID_REDO)) && super.onTextContextMenuItem(id);
}
Those magic id numbers were found here, and are used only as a backup if the android.R.id.undo values aren't found. (it also might be reasonable to assume that if the values aren't there the feature isn't there, but anyway...)
This is not the best solution because both undo trackers are still there and both are running in the background. But at least you won't trigger both of them simultaneously with ^Z. It's the best I could think to do until this gets officially documented and the getUndoManager() methods of TextView is no longer hidden...
Why they made a feature you can't turn off (or even know if it was there or not) "live" in released Android I can't say.
I just opened an issue on Android's issue tracker if anyone wants to follow this.
A:
There is an implementation of undo/redo for Android EditText in
http://credentiality-android-scripting.googlecode.com/hg/android/ScriptingLayerForAndroid/src/com/googlecode/android_scripting/activity/ScriptEditor.java
The code works but does not handle configuration changes properly. I am working on a fix and will post here when it is complete.
My Google search was :-
android edittext onTextChanged undo
|
[
"math.stackexchange",
"0002748818.txt"
] | Q:
How to compute Laurent series?
when dealing with Laurent series I am confused about how to compute negative coefficients.
Laurents theorem states (in my course at least) that if f is differentiable on $D(z_0, R)/ \{z_0\}$ R>0. then $\exists a_n\in \Bbb C s.t.f(\zeta)=\sum_{n=-\infty}^{\infty}a_n(\zeta-z_0)^n$, $\zeta \in D(z_0,R)/\{z_0\}$
where $a_n=1/2\pi i\int_{C(z_0,r)}\frac{f(z)}{(z-z_0)^{n+1}}dz$
combining this with cauchy's integral formula for derivatives gives $a_n=\frac{f^n(z_0)}{n!}$.
I tried to compute the Laurent series of $\frac{1}{z^2}$ but I dont understand how to do this for $a_{-1}$ , as $a_{-1}=f^{-1}(0)/-1!$ and I'm not sure how to compute this.
Does $f^{-1}(0)$ simply mean the inverse here ?
Does $-1!=-(1!)$, i.e. does $-n!=-(n!).$
A:
As mentioned in another answer, the Laurent series of $z^{-2}$ is simply $z^{-2}$. We now show it using your formula. First, note that
$$
a_n = \frac{1}{2\pi i}\int_{C(0,1)}\frac{z^{-2}}{z^{n+1}}dz
= \frac{1}{2\pi i}\int_{C(0,1)}z^{-3-n}dz
$$
So if $-3-n \geq 0$, the $a_n = 0$ (by Cauchy's theorem). Thus, $a_n = 0$ for all $n\leq -3$. Now, if $n=-2$ then we may compute
$$
a_{-2} = \frac{1}{2\pi i}\int_{C(0,1)}z^{-1}dz = \frac{1}{2\pi i}\int_0^{2\pi}\left(e^{i\theta}\right)^{-1}ie^{i\theta}d\theta
=1
$$
Now, if $n \geq -1$ then
\begin{align*}
a_{n} = \frac{1}{2\pi i}\int_{C(0,1)}z^{-(n+3)}dz
&= \frac{1}{2\pi i}\int_0^{2\pi}\left(e^{i\theta}\right)^{-(n+3)}ie^{i\theta}d\theta\\
&= \frac{1}{2\pi}\int_0^{2\pi}e^{-(n+2)i\theta} d\theta\\
&= \left.\frac{1}{2\pi}\frac{e^{-(n+2)i\theta}}{-(n+2)i}\right|_0^{2\pi} = 0
\end{align*}
|
[
"stackoverflow",
"0012033716.txt"
] | Q:
Values lost when form made invisible
I am making a simple wizard. I created one static class for holding my forms:
namespace LABEL_AUTOMATION
{
static class ProjectHelper
{
public static Form1 frm1 = new Form1();
public static Form2 frm2 = new Form2();
}
}
and for form1's next button I am having the following code:
private void buttonNext_Click(object sender, EventArgs e)
{
this.Visible = false;
ProjectHelper.frm2.Visible = true;
}
and similar logic for form2's back button:
private void buttonPrevious_Click(object sender, EventArgs e)
{
this.Visible = false;
ProjectHelper.frm1.Visible = true;
}
The problem is that when I move between the forms, the values of the controls like textbox gets cleared.
How to correct it ?
Also, I am using the form's visible changed event to execute the code when the user switches between forms. But, the event gets fired before the form gets visible. Any other event that I can use ?
EDIT: I actually didnt change the Program.cs file which was actually creating and running a seperate instance of Form1. So I changed my code to:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
ProjectHelper.frm1.Show();
}
But it is giving the following error:
The type initializer for 'LABEL_AUTOMATION.ProjectHelper' threw an exception.
A:
I think you are showing/hiding instances of your forms which are not in ProjectHelper class.
You should at Main do
ProjectHelper.frm1.Show();
or
ProjectHelper.frm2.Show();
|
[
"stackoverflow",
"0000216278.txt"
] | Q:
TryParse: What is more readable?
Out style:
bool result;
if(something.TryParse(val, out result))
{
DoSomething(result);
}
Nullable style:
bool? result = something.TryParse2(val);
if(result.HasValue)
{
DoSomething(result.Value);
}
A:
TryParse(val, out result) is a idiom established by the .NET framework in int.TryParse, DateTime.TryParse, etc. It is likely that people that read the code will be familiar with this idiom, so you should stick to it, unless you find a very good reason not to.
A:
I don't mean to be unkind. But when you propose a change to a well-established idiom, it undermines confidence if your sample code isn't right.
Your first example should either be:
something result;
if (something.TryParse(val, out result))
{
DoSomething(result);
}
or:
bool result;
if (bool.TryParse(value, out result))
{
DoSomething(result);
}
Your second example should either be:
Nullable<something> result = something.TryParse2(val);
if(result.HasValue)
{
DoSomething(result.Value);
}
or:
bool? result = bool.TryParse2(val);
if (result.HasValue)
{
DoSomething(result);
}
If I were going to implement an extension method for each value type that did what your TryParse2 seems to do, I wouldn't call it TryParse2. Right now, if a method's name begins with Try, we expect it to return a bool indicating whether or not it succeeded or failed. Creating this new method creates a world where that expectation is no longer valid. And before you dismiss this, think about what was going through your mind when you wrote example code that didn't work, and why you were so sure that result needed to be a bool.
The other thing about your proposal is that it seems to be trying to solve the wrong problem. If I found myself writing a lot of TryParse blocks, the first question I'd ask isn't "How can I do this in fewer lines of code?" I'd ask, "Why do I have parsing code scattered throughout my application?" My first instinct would be to come up with a higher level of abstraction for what I'm really trying to do when I'm duplicating all of that TryParse code.
|
[
"stackoverflow",
"0053638410.txt"
] | Q:
Discrete Integration of a 1st Differenced Logged Series in R
I have a 1st differenced logged series that I need to convert back to the original level units. How do I do this in R?
Below is my data series, their respective transformations, and attempted code:
Original Series:
o <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Logged Series:
l <- c(0.693, 1.099, 1.386, 1.609, 1.792, 1.946, 2.079, 2.197, 2.303)
1st Differenced, Logged Series:
dl <- c(-0.693, -1.792, -2.485, -2.996, -3.401, -3.738, -4.025, -4.277, -4.500)
diffinv(dl, differences = 1)
Desired output:
[1] 1 2 3 4 5 6 7 8 9 10
Attempted Code:
x <- c(1:10)
lx <- log(x)
dlx <-diff(lx)
diffinv(dlx, differences = 1)
Current Output:
[1] 0.0000000 0.6931472 1.0986123 1.3862944 1.6094379 1.7917595 1.9459101
[8] 2.0794415 2.1972246 2.3025851
A:
Just need to remember your definitions. e ^ (ln (x)) = x , therefore
exp(diffinv(dlx, differences = 1))
[1] 1 2 3 4 5 6 7 8 9 10
|
[
"stackoverflow",
"0043458335.txt"
] | Q:
Laravel return last users
I was wondering, what is the simplest way to return last 3 users from database and show them in homepage with Laravel Framework. I have this column, last three registred users/companies and i want to show users name and more info.
A:
Use latest() and take() methods:
User::latest()->take(3)->get();
latest() is a shortcut for orderBy('created_at', 'desc'), so you also can do this:
User::orderBy('created_at', 'desc')->take(3)->get();
|
[
"stackoverflow",
"0034218760.txt"
] | Q:
Python Apscheduler - Schedule Jobs dynamically (nested)
We have a requirement to schedule multiple jobs dynamically while current job is executing.
Approximate Scenario is:
There should be a scheduler to go through a table of application daily basis (assume at 6 AM UTC).
Find the users who has today's datetime as resume_dttime
Dynamically schedule a job for that user and start his service at that today's resume_dttime
So the my code is:
from apscheduler.schedulers.blocking import BlockingScheduler
sched = BlockingScheduler()
@sched.scheduled_job('cron', day_of_week='mon-fri', hour=6)
def scheduled_job():
"""
"""
liveusers = todays_userslist() #Get users from table with todays resume_dttime
for u in liveusers:
user_job = get_userjob(u.id)
runtime = u.resume_dttime #eg u.resume_dttime is datetime(2015, 12, 13, 16, 30, 5)
sched.add_job(user_job, 'date', run_date=runtime, args=[u.name])
if __name__ == "__main__":
sched.start()
sched.shutdown(wait=True)
The queries are:
Is this the good way to add jobs dynamically?
The issue is, there could be 100 or more users. so, adding 100 jobs dynamically is a good idea?
Is there any other way to achieve this?
A:
APScheduler 3.0 was specifically designed to efficiently handle a high volume of scheduled jobs, so I believe your intended way of using it is valid.
|
[
"christianity.stackexchange",
"0000034791.txt"
] | Q:
How might one categorize all of the books of the New Testament by theme?
I've recently been researching the various ways the New Testament has been categorized by scholars. The obvious example is a grouping based on genre, with categories such as biography, historical, epistolary, and apocalyptic.
I've also been made aware of an entirely different categorization scheme which is based on the theological focus and tone of the author, as opposed to genre. The classic categories I've seen are Pauline, Johannine, Synoptic, and Petrine.
However, there are some books that are tricky to classify according to this scheme. For example, what category is James? "Jamine" perhaps? And is Jude normally classified as Petrine, or is it better to think of it as independent from the influence of the Petrine letters?
(In a nutshell, I'm looking for a categorization scheme which is complete, and which has some reasonable justification based on research and/or scholarly consensus)
Here is my attempt to group the books, for reference (I haven't included Acts, Jude, or James):
A:
The Books of the Bible, a reading Bible version of the NIV, has reordered the NT in this way:
Luke-Acts and the Pauline epistles
Luke-Acts
1 Thessalonians
2 Thessalonians
1 Corinthians
2 Corinthians
Galatians
Romans
Colossians
Ephesians
Philemon
Philippians
1 Timothy
Titus
2 Timothy
Matthew and works addressed to Jewish believers in Jesus
Matthew
Hebrews
James
Mark and works addressed to a Roman audience
Mark
1 Peter
2 Peter
Jude
John and the letters of John
John
1 John
2 John
3 John
Revelation
In each section the books are ordered according to their hypothesised date of writing. This arrangement also groups Luke and Paul's writings and Mark and Peter's writings together, which is an advantage as both of these pairs are thought to have worked together in their ministry.
I suspect though that all of these categorisation systems are going to be pretty simplistic. There are so many factors you could categorise them by. For example you could group Colossians, Ephesians and 1 Peter together for their instructions to husbands and wives, or 1 & 2 Thessalonians and 2 Peter together for their focus on eschatology. However you look at it you're likely to see new ways to categorise them, and in the end this kind of scheme can only tell you a tiny fraction of the content of any book.
|
[
"physics.stackexchange",
"0000477460.txt"
] | Q:
How does increasing linear mass density affect wavelength?
In a standing wave, we have the equation:
$$v = \sqrt{\frac{T}{\mu}}$$
where $T$ is string tension and $\mu$ is linear mass density. By this, if we increase linear mass density, wave velocity will decrease. But how does this affect wavelength? Velocity is the product of wavelength and frequency, but what happens when velocity changes?
A:
A standing wave is set up because you have a source that is creating periodic movements of a certain frequency that creates a wavelength of the form $\frac{2L}{N}$ where N is a natural number.
If the mass density is increased without changing the frequency of the driving source then it is obvious that the wavelength won't be equal to $\frac{2L}{N}$ as a lower velocity will lead to a lower wavelength for the same frequency. So, you won't observe a standing wave unless the change in velocity is such that the new wavelength is also of the form $\frac{2L}{N}$. In this case, you will see a different mode of the standing wave.
|
[
"security.stackexchange",
"0000233353.txt"
] | Q:
Email sender spoofing check from receiver
I understand there are techniques to prevent someone from spoofing your domain in emails.
Is there any guarantee or check that the receiver can do to ensure the sender is authentic?
Gmail shows TLS and signature information, is that sufficient to guarantee the authenticity of the sender when present?
A:
Message authentication methods such as SPF, DKIM, and DMARC can be used by a message recipient to determine whether the domain of the apparent sender may have been spoofed. These standards are based on information published in the DNS for the sender’s domain.
In the case of SPF, an SPF record is published in the DNS for a domain to specify the SMTP servers that are authorized to send mail from senders in that domain. If a spoofer tries to send a message appearing to be from *@paypal.com, he is unlikely to be able to relay the message through one of the SMTP servers designated in the SPF record for paypal.com. If he tries to send the message through a SMTP server other than one that is designated in the SPF record for paypal.com, the recipient’s spam filter would likely detect this mismatch and determine that there is a high likelihood that this message was spoofed. As pointed out in the comments by @SteffenUllrich, the shortcoming of SPF is that it only applies to the domain of the sender address in the MAIL FROM of the message envelope, which is generally not seen by the recipient. However, DMARC can be used in conjunction with SPF to apply to the sender address in the message headers as well.
In the case of DKIM, a DKIM record containing a public key is published in the DNS of the domain. A signature over a hash derived from the message body and headers is created using the private key corresponding to that public key, and this signature is included in the headers of the message. If a spoofer attempts to send a message appearing to be from *@paypal.com, he would not have the private key, and therefore would not be able to create a valid signature. Therefore, if the recipient’s spam filter is able to verify the signature using the DKIM public key published in the DNS of the purported sender’s domain, then it’s unlikely that the message was spoofed.
As pointed out by @SteffenUllrich, all of the above frameworks validate the sender’s domain, but not the particular sender. In addition to (or instead of) these frameworks, the sender can sign the message using an S/MIME or PGP/GPG signature. If the recipient has the sender's public signing key, then the recipient can use the public key to verify the signature. If the signature verifies, then this proves that the sender (or someone else that has the sender's private key) signed the message.
|
[
"islam.stackexchange",
"0000055442.txt"
] | Q:
My mother is forcing me not to fast during my exams
My mother thinks I'll mess up my exams if I fast. If i do fast on exam day, she might get extremely angry at me and also worried. Yesterday she explained it might affect her health if I do fast because of how worried she will be. Should I obey her or fast on that day?
A:
You are not required to obey your parents in sin. If fasting is prescribed for you (i.e: you have no significant health complication, you are pubescent, you are not menstruating etc) you should fast.
Your mother will learn to accept it once it becomes normal for her, remember that people used to fight wars while fasting.
|
[
"math.stackexchange",
"0001991311.txt"
] | Q:
Prove $a^{2}(1+b^{2})+b^{2}(1+c^{2})+c^{2}(1+a^2)\geq 6abc$
Prove $a^{2}(1+b^{2})+b^{2}(1+c^{2})+c^{2}(1+a^2)\geq 6abc$
My attempt:
$a^{2}(1+b^{2})+b^{2}(1+c^{2})+c^{2}(1+a^2)-6abc\geq 0$
$\implies a^{2}+a^{2}b^{2}+b^{2}+b^{2}c^{2}+c^{2}+c^{2}a^{2}-2abc-2abc-2abc\geq 0$
$\implies (a-bc)^{2}+(b-ac)^{2}+(c-ab)^{2}\geq 0$
Each of these terms must be non-negative, thus the sum is also non-negative.
I'm new to writing proofs, so I don't know whether this proof is fine.
A:
Alternatively by $AM \ge GM$,
\begin{align*}
a^2(1+b^2)+b^2(1+c^2)+c^2(1+a^2) &=
a^2+b^2+c^2+a^2b^2+b^2c^2+c^2a^2 \\
& \ge 6\sqrt[6]{a^6b^6c^6} \\
\end{align*}
A:
The idea behind your proof is okay, except for the fact that your $\implies$ should rather be $\iff$ for it to be sufficient.
What's more it is not (formally) correct to write $\implies$ signs one after the other, since $\implies$ is not associative ($(A\implies B) \implies C $ is different from $A\implies (B \implies C)$, and both are different from what you seem to mean by $A\implies B \implies C$).
This is one of the reasons why it is always better to use words rather than mathematical notations when it comes to reasonning, in order to avoid confusion, and simply because it (hopefully) requires less effort from the ones who read you since it makes your proof much smoother.
|
[
"meta.serverfault",
"0000001807.txt"
] | Q:
editing other user's posts for completely trivial reasons
I'm relatively new to serverfault/stackexchange, though not to systems administration. I've posted only a few answers here so far. In the last day, two of my posts were edited by other users. I get it, creative commons, etc. - I've been editing on wikipedia for many years, have 10k edits there, I know how it works. If I don't like it, tough noogies.
As a matter of, well, I don't know, courtesy? I find it rather annoying to have someone come in behind me and fix my lack of capitalization.
I've habitually written like this for longer than I can remember (and for the young'uns, that means at least thirty years now). It's a stylistic choice. where necessary/appropriate, I'll use proper capitalisation. In the relatively informal setting of the internet, and a gathering place where one's expertise is what matters, it seems a bit passive-aggressive to be editing another bloke's words for such a trivial reason.
Another post that was edited also fixed the caps, but in addition did some trimming of what I wrote to conform to what that author apparently thought was nicer wording or style - perhaps a touch less verbose than it initially was. Still, it strikes me as a bit passive aggressive. The actual useful information of both posts was unchanged - and isn't it the informative content that matters? Editing other's posts wily-nilly for stylistic reasons just seems rather in-your-face.
If my posts had typos, I'd have no issue with someone bouncing in and fixing them for clarity, that seems an appropriate fix of someone else's post. Likewise, if I wrote something largely correct but left out a 'not' or something that completely changed the meaning, sure, go ahead and fix the error. My writing style? Really?
Hey, this is 'meta', so I figure it's worth asking what others think of this.
A:
It's not just the information that matters, it's the communication of the information. If your post could be understood better through some rewording and proper capitalization, then those edits should be done. Try to not take it so personally. It's not personal. Your knowledge is valuable but your grammar may not be infallible.
Besides all of that, he may just be trying to earn a badge and sees proper capitalization as an easy, legitimate edit.
EDIT
I'm also going to add that a site whose FAQ recognizes its mission as being for professionals should look as though the answers were written by professionals. Would you write a proposal to your board or your clients that used slang, used abbreviations, and didn't capitalize?
A:
Per https://serverfault.com/faq#editing
Other people can edit my stuff?!
All contributions are licensed under Creative Commons and this site is collaboratively edited, like Wikipedia. Edits are tracked in public revision history. If you are not comfortable with the idea of your contributions being collaboratively edited by other trusted users, this may not be the site for you.
That said, we do encourage non-trivial edits, that is, edits which make a post substantively better in a few different ways.
http://blog.stackoverflow.com/2009/04/in-defense-of-editing/
A:
Your choice not to use capitalisation is really no different to someone who doesn't know any better.
The official language of this site is English. If I read quantcast correctly then less than 50% of the people who visit this site have English as a first language. Many questions and answers are poorly written because of a poor understanding of English language, it's usage and the vagaries of it's grammar. These usually get 'fixed up'.
Someone editing your posts to conform with more normal English usage should be expected (it's encouraged, we have badges for editing). There are even tools to help do this.
|
[
"stackoverflow",
"0004970088.txt"
] | Q:
Is there a way to use Eclipse to generate a JSF form from a JPA POJO?
Is there a code generator for Eclipse that can create a facelets form that is based on the fields of a JPA POJO?
I'm just looking for something that can inspect my JPA entity and belch out a form based on it. Doesn't need to be pretty. I'm using a regular Eclipse Helios Java EE distribution. If I have to install a plugin or something, that is fine as long as it is free.
As an alternative if you know of any other tools that can do this that would be good too, as long as it doesn't require installing another IDE. I'm looking for quick and dirty here.
TIA.
A:
Eclipse can't do it out the box. It can only generate JPA entities out of an existing DB table (and vice versa) with the Java EE builtin Dali plugin. For generating JSF/Facelets pages based on JPA entities, there's as far there's only the CRUDO plugin.
Netbeans can do it all out the box by the way.
|
[
"stackoverflow",
"0036362962.txt"
] | Q:
Highcharts-ng with multiple series draw chart incorrectly
I have two fiddles: no angular, and using angular. The one with the angular doesn't work correctly. It doesn't show dates in xAxis, and doesn't use percent for yAxis.
Is there something specific need to be done, to have that work with angular?
No angular html
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<div id="container" style="height: 400px; min-width: 310px"></div>
Angular html
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<div ng-app="myApp">
<div ng-controller="myctrl">
<highchart id="chart1" config="ipo" class="span9"></highchart>
</div>
</div>
Not angular javascript
$(function () {
function createChart() {
$('#container').highcharts('StockChart', {
rangeSelector: {
selected: 4
},
yAxis: {
labels: {
formatter: function () {
return (this.value > 0 ? ' + ' : '') + this.value + '%';
}
},
plotLines: [{
value: 0,
width: 2,
color: 'silver'
}]
},
plotOptions: {
series: {
compare: 'percent'
}
},
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.change}%)<br/>',
valueDecimals: 2
},
series: [{
name: 'IPO',
data: [[1381881600000, 20.34], [1381968000000, 20.43], [1382054400000, 20.72]]
}, {
name: 'SPX',
data: [[1381881600000, 1721.54], [1381968000000, 1733.15], [1382054400000, 1744.5]]
}]
});
}
createChart();
});
Angular javascript
var myApp = angular.module('myApp', ['highcharts-ng']);
myApp.controller('myctrl', BindingCode);
myApp.factory("Factory", Factory);
function ipo() {
this.chartConfig = {
rangeSelector: {
selected: 4
},
yAxis: {
labels: {
formatter: function () {
return (this.value > 0 ? ' + ' : '') + this.value + '%';
}
},
plotLines: [{
value: 0,
width: 2,
color: 'silver'
}]
},
plotOptions: {
series: {
compare: 'percent'
}
},
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.change}%)<br/>',
valueDecimals: 2
},
series: [{
name: 'IPO',
data: [[1381881600000, 20.34], [1381968000000, 20.43], [1382054400000, 20.72]]
}, {
name: 'SPX',
data: [[1381881600000, 1721.54], [1381968000000, 1733.15], [1382054400000, 1744.5]]
}]
}
}
function BindingCode($scope,Factory) {
$scope.ipo = Factory.CreateChart();
$scope.ipo = $scope.ipo.chartConfig;
}
function Factory() {
return {
CreateChart: function () {
return new ipo();
}
}
}
Not angular screenshot
Angular screenshot
A:
The problem is that not all the highchart options go into the top-level JSON configuration.
From the FAQ:
Why doesn't my plot options/tooltip/drilldown/other feature work?
At least half of all issues filed are due to this. Before you file an
issue read this! A common error is to put other Highcharts options
directly into the chartConfig. In general if the Highcharts option you
want isn't listed above you probably want to put it in
chartConfig.options.
In your case, you need to move pretty everything except 'series' into an options object.
chartConfig = {
options : {
rangeSelector: {
selected: 4
},
type: "line",
plotLines: [{
value: 0,
width: 2,
color: 'silver'
}],
plotOptions: {
series: {
compare: 'percent'
}
},
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.change}%)<br/>',
valueDecimals: 2
},
yAxis: {
labels: {
formatter: function () {
return (this.value > 0 ? ' + ' : '') + this.value + '%';
}
},
}
},
series: [{
name: 'IPO',
data: [[1381881600000, 20.34], [1381968000000, 20.43], [1382054400000, 20.72]]
}, {
name: 'SPX',
data: [[1381881600000, 1721.54], [1381968000000, 1733.15], [1382054400000, 1744.5]]
}]
}
Updated fiddle
https://jsfiddle.net/mgwkzob3/1/
|
[
"stackoverflow",
"0026072347.txt"
] | Q:
Can deadlock on database tables allows other queries to execute
I'm working around Microsoft SQL Server. I know that it uses parallel processing. But I want to know that, Say two update query on same table X turns into deadlock situation and 3rd query comes for another table Y, so SQL server will allow to run 3rd query or it'll block until SQL server recovers from deadlock? I tried to put scenario in image for better explanation.
A:
In most normal cases, Q3 will be unaffected by the deadlock between Q1 and Q2, because the locks taken will most likely be page or row locks against table X.
In fact, I can't imagine a scenario where a deadlock could occur if either of the first two queries obtains a table lock. But that's still table X, not Y, which has no existing locks held.
One possible case of Q3 being blocked could occur if either of the others had previously accessed table Y within a transaction with the holdlock option. For example:
Q1
begin transaction;
select * from Y where some_col = 'goats' with (updlock, holdlock);
update X set other_col = 'alpacas' where animal = 'best'; -- deadlock occurs here
commit transaction;
This is pretty contrived, but Q1 has obtained an update lock on table Y that is held until the end of the transaction, blocking any selects from Q3 until the transaction has complete (and the deadlock resolved).
|
[
"english.stackexchange",
"0000223067.txt"
] | Q:
'no matter in which way' or 'no matter which way?
Is in necessary in the phrase:
It is the same, no matter in which way it is done.
That is, is it acceptable to write:
It is the same, no matter which way it is done.
A:
The frequent "in which way" is nearly always shortened to "which way".
|
[
"stackoverflow",
"0049347535.txt"
] | Q:
FireBaseUI Auth - how to know if account is from a new signup or existing user?
I am using firebaseUI for authentication. it essentially opens a a external activity and logs the user into firebase and sends the developer a call back in onActivityResult. It works great the problem is i need to know if the user is a new signup or an existing user. is there any kind of metadata or something i can use to know this ? here is what i have so far IN JAVA ANDROID:
private void ititFireBaseUi() {
AuthUI.getInstance()
.signOut(getActivity())
.addOnCompleteListener(new OnCompleteListener<Void>() {
public void onComplete(@NonNull Task<Void> task) {
// Choose authentication providers
List<AuthUI.IdpConfig> providers = Arrays.asList(
new AuthUI.IdpConfig.Builder(AuthUI.EMAIL_PROVIDER).build(),
new AuthUI.IdpConfig.Builder(AuthUI.PHONE_VERIFICATION_PROVIDER).build(),
new AuthUI.IdpConfig.Builder(AuthUI.GOOGLE_PROVIDER).build(),
new AuthUI.IdpConfig.Builder(AuthUI.FACEBOOK_PROVIDER).build());
//new AuthUI.IdpConfig.Builder(AuthUI.TWITTER_PROVIDER).build());
// Create and launch sign-in intent
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setAvailableProviders(providers)
.setLogo(R.drawable.logo)
.build(),
RC_SIGN_IN);
}
});
}
and then for the result:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
IdpResponse response = IdpResponse.fromResultIntent(data);
//I WOULD LIKE TO KNOW HERE IF THE USER IS A NEW USER OR EXISTING USER
String msg = "";
if (resultCode == RESULT_OK) {
// Successfully signed in
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
msg = "generating token with email:" + user.getEmail();
Timber.d(msg);
Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
presenter.generateTokenWithFireBase(user);
// ...
} else {
// Sign in failed, check response for error code
}
}
}
}
I see a meta class that maybe can help me but i dont know how to use it.
gradle : implementation 'com.firebaseui:firebase-ui-auth:3.2.2'
A:
Do not use the creation and sign in timestamp comparison. I found it to be unreliable.
IdpResponse has a isNewUser() method to tell you whether the login is a new account or not.
A:
public boolean isNewSignUp(){
FirebaseUserMetadata metadata = mAuth.getCurrentUser().getMetadata();
return metadata.getCreationTimestamp() == metadata.getLastSignInTimestamp();
}
At the time of writing, Looks like each logged in user has meta data as i suspected. we can check the last sign time to know if its a new account. I heard they will be making this easier in the future, check later versions of firebase authentication before attempting this.
|
[
"stackoverflow",
"0041369553.txt"
] | Q:
memory allocation in x86 Assembly language
I was learning about SIZEOF and TYPE operators yesterday. While doing that, I created an array,
Array QWORD 1h,2h,3h,4h,5h
and in .code section, I wrote,
MOV eax, SIZEOF Array
After assembling this, it's awkward that I got only 28 bytes allocated for array (using visual studio community 2015). I saw the values of registers in debugging session.
My question here is, each QWORD occupies 8 bytes of memory. Then, why didn't I get SIZEOF Array as 40?
Even worse.
When I run this,
Array QWORD 1h
it gave me 8 bytes as expected
Array QWORD 1h,2h
Gives me 10..!!
And,
Array QWORD 1h,2h,3h
Gives me 18..!!
And so on...
A:
By default, Visual Studio's register window shows hexadecimal numbers. Could it be that you are confusing 28 with 0x28? 0x28 is the same as 40. (Similarly, 0x10 is 16, 0x18 is 24, and so on.)
|
[
"es.stackoverflow",
"0000202873.txt"
] | Q:
Rescatar un dato desde un texto con expresión regular
quisiera consultar sobre una forma por medio de una expresión regular para extraer del texto siguiente el nombre que está marcado en negro
este es un ejemplo de lectura de un documento que viene por OCR:
JOSE ANTONIO VEGA SANCHEZ | D. IDENTTFICACION I C.C. 3.131.656 I BANCO
La idea es generar una expresión regular que pueda sacar solo el nombre que está en negrita que en este caso es JOSE ANTONIO VEGA SANCHEZ, espero me puedan ayudar y muchas gracias por la cooperación en este caso.
A:
Si tus string limita los campos por medio un pipe, podes usar la siguiente expresión:
^(.*)\|
donde
^ indica el comienzo del string
(.*) captura cualquier carácter imprimible en el grupo $1
\| escapa el pipe para finalizar la captura del grupo.
|
[
"stackoverflow",
"0009047070.txt"
] | Q:
Locking data to an Excel Chart
In VBA code I create a chart from a sheet with filtered data.
When I go to create the second chart (re-filtering the data, creating new chart), both charts take the values of the second chart.
How can I lock the chart data of the first chart to prevent it from being overwritten when the second chart is created?
VBA code
1. Filter data for graph 1
2. Create graph 1
3. Filter data for graph 2
4. Create graph 2
Graph 1 and graph 2 now both have graph 2's data.
Now what I tried to do was to
5. Cut the chart and using "PasteSpecial" as an image.
Sheets("Sheet2").PasteSpecial Format:="Picture (Enhanced Metafile)", Link:=False, DisplayAsIcon:=False
It worked on my computer but whenever it was run anywhere else it would produce an error.
Namaste
A:
ulvund: Instead of manually copying and pasting it as an image, have you considered exporting the chart as an image and then re-importing it in Excel? The below works for me :)
Example
Option Explicit
Sub Sample()
Dim FileNM As String
FileNM = "C:\Sample.jpg"
'~~> Export the chart as a jpg
Sheets("Sheet1").ChartObjects(1).Chart.Export Filename:=FileNM, FilterName:="jpg"
DoEvents
'~~> Import the saved image in Sheet 2
Sheets("Sheet2").Pictures.Insert FileNM
End Sub
A:
The easiest way to get the behavior you are looking for is to add code to your chart creation method to move the chart's source data to a hidden utility spreadsheet, or something similar, and not reference the "working" range directly.
For example, first copy the data to a hidden spreadsheet you create called "ChartData" and then change the chart creation code to look at that sheet instead of where it is looking now. Then, you can either retain a counter on some configuration sheet, or use the spreadsheets shapes collection (search ActiveSheet.Shapes for objects of type Chart) to determine how many charts have already been created and set up subsequent charts to reference their own individual columns on "ChartData" so that there will be no overlap.
If you use the shapes collection, however, remember to cleanup the ChartData sheet to keep your data and chart collection in sync.
However you solve the problem though, the key is to have the charts reference their own data series and not a shared source.
|
[
"stackoverflow",
"0031659306.txt"
] | Q:
Collect decoded audio from libav as doubles
I'm currently trying to gather decoded audio data (from multiple formats) to perform certain audio manipulations (using a *.wav file for testing).
I have a class that handles all the decoding via FFmpeg libav. If I extract the data as unit8_t into a vector, and
for (int i = 0; i < bytevector.size(); i++) {
fwrite(&bytevector[i], sizeof (uint8_t), 1, outfile2);
}
to a raw file and play it via
play -t raw -r 44100 -b16 -c 1 -e signed sound.raw it sounds perfectly fine.
However, how is it possible to have all the correct information as doubles when the file for example is 2 bytes per sample and the frame->data information is given as uint8_t? The wav files I've tested are 44100/16bits/1 channel. (I already have code that will change uint8_t* into a double)
Opening the same files with Scilab will show half the size of the byte vector as doubles.
wav file in Scilab as an array of doubles shows:
-0.1, -0.099, -0.098, ..., 0.099, +0.1
versus byte vector:
51, 243, 84, 243, 117, 243, ...
Can 51 and 243 really form a double? Any suggestions on how to get past this issue?
Code below for reference:
while ((av_read_frame(formatContext, &readingPacket)) == 0) {
if (readingPacket.stream_index == audioStreamIdx) {
AVPacket decodingPacket = readingPacket;
while (decodingPacket.size > 0) {
int gotFrame = 0;
int result = avcodec_decode_audio4(context, frame, &gotFrame, &decodingPacket);
if (result < 0) {
break;
}
decoded = FFMIN(result, decodingPacket.size);
if (gotFrame) {
data_size = (av_get_bytes_per_sample(context->sample_fmt));
if (data_size < 0) {
}
// Only for 1 channel temporarily
for (int i = 0; i < frame->nb_samples; i++) {
for (int ch = 0; ch < context->channels; ch++) {
for (int j = 0; j < data_size; j++) {
bytevector.push_back(*(frame->data[ch] + data_size * i + j));
}
}
}
} else {
decodingPacket.size = 0;
decodingPacket.data = NULL;
}
decodingPacket.size -= result;
decodingPacket.data += result;
}
}
av_free_packet(&readingPacket);
}
A:
Quick way to transform two bytes into a float:
byte bits[] = {195,255}; //first sample in the test s16 wav file
int16_t sample;
memcpy(&sample,&bits,sizeof(bits));
std::cout<<sample*(1.0f/32768.0f)<<std::endl;
This code yields -0.001861572265625 when printed (with more precision setprecision(xx);) which is first number given by Scilab with the same file.
I hope this help anybody with similar issues.
|
[
"stackoverflow",
"0029645770.txt"
] | Q:
Replacing a parent XML tag if contains a string using regex
I have the following XML :
<customer>
<name>Customer name</name>
<address>
<postalcode>94510</postalcode>
<town>Green Bay</town>
</address>
<phone>0645878787</phone>
</customer>
I would like using only REGEX, replace the whole <address>..</address> tag with an empty string if the postal code is 94510
I have
String s = "<the xml above here/>"
s = s.replace(source, target);
I only have control over "source" and "target". Is there a regular expression that may solve this problem ?
Thank you
A:
The most straightforward way I can see to do this without external libraries is to use an XPath expression to select the nodes that should be deleted, and to then delete them. This is fairly verbose in Java but not terribly complicated:
import java.io.*;
import javax.xml.parsers.*;
import javax.xml.xpath.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
import javax.xml.transform.dom.*;
import org.w3c.dom.*;
public class Foo {
// Error handling should be done, but I can't know what you want to happen
// in case of broken XML.
public static void main(String[] args) throws Exception {
String xml =
"<customer>\n"
+ " <name>Customer name</name>\n"
+ " <address>\n"
+ " <postalcode>94510</postalcode>\n"
+ " <town>Green Bay</town>\n"
+ " </address>\n"
+ " <phone>0645878787</phone>\n"
+ "</customer>";
// XPath expression: It selects all address nodes under /customer
// that have a postalcode child whose text is 94510
String selection = "/customer/address[postalcode=94510]";
// Lots of fluff -- the XML API is full of factories; don't mind them.
// What all this does is to parse the document from the string.
InputStream source = new ByteArrayInputStream(xml.getBytes());
Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(source);
// Create a list of nodes that match our XPath expression
XPathExpression xpath = XPathFactory.newInstance().newXPath().compile(selection);
NodeList nodes = (NodeList) xpath.evaluate(document, XPathConstants.NODESET);
// Remove all those nodes from the document
for(int i = 0; i < nodes.getLength(); ++i) {
Node n = nodes.item(i);
n.getParentNode().removeChild(n);
}
// And finally print the document back into a string.
StringWriter writer = new StringWriter();
Transformer tform = TransformerFactory.newInstance().newTransformer();
tform.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
tform.transform(new DOMSource(document), new StreamResult(writer));
// This is our result.
String processed_xml = writer.getBuffer().toString();
System.out.println(processed_xml);
}
}
|
[
"japanese.stackexchange",
"0000076994.txt"
] | Q:
Confusions on usage of the past tense ていた and た to express an ongoing actions and states (namely, 'has/has been' doing something):
So, as far as I'm aware, the ていた ending can have these meanings depending on verb used:
a past continuous action and works pretty similarly to English:
(彼女がシャワーを浴びている間僕は勉強していた。)
a past state:
(お腹が空いていた)
had been doing something.
Now, these usages are confusing me and is something I've been seeing recently:
私は今まで続けてた仕事を、今年もちゃんと続けれればなって思いますね。
This is from a youtube video about new year's resolutions (will link below). I had expected to either find 続けている or 続けてきた here, based on the usages above. It seems like she is still doing her job and it is continuing into the now and future, so to speak. It was translated (and I think definitely correctly) as "well, I just hope I'll be able to continue the job I've been doing up to now".
Similarly, I don't understand an example like this:
前から興味があったからその仕事をやらせてください。(I've been interested in that for a while so please let me do it). Taken from my textbook.
I'm trying to think of this in terms of Japanese and not English but surely the speakers in both sentences are 1. still doing their job now, and 2. still have the interest. So I'm confused. This is not the first time I've seen things like this.
Video: https://youtu.be/7x2NBdoXuLk?t=188
A:
This is what I love coming to this forum as a native speaker! Interesting valid observations to expressions that I take for granted, which in turn give me new insights.
Both of those expressions feel completely normal and acceptable to me, but I believe for different reasons.
続けてた is an informal speech form of 続けてきた in this sentence. I don't think 続けていた would be quite appropriate here for the exact reason you mentioned.
前から興味があった is OK, and the past form is chosen simply because the emphasis of the phrase is in the past, that the interest had developed some time ago,and it is "から" that adds the continuity. Think 前は興味があった, which would mean "I used to be interested [but not anymore]"
|
[
"stackoverflow",
"0032639989.txt"
] | Q:
Centralized shared gulp dependencies for multiple projects?
Is it possible to share gulp dependencies for multiple projects instead of having them in every project folder (as it is for default)?
This is what I'm aiming for (every client project would have the same structure):
/shared
node_modules
shared_scss
shared_js
gulpfile.js
/client-project-1
client_scss
client_js
gulpfile.js
/client-project-2
/client-project-3
/client-project-n
A:
Sharing dependencies in Node.js is easy: given a module id that requires a lookup, the require.resolve algorithm searches in node_modules directories and walks up the directory tree doing that until module is resolved:
If the module identifier passed to require() is not a native module, and does not begin with '/', '../', or './', then Node.js starts at the parent directory of the current module, and adds /node_modules, and attempts to load the module from that location.
If it is not found there, then it moves to the parent directory, and so on, until the root of the file system is reached.
Back to your question, you can basically put your projects into one directory with a shared node_modules subdirectory and every require call from any of your client project directories will load the dependency from that shared node_modules (if it exists and not overridden in the client directory).
shared
├── node_modules
│ └── ...
├── shared_js
├── shared_scss
├── gulpfile.js
|
├── client-project-1
│ ├── client_js
│ ├── client_scss
│ └── gulpfile.js
|
├── client-project-2
├── client-project-3
└── client-project-n
If you also symlink shared_js into shared/node_modules/shared_js, client projects will be able to require them with require('shared_js/...').
Alternatively, you can install shared dependencies globally into $HOME/.node_modules or $NODE_PATH, but this is discouraged.
|
[
"stackoverflow",
"0004316019.txt"
] | Q:
How can I create a custom View with a Relative Size?
I would like to design an application which could work with devices of any screen resolution.
My idea to do so was to create one Custom View for each type of View I use, and use the layout_width and layout_height specified in the XML as a percentage of the parent size (for example, layout_width="100dp" is equivalent to fill_parent, and layout_width="50dp" means the View's width will be half the parent's one).
Here is the custom TextView class I made:
public class RSTextView extends TextView {
public RSTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int w, int h) {
int parentWidth = ((View)this.getParent()).getWidth();
int parentHeight = ((View)this.getParent()).getHeight();
Log.i(null, "Width: " + w + "; Height: " + parentHeight);
this.setMeasuredDimension(parentWidth * MeasureSpec.getSize(w) / 100,
parentHeight * MeasureSpec.getSize(h) / 100);
}
}
However, it does not work. The parentWidth and parentHeight size is always 0.
Is there any better way to create an application with a relative size?
And if it is the right way to go, how can I retrieve the View's parents' size from the onMeasure method?
A:
Since you're checking a view's height during the layout phase, you probably want to be using getMeasuredHeight, not getHeight, but I'm not sure you need to be doing what you're doing at all. It's hard to tell from your description, but it seems like you might be trying to recreate the behavior of LinearLayout weights. For example, if you have a horizontal LinearLayout with 3 children, you can easily set the first to take up half its width and the others each to take up 25% by assigning them 0px layout_widths and layout_weights of 2, 1 and 1 respectively (or any other weights of those proportions).
If you do decide to go the custom View route, though, don't overload what layout_height and layout_width do -- use custom XML attributes to take the argument for the percentages (I'd dig into LinearLayout's code to see how layout_weight is implemented).
|
[
"stackoverflow",
"0059896042.txt"
] | Q:
Pandas is sorting integer in a wierd way like string
Even when a column in a pandas df is int.. It is being sorted like a string or in a weird way.
n_frames video img
-----------------------------
1 Videos482 1.jpg
10 Videos482 2g.jpg
11 Videos482 2d.jpg
2 Videos482 1q.jpg
1 Videos484 234.jpg
100 Videos484 34.jpg
What I want is: See the n_frames column.
n_frames video img
-----------------------------
1 Videos482 1.jpg
2 Videos482 1t.jpg
10 Videos482 2g.jpg
11 Videos482 1q.jpg
1 Videos484 234.jpg
100 Videos484 34.jpg
When I check df.dtypes I get:
n_frames int32
My code:
print(df.dtypes)
df = df.groupby('video')
df.apply(lambda _df: _df.sort_values(by=['n_frames']))
df.apply(lambda _df: _df.to_csv("rubbish.csv", index=False ))
So basically. I want to groupby the video keeping the n_frames in increasing accending order.
Upper data is small form of original.
Original>
n_frames,trainTest,classes,vdo_noext,img
1,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 1.jpg
10,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 10.jpg
100,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 100.jpg
101,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 101.jpg
102,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 102.jpg
103,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 103.jpg
104,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 104.jpg
105,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 105.jpg
106,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 106.jpg
107,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 107.jpg
108,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 108.jpg
109,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 109.jpg
11,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 11.jpg
110,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 110.jpg
111,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 111.jpg
112,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 112.jpg
113,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 113.jpg
114,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 114.jpg
115,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 115.jpg
116,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 116.jpg
117,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 117.jpg
118,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 118.jpg
119,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 119.jpg
12,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 12.jpg
120,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 120.jpg
Update: n_frames column dtype was never a string and integer even before I converted into int..
Why is integer being sorted in that wierd way?
A:
Difficult to say without the data to hand but I would switch the rows around like so:
df = df.groupby('video')
df['n_frames'] = df['n_frames'].astype(int)
df.apply(lambda _df: _df.sort_values(by=['n_frames']))
df.apply(lambda _df: _df.to_csv("rubbish.csv", index=False ))
In other words, change the data type after the groupby
|
[
"stackoverflow",
"0036949697.txt"
] | Q:
Trying to find common elements between the rows in a single 2D array
I have a 2 dimensional String array and I am trying to find if the rows have common elements between them and what that element is. It should look at the element that is in (0,0) and compare it to the element that is in (1,0), (1,1), (1,2) and so on. I am trying to use nested for loops but I can't seem to get it right. Could someone tell me what is wrong with my code and how I should fix it?
for(int i = 0; i < times.length; i++ ){
for(int j = 0; j < times[i].length; j++ ){
if(i+1 < times.length)
if(times[i][j].equals(times[i+1][j])){
System.out.println(times[i][j + " = " + times[i+1][j])
}
}
}
A:
I will try to keep this as intuitive and easy to understand as possible. The bounds for the first row is [0, times.length - 2]. That way, the bounds for the second row will be [1, times.length - 1].
For each element in first row, I will check every element in the second row. The following code demonstrates that.
for(int row = 0 ; row < times.length - 1 ; row++) {
for(int colFirst = 0 ; colFirst < times(row).length ; colFirst++) {
for(int colSecond = 0 ; colSecond < times(row + 1).length ; colSecond++) {
if(times[row][colFirst].equals(times[row+1][colSecond]))
System.out.println(times[i][j + " = " + times[i+1][j]);
}
}
}
|
[
"stackoverflow",
"0025106511.txt"
] | Q:
IncludeJS with timeInterval issue
Source code.
var page = require('webpage').create();
page.onConsoleMessage = function(msg) {
console.log(msg);
};
page.open("http://info.finance.yahoo.co.jp/fx/", function(status) {
if ( status === "success" ) {
interval = setInterval(function(){
console.log("executed");
page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {
var result = page.evaluate(function() {
console.log($("#USDJPY_bid").text());
});
});
}, 3000);
}
});
It works.
>phantomjs --web-security=false sample.js
executed
102.6
executed
102.6
102.6
executed
102.6
102.6
102.6
I want to get data reloaded by jQuery. First it connect to website and, and repeat executing jQuery with keeping connect.
Number of console.log is increse each time it called. It happens only inside of Includejs. I need it called only once.
A:
If you look closely, you will see that jQuery is already included in the page, so you don't need to include it yourself. This is sufficient:
page.open("http://info.finance.yahoo.co.jp/fx/", function(status) {
if ( status === "success" ) {
interval = setInterval(function(){
var result = page.evaluate(function() {
console.log($("#USDJPY_bid").text());
});
}, 3000);
}
});
If you still want to include your version of jQuery, then you should do this only once:
page.open("http://info.finance.yahoo.co.jp/fx/", function(status) {
if ( status === "success" ) {
var loaded = false;
page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {
loaded = true;
});
setInterval(function(){
if (!loaded) return;
page.evaluate(function() {
console.log($("#USDJPY_bid").text());
});
}, 3000);
}
});
This works on my machine only without the --web-security=false flag. Strangely, I have to decouple includeJs from setInterval.
|
[
"stackoverflow",
"0050416714.txt"
] | Q:
How to get Dropdown to return text value instead of index value
I am currently working on a drop down within my form and it is returning the index value e.g. 0,1,2 when the box is selected. I need it to return the literal text within the box e.g. 'Server One','Server Two' . I am working with the laravel collective forms. attached is the code snippet for the form. Any help would be much appreciated! The variable $statuses is the list of all the servers within the database.
@extends('layouts.app')
@section('content')
<h1></h1>
<h1>Edit Incident</h1>
{!! Form::open(['action' => ['IncidentsController@update', $incident->id], 'method' =>'POST']) !!}
<div class="form-group">
{{Form::label('title','Title')}}
{{Form::text('title',$incident->title,['class' => 'form-control', 'placeholder' => 'Title'])}}
{{Form::label('body','Body')}}
{{Form::textarea('body',$incident->body,['id' => 'article-ckeditor','class' => 'form-control', 'placeholder' => 'Body text'])}}
{{Form::label('status','Server Status:')}}
<br>
{{Form::label('status','Resolved:')}}
{{Form::radio('status', 'Resolved' , false) }}
<br>
{{Form::label('status','Unresolved:')}}
{{Form::radio('status', 'Unresolved' , true) }}
<br>
{{ Form::label('server', 'Server:') }}
<br/>
{{Form::select('server', $statuses),['name' => "server",'class' => 'form-control']}}
</div>
{{Form::hidden('_method', 'PUT')}}
{{Form::submit('Submit', ['class' => 'btn btn-primary'])}}
{!! Form::close() !!}
dd($server)
@endsection
createIncident:
public function createIncident(){
$statuses = Status::pluck('server');
dd($statuses);
return view('createIncident', ['statuses' => $statuses]);
}
result of dd($statuses)
A:
ended up changing the way I displayed and stored the form itself and used select tags to fix it.
<select name="server">
@foreach($statuses as $key => $value)
<option>{{$value}}</option>
@endforeach
</select>
|
[
"stackoverflow",
"0044911235.txt"
] | Q:
Reactjs, How to compare props.location.pathname to a string?
In my router, I need to do the following:
if (props.location.pathname !== '/confirm') {
// redirect to /confirm to force the user to confirm their email
}
The if statement is not acting as expected.
If I output:
console.log(props.location.pathname)
I get in the console.
/confirm
However, props.location.pathname with the value of '/confirm' is not being seen as the same as /confirm
What am I doing wrong?
A:
type of both the operands should be same while using == for comparision.Make sure both are of string type or change if to
if (props.location.pathname != '/confirm') {
// redirect to /confirm to force the user to confirm their email
}
|
[
"english.stackexchange",
"0000120145.txt"
] | Q:
Which logical fallacy pushes through something as though it were fact and creates a point of contention afterwards to distract?
For example:
"To corrupt society by allowing violent video games is something only a mother could understand."
The point of contention is likely to be the latter part, where you'd be tempted to say "That's nonsense, being a mother doesn't somehow give you greater powers of perception" or similar, and argue about that, whilst completely missing the point that the person arguing has just stated that violent video games corrupt society and it has gone through unnoticed.
They could easily follow up with "Go on then, name one man that is able to understand the corruption they cause", and you're now fighting on two fronts - if you say "hold on, that premise is flawed" you can be steamrolled over because it sort of seems like it should be true, and you immediately weaken your position as appearing not to understand thus proving the second point about mothers.
Alternatively, you could defend yourself and argue their case for them "Well as a man I was exposed to many video games as a child and they haven't had any effect on myself or anyone that I know", and you're knee deep in agreeing with their hidden assumption before you know it.
A:
You are describing, at least in part, an argument based on false premises. However you are also adding an element of misdirection.
But your question is fatally flawed. Your British public school habit of engaging in distraction when crafting a "logical" position is arguably the principal reason that the budget shortfall will continue to shape the debate to end the logjam on the withdrawal of Royal troops from the American colonies.
Obviously.
|
[
"math.stackexchange",
"0001857462.txt"
] | Q:
Let S be a bounded subset of $\mathbb{R}^n$. If $f$ is integrable (Riemann sense) on $S$ then $f$ is integrable on $int S.$
Let S be a bounded subset of $\mathbb{R}^n$. If $f$ is integrable (Riemann sense) on $S$ then $f$ is integrable on $int S$ and $\int_{int~S}f = \int_Sf.$
I know this theorem using that $f$ is continuous. To prove that is true without this hypothesis seems a little hard.
What I thought was something like: $$\text{$f$ is integrable} \Rightarrow |\partial S| = 0,$$ where $|\partial S| = 0$ means that the boundary of $S$ has null measure.
Now, once $S = int ~S \cup \partial S$and this is a disjoint union,
$$\int_S f = \int_{int~S}f + \int_{\partial S}f = \int_{int~ S}f~ \text{once $|\partial S| = 0$}.$$
Is this right?
A:
Note that $S=C\cup D$, where $C$ are the points of continuity, and $D$ is $S \setminus C$. Our theorem on Riemann integrability assures that $C$ is Lebesgue measurable, and since $S$ is assumed to be, then so is $D$. Now let $C_i = int(S)\cap C$ and $D_i = int(S) \cap D$ (which again are measurable). Finally let $C_b = C \setminus C_i \subseteq \partial S$ and $D_b = D \setminus D_i \subseteq \partial S$. Note that all our sets are disjoint, and their union is $S$, furthermore $int(S) = C_i \cup D_i$.Then we can make the following calculation for $f$ Riemann measurable:
\begin{align*}
\int_S f d\mu &= \int_C f d\mu +\int_D fd\mu = \int_{C_i} fd \mu +\underbrace{\int_{D} f d\mu}_{=0}\\
&= \int_{C_i} f d\mu + \underbrace{\int_{D_i} f d\mu}_{=0} +\underbrace{\int_{D_b} fd\mu}_{=0} = \int_{C_i} f d\mu +\int_{D_i} f d \mu\\
&= \int_{int(S)} f d\mu.
\end{align*}
|
[
"stackoverflow",
"0008415334.txt"
] | Q:
App Engine - Subdomain
I have deployed an application on Google App Engine and I want to link a Subdomian to that application.
I currently have a domain that is linked to a "live" site. from Google documentation I understand that i need to set up my domain with Google Apps:
To serve your app on a custom domain, the domain must be set up with Google Apps
(Source)
What exactly that mean?
I've looked in Google documentation and could get a clear idea...
Does that will effected my "live" site in some way?
just to clarify, www.mydomain.com - points a site that i own and i want sub.mydomain.com to point to my Google application.
A:
You need to make a CNAME to forward to your app address.
Let's say your app address is https://yourapp.appspot.com, and you want sub.mydomain.com to forward to it, just do like below:
Please read THIS first, follow the steps until step 5. You'll need to type your mydomain.com in step 3, and type sub in step 5. After these, you'll some steps on how to Chang CNAME record, just follow:
set your host name to sub
Type: CNAME
IP address/host name: ghs.google.com.
Priority status: (whatever just make it's the number)
OK, and you'll visit your app by http://sub.mydomain.com, different hosting providers have different time to set it valid. :)
BTW, it'll not effect your "live" site in any way. As your main site use mydomain.com, and you just need sub.mydomain.com. What GAE said is that, if you want to set mydomain.com to your app, you need to set A type instead of CNAME type in your host. This domain hosting method includes more steps, you'll see GAE's doc that you found, and so it will effect your live site.
|
[
"stackoverflow",
"0001321779.txt"
] | Q:
Any VCARD generator class for Zend framework?
Hi guys I need a class to generate vcards - something that I can use with the Zend Framework - nothing too flashy. Thanks again...
A:
there is vcardphp on sourceforge.net (for php in general), should'nt be hard to make into a Zend module.
And also http://www.bitfolge.de/index.php?l=en&s=phpvcard.
I have used both for various projects.
|
[
"stackoverflow",
"0018207362.txt"
] | Q:
background image with horizontal scrolling
I have a background image in bottom right of the page.
when i compress the browser width, the background image is cropped at the left side. Means i can't browse the background image with the horizontal scroll bar.
I have below background properties.
background-image:url('Image.png');
background-size: 564px 282px;
background-attachment: fixed;
background-position: bottom right;
background-repeat: no-repeat;
Please let me know, what im missing here.
Thanks in advance
A:
No horizontal scrolling for images:
You need to add background-size css attribute to either contain, fit or 100%.
This will make your image to appear without horizontal scrolling.
For horizontal scrolling for images:
If you want scrolling, then you have to give a min-width and that width should be same as the background image width.
|
[
"math.stackexchange",
"0003103980.txt"
] | Q:
can mutual entropy be higher than joint entropy?
Let's assume I have three probability distributions A,B,C.
The entropy of each is 1.58, with joint entropy 1.58.
Calculating mutual entropy with formula I(A,B,C) = H(A)+H(B)+H(C)-J(A,B,C) results in 3.16.
How could this be explained? This means there is more common information than there is a capacity of a channel. Could you explain this?
A:
The mutual information $I(X;Y)$ (not "mutual entropy"; also, notice the semicolons, don't confuse them with commas) relates always two (perhaps multivariate) random variables.
$I(A;B;C)$ is a highly dubious extension of the concept of the "real" mutual information, which is not very meaningful, nor much used. For one thing, as you noted, it can be negative. See also here.
|
[
"rpg.stackexchange",
"0000157779.txt"
] | Q:
By RAW: Does a creature know that it is hidden?
When a creature attempts to Hide it makes a Stealth check, which is compared to the passive Perception of opposing creatures that may notice it, or a group check if there is more than one.
Does the creature attempting to Hide know whether or not is has successfully hidden?
If an opposing creature decides to take the Search action, making a Perception check to attempt to detect the hiding creature, does the hiding creature know if they have remained hidden?
Does the hiding creature know that the Search action has been taken?
This question is NOT about whether or not a player knows the result of their own roll. I did not ask if ingame characters know about gameplay mechanics or about the rolls of dice at all. It is about whether or not they know the result of checks, and whether they would reasonably be able to infer actions of other creatures.
A:
This is a matter of playstyle
The extent to which ludomechanical constructs-- such as ability scores, spell levels, hit points, and class levels-- are a part of the fiction is a matter of playstyle.
Some groups will have characters say things like, "Aw man, 12d6
damage from the fireball? That's a 7th level spell slot. We better
watch out for teleport; he probably knows that spell if he's got
slots that high."
Some groups will have characters say, "Alack and alarum! The flames of
this evil magus art so hot methinks he wields power great enough to
rend the very fabric of this world in twain-- we ought to expect that
he shall endeavor to do so and beat a cowardly retreat if we his
plans set awry."
Some groups will have players make their characters act like they
don't and shouldn't know that an enemy with a pointy hat and robes
and a staff not wearing any armor is more likely to cast spells than
a hulking dude in full plate with a tower shield in one hand and a
waraxe in the other.
Some groups won't even let players know how much damage they've taken
or how much hp they have left.
The rules favor to a moderate extent the frame that the players should be allowed to know everything their character's know and vice versa-- that's the position from with combat options are generally balanced, for example. But the game remains playable, if very different, when this paradigm is shifted one way or the other.
How does this apply to hiding?
Well, first of all, even if a player knows whether or not their PC is hidden-- or a DM knows whether or not a given NPC is hidden-- that doesn't necessarily mean that the creature knows that. We can't jump from definitely allowed out-of-character knowledge to definitely allowed in-character knowledge like that; that's not a valid inference. Instead, if we lack any explicit guidance as to in-character knowledge, we have to turn to our group's method of handling that sort of information. We do, in fact, lack that sort of explicit guidance with the stealth mechanics, including the 'hide' action, so this is, obviously, necessary.
However, there's more: the rules also do not say whether or not players know when their character is hidden. While ordinarily this would mean that players don't know that information-- you normally don't get to do stuff unless the rules say you can-- the rules very much assume that players do know that information: for example, players are expected to roll their attack rolls and if they have incomplete information about conditions potentially granting advantage or disadvantage, that doesn't work practically-- you have to tell them at least some of the times or roll for them at least some of the times and doing any of that part-way is very much outside the rules. Page 5 of the DMG does implicitly suggest it's normal for the DM to roll damage rolls the PCs make instead of having them do so, though that contradicts much of the PHB and the player-facing parts of the DMG (5e's rules aren't intended to be consistent or coherent as a whole), but nothing is said at any point about DMs making attack rolls for player characters.
The rules also do not say whether or not a DM knows if their NPCs are hidden-- that may seem inherent in their running of the game, but one could imagine an esoteric but RAW-compliant system wherein only the person controlling the being being hidden from knows whether the attempt was successful or not. Again, the rules very much seem to expect, even though there is no explicit text, that the DM should know what's going on-- for example the rules declare the DM to have responsibility for refereeing the rules.
So, then, the rules do not tell us whether or not a creature's controller knows when it has hidden successfully some, all, or none of the time, nor, having answered that question affirmatively, whether the creature itself knows that. No mechanism is provided for resolving this absence of rules except for the advice on page 34 of the DMG; the section titled "Play Style".
A:
Knowledge is often up to the DM to provide
The PHB (page 6) covers how actions are generally handled(emphasis mine):
The DM describes the environment. The DM tells the players where their adventurers are and what's around them…
The players describe what they want to do. […] the DM listens to every player and decides how to resolve those actions.
The DM narrates the results of the adventurers' actions.
In the case in question, we have a character who has said that they want to Hide to become unnoticed and explains how/where they will do so. The DM needs to decide if it's reasonable and if a roll is required (yes, it's so easy to hide, you're hidden - no, there is no way for you to hide, there is no attempt to be made.) The player makes the requested roll (most likely Stealth, but again this is up to the DM), and then the DM narrates the result.
It's really about the narration
So now you've got a situation where the DM has called for a roll and the player has made one. It's now up to the DM to describe what happens. If it's a 'failed' roll, maybe they describe noise being made, or some other environmental stimulus being triggered. Or that the player notices another creature noticing them. They can also choose to do none of the above and tell the player they believe they're hidden. It's all up to the DM and the table responding to the DM to determine what works best and is fun for everyone.
So in the case of a stealth attempt we are have an event where a player wants to hide. This is the action, the results of that action can be numerous and all are available as results (including being found or not being found.) This is in someways a Schroedinger's cat. WHen you declare your attempted action, it contains all possible results. Once the player rolls, the DM and the table see the result and the DM determines and narrates the result as they see fit. Some tables may like knowing, others may prefer not to. Both are perfectly acceptable as well as any option in between.
A:
This is not covered by the rules intentionally
Your question is very logical, and I guess it naturally comes from the following points:
The game rules define the game world
According to these rules, a creature can take the Hide action
After taking the Hide action, a creature can be or not be hidden
But does the creature know the outcome of its Hide action? It is a missing piece in the rules, so you've asked about it. Plain and simple, right? Why can this cause any misunderstanding and arguing?
Well, that's because the premises up above are not correct (or they are table dependent, strictly speaking). They suit the 3.5e or Pathfinder quite well, and are definitely true for a computer game, but they work poorly in the 5e paradigm. The Fifth edition tries to simplify rules and in the same time it moves to the older (2e AD&D-ish) paradigm, where the narrative truth was put ahead. You can read more about this paradigm in the A Quick Primer for Old School Gaming essay by Matthew Finch.
The rules do not define the game world
In the world a breastplate protects you because it is hard and sturdy, and it covers your vital organs. We, the players, use this simplified one-number abstraction only when we resolve a so-called "attack roll", in order to do it more easily. That does not mean the breastplate have have its "AC 14" somewhere.
The rules are not like the laws of physics applying to the game world. The rules is a DM's tool, which they can use to figure out an outcome of a situation. For more information, read "The Role of the Dice" chapter in the DMG. My point is — all the things you can read in the Player's Handbook do not encompass the whole game world. So in the game world creatures can (and will) hide because that's how they live, not because there is "the Hide action" in the PHB.
PHB gives you basic roleplaying guidelines and basic game mechanics, so you know what to expect from the DM. But it does not tell you what a DM should do, nor it describes any actual "laws" of the world. Instead, the game world is supposed to be vast and living, and you explore it, working with your DM through a conversation. For More information read PHB page 6 "How to play" and DMG page 9 "A World of Your Own".
You don't "take the Hide action" in order to hide
Well, that's a tricky one, so let's talk more about D&D history a bit. There is a reason why skill checks were removed in 5th edition.
In previous edition, players are supposed to say "I use X skill" when they wanted to achieve some goal. So you declared the mechanics and get the effect. Now you describe what do your character do in the first place, and then the DM might (or might not) use any game mechanics in order to resolve the outcome.
So you don't hide because you've taken the Hide action. The flow was reversed — now you take the Hide action because you're hiding, and you're hiding because, as a player (or a DM), you are describing the respective character actions. Things are more strict in combat though, but in general, "rules as written" does not mean "the only right thing" anymore — DMs are supposed to stick to the narrative truth, going with what's best for their story, not just "following the rules as strict as possible". That's why the rules are intentionally silent on many corner cases now.
"Hide" action in the rules does not actually describe hiding
The Hide action is a part of the "actions in combat" chapter. That does not mean you can not hide out of the combat. That means these particular mechanics matter in combat because of the action economy, so the action economy is the thing the rules description says about:
Hiding in combat should have benefits for attack in terms of mechanics; that's why you have Advantage
Hiding in combat is powerful because of the positioning, so it spends resources (it takes an action, unless you have a feature that allows you to use a bonus action)
Hiding in combat is also risky, so it's not automatic; that's why it requires us to roll dice
But these particular mechanics do not describe all the benefits from hiding. The rules intentionally do not say things like "enemy is (not) aware of you when you are hiding" because it's not a matter of mechanics now, it's a matter of the common sense, a current context and your narrative positioning (more on this later).
A creature is not either "hidden" or "not hidden"
"Hidden" is not a condition nor a boon a creature can have. Instead, "hidden" describes your narrative positioning. You can't be just "unseen and unheard", you are always unseen (or unheard) by somebody.
But your whole positioning means even more. Imagine you're a rogue searching through a manor, suddenly you hear a guard coming through the corridor. What do you do?
You freeze, staying still, making no noise, waiting for the guard to leave
You stand right behind the door, ready to stun an enemy with your sap
That nearby chest is empty, you get into that chest and close it, leaving a small slit to peek out
All three situations can be modeled with the same "Hide action" so they are identically in terms of mechanics, but they differ drastically in terms of the narrative positioning. It's a thing in 5e now, a good DM should take it into the consideration.
If rule do not cover this, how to understand, what's going on
So what do you do? You use the common sense. In the real world, do you know if you're not longer hidden? When someone notice you, no "eye" icon appears in front of you, neither you hear an alarm sound. Instead, you can (or can not) figure it out by the behavior of the creature searching for you. The same approach can be used in the 5e game.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.