qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
87,929 | I'm reading a paper on jet engines that repeatedly mentions the stagnation pressure and temperature. What does this mean? Is it the point where the jet engine stalls in performance/efficiency/thrust, etc?
I'm a bit confused. 99% of the information on stagnation pressure is the static pressure, or the about stagnation point, or pressure where fluid velocity is zero. | 2021/06/25 | [
"https://aviation.stackexchange.com/questions/87929",
"https://aviation.stackexchange.com",
"https://aviation.stackexchange.com/users/44452/"
] | [](https://i.stack.imgur.com/RtPh1.png)[Image source](https://www.researchgate.net/figure/Smoke-visualisation-and-flow-topology-of-the-airflow-around-a-cylinder_fig7_260045652)
Stagnation pressure is used as a synonym for total pressure. An object in airflow experiences pressure from the flow = dynamic pressure, indeed for incompressible flow proportional to the velocity squared.
In the pic above, on the right hand side, is an indication of the Stagnation Point. This is where the air streaming in does not flow around the cylinder but is stopped by the body contour. The flow stagnates, and all inflowing dynamic air pressure is converted into static pressure at this point.
Which is called the stagnation pressure. | The analytical formula for the stagnation pressure $p\_{st}$ is :
$$p\_{st} = p\_{\infty} + \frac{1}{2} \rho V^2$$
with $p\_∞$ static pressure, $\rho$ = air density, $V$ = air speed for incompressible flow.
The point where the fluid is at rest is the point where stagnation pressure = static pressure ($p\_{\infty} = p\_{st}$), because the kinetic energy of the fluid is 0.
For compressible flows you can calculate the ratio of Stagnation/Static pressure with the formula :
$$\frac{p\_{st}}{p\_∞} = {\left( 1 + \frac{\gamma - 1}{2}M^2\right)}^{\frac{\gamma}{\gamma - 1}} $$ , simply by replacing Mach=0 then you can see that the stagnation pressure = static.
Try understanding how pitot measurement for pressure works and try studying Anderson for Fundamental Aerodynamics.
Hope that helps |
25,688,287 | How can I execute a calculation in python (2.7) and capture the output in the variable 'results'?
**Input:**
```
let calculation = '(3*15)/5'
let formatting = '\\%2d'
let grouping = '0'
exe "python -c \"import math, locale; locale.format(formatting, calculation, grouping)\""
```
and capture the output in a variable `results`
**Output:**
results = '9'
ps:
Is there also a possibility in python to wrap the first part of my calculation, something like the eval() function in vim?
p.e.
```
let command = 'python -c \"import math, locale\"'
exe "eval(command); locale.format(formatting, calculation, grouping)"
``` | 2014/09/05 | [
"https://Stackoverflow.com/questions/25688287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/662967/"
] | Hmm… `:let foo = (3*15)/15`.
Anyway, you can capture the output of an external command with `:let foo = system('mycommand')`:
```
:let foo = system("python -c 'print (15*3)/5'")
```
It's up to you to put the string together. | I ever wrote a script to do number calculation in vim. It supports three expression evaluation engines: `GNU bc, vimscript and python`.
It is called `HowMuch` : <https://github.com/sk1418/HowMuch>
For the python part, you could check here:
<https://github.com/sk1418/HowMuch/blob/master/autoload/HowMuch.vim#L285>
hope it helps. |
59,287,801 | need help
I have a task count of 250.
I want all these tasks to be done via a fixed no of threads. ex 10
so, I want to feed each thread one task
```
t1 =1
t2=2
.
.
.
```
currently I have written the code in such a way that, among those 10 threads each thread picks one task.
and I will wait till all the 10 threads are done using the `thread.join()`.and then again create 10 threads and feed each thread one task.
### Problem:
Although some of the threads are finished performing the task. I need to still wait for other threads to complete.
I want to maintain the thread count as 10 through . That is if among 10 threads if one thread finished the task, it can pick another task and similarly others.
any solution?
### my Code:
```java
for(int i=0;i<finData.size();i++){
ArrayList<Thread> AllThreads = new ArrayList<>();
if(i+10 <= finData.size()){
p=i+10;
}else{
p=i+10-finData.size();
}
for(int k=i;k<p;k++){
FeeConfigCheck = new Thread(new FeeConfigCheck(finData.get(k)));
AllThreads.add(FeeConfigCheck);
FeeConfigCheck.start();
Thread.sleep(100);
}
for(int h=0;h<AllThreads.size();h++){
AllThreads.get(h).join();
}
if(p<10){
System.out.println("Pointer----------------"+i);
break;
}
i=p;
System.out.println("Pointer----------------"+i);
}
``` | 2019/12/11 | [
"https://Stackoverflow.com/questions/59287801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12518808/"
] | You're reinventing the wheel; this is not neccessary. Java already contains functionality to have a fixed number of threads plus a number of tasks, and then having this fixed number of threads process all the tasks: [Executors](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/concurrent/Executors.html)
```
ExecutorService pool = Executors.newFixedThreadPool(10);
for (int k = i; k < p; k++) {
Runnable r = new FooConfigCheck(finData.get(k));
pool.submit(r);
}
pool.shutdown();
while (!pool.awaitTermination(1000, TimeUnit.SECONDS)) ;
```
That's all you have to do here.
See the javadoc of these classes for the various things you can ask it; how many tasks are in the queue is something you can ask, if you need that information.
EDIT: Added a call to shutdown. | ```
ExecutorService pool = Executors.newFixedThreadPool(20);
int count=0;
while(count<finData.size()){
if (pool instanceof ThreadPoolExecutor) {
if(((ThreadPoolExecutor) pool).getActiveCount()<20){
System.out.println("Pointer -----"+count);
Runnable r = new FeeConfigCheck(finData.get(count));
pool.submit(r);
count++;
Thread.sleep(500);
}
}
}
pool.shutdown();
while (!pool.awaitTermination(1000, TimeUnit.SECONDS)) ;
```
This Worked for me. The pointer was keep on incrementing even when all threads are busy. So i used the getActiveCount() to know the number of active threads. this way i was able to feed the thread whenever it completed its task.Thanks all for the help. :) |
5,279,503 | Looking for some help with my bash script. I am trying to write this shell script to do the following:
1. find files in a dir named:
`server1-date.done`
`server2-date.done`
`server3-date.done`
`...`
`server10-date.done`
2. print to a `listA`
3. find files in a dir (\*.gz) and print to a `listB`
4. if `listA` has a count of `10` (basically found 10 `.done` files), then
proceed with the moving the files in `listB` to its new directory
5. after moving the files from `listB`, then remove the old directory which is similarly named (`server1-date`, `server2-date`, ...) and the .done files.
So far, I have this in the works. I can't get the condition for the `if` section working. I don't think I coded that correctly. Any code suggestions, improvements, etc would be appreciated. Thanks.
```
#Directories
GZDIR=/mydumps/mytest
FINALDIR=/mydumps/mytest/final
FLGDIR=/backup/mytest/flags
export GZDIR FINALDIR FLGDIR
#lists
FLGLIST="/mydumps/mytest/lists/userflgs.lst"
GZLIST="/mydumps/mytest/lists/gzfiles.lst"
export FLGLIST GZLIST
#Find files
find $FLGDIR -name \*.done -print > $FLGLIST
find $GZDIR -name \*.gz -print > $GZLIST
#Get need all (10) flags found before we do the move
FLG_VAL =`cat $FLGLIST | wc -l`
export $FLG_VAL
if [ "$FLG_VAL" = "10" ]; then
for FILE in $GZLIST
do
echo "mv $GZLIST $FINALDIR" 2>&1
for FLAG in $FLGLIST
do
echo "rmdir -f $FLAG" 2>&1
done
done
else
echo "Cannot move file" 2>&1
exit 0
fi
``` | 2011/03/11 | [
"https://Stackoverflow.com/questions/5279503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/374916/"
] | First of all, I really recommend that you as the default approach always [test for exceptions](http://dl.dropbox.com/u/20930447/index.html), and do not include the "normal" case inside a test unless that is necessary.
```
...
FLG_VAL=`wc -l < $FLGLIST` # no need for cat, and no space before '='
export $FLG_VAL
if [ "$FLG_VAL" != "10" ]; then
echo "Cannot move file" 2>&1
exit 0
fi
for FILE in $GZLIST
do
echo "mv $GZLIST $FINALDIR" 2>&1
for FLAG in $FLGLIST
do
echo "rmdir -f $FLAG" 2>&1
done
done
```
See how much easier the code is to read now that the error check is extracted and stands by itself? | ```
FLG_VAL =`cat $FLGLIST | wc -l`
```
Should be:
```
FLG_VAL=`cat $FLGLIST | wc -l`
``` |
5,279,503 | Looking for some help with my bash script. I am trying to write this shell script to do the following:
1. find files in a dir named:
`server1-date.done`
`server2-date.done`
`server3-date.done`
`...`
`server10-date.done`
2. print to a `listA`
3. find files in a dir (\*.gz) and print to a `listB`
4. if `listA` has a count of `10` (basically found 10 `.done` files), then
proceed with the moving the files in `listB` to its new directory
5. after moving the files from `listB`, then remove the old directory which is similarly named (`server1-date`, `server2-date`, ...) and the .done files.
So far, I have this in the works. I can't get the condition for the `if` section working. I don't think I coded that correctly. Any code suggestions, improvements, etc would be appreciated. Thanks.
```
#Directories
GZDIR=/mydumps/mytest
FINALDIR=/mydumps/mytest/final
FLGDIR=/backup/mytest/flags
export GZDIR FINALDIR FLGDIR
#lists
FLGLIST="/mydumps/mytest/lists/userflgs.lst"
GZLIST="/mydumps/mytest/lists/gzfiles.lst"
export FLGLIST GZLIST
#Find files
find $FLGDIR -name \*.done -print > $FLGLIST
find $GZDIR -name \*.gz -print > $GZLIST
#Get need all (10) flags found before we do the move
FLG_VAL =`cat $FLGLIST | wc -l`
export $FLG_VAL
if [ "$FLG_VAL" = "10" ]; then
for FILE in $GZLIST
do
echo "mv $GZLIST $FINALDIR" 2>&1
for FLAG in $FLGLIST
do
echo "rmdir -f $FLAG" 2>&1
done
done
else
echo "Cannot move file" 2>&1
exit 0
fi
``` | 2011/03/11 | [
"https://Stackoverflow.com/questions/5279503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/374916/"
] | I do not know if this will work, but it will fix all the obvious problems:
```
#!/bin/sh
#Directories
GZDIR=/mydumps/mytest
FINALDIR=/mydumps/mytest/final
FLGDIR=/backup/mytest/flags
export GZDIR FINALDIR FLGDIR
#lists
FLGLIST="/mydumps/mytest/lists/userflgs.lst"
GZLIST="/mydumps/mytest/lists/gzfiles.lst"
#Find files
find "$FLGDIR" -name '*.done' -print > "$FLGLIST"
find "$GZDIR" -name '*.gz' -print > "$GZLIST"
#Get need all (10) flags found before we do the move
FLG_VAL=$(wc -l <"$FLGLIST") # Always prefer $( ... ) to backticks.
if [ "$FLG_VAL" -ge 10 ]; then
for FILE in $(cat "$GZLIST")
do
echo "mv $FILE $FINALDIR" 2>&1
done
for FLAG in $(cat "$FLGLIST")
do
echo "rmdir -f $FLAG" 2>&1
done
else
echo "Cannot move file" 2>&1
exit 0
fi
``` | ```
FLG_VAL =`cat $FLGLIST | wc -l`
```
Should be:
```
FLG_VAL=`cat $FLGLIST | wc -l`
``` |
5,279,503 | Looking for some help with my bash script. I am trying to write this shell script to do the following:
1. find files in a dir named:
`server1-date.done`
`server2-date.done`
`server3-date.done`
`...`
`server10-date.done`
2. print to a `listA`
3. find files in a dir (\*.gz) and print to a `listB`
4. if `listA` has a count of `10` (basically found 10 `.done` files), then
proceed with the moving the files in `listB` to its new directory
5. after moving the files from `listB`, then remove the old directory which is similarly named (`server1-date`, `server2-date`, ...) and the .done files.
So far, I have this in the works. I can't get the condition for the `if` section working. I don't think I coded that correctly. Any code suggestions, improvements, etc would be appreciated. Thanks.
```
#Directories
GZDIR=/mydumps/mytest
FINALDIR=/mydumps/mytest/final
FLGDIR=/backup/mytest/flags
export GZDIR FINALDIR FLGDIR
#lists
FLGLIST="/mydumps/mytest/lists/userflgs.lst"
GZLIST="/mydumps/mytest/lists/gzfiles.lst"
export FLGLIST GZLIST
#Find files
find $FLGDIR -name \*.done -print > $FLGLIST
find $GZDIR -name \*.gz -print > $GZLIST
#Get need all (10) flags found before we do the move
FLG_VAL =`cat $FLGLIST | wc -l`
export $FLG_VAL
if [ "$FLG_VAL" = "10" ]; then
for FILE in $GZLIST
do
echo "mv $GZLIST $FINALDIR" 2>&1
for FLAG in $FLGLIST
do
echo "rmdir -f $FLAG" 2>&1
done
done
else
echo "Cannot move file" 2>&1
exit 0
fi
``` | 2011/03/11 | [
"https://Stackoverflow.com/questions/5279503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/374916/"
] | I do not know if this will work, but it will fix all the obvious problems:
```
#!/bin/sh
#Directories
GZDIR=/mydumps/mytest
FINALDIR=/mydumps/mytest/final
FLGDIR=/backup/mytest/flags
export GZDIR FINALDIR FLGDIR
#lists
FLGLIST="/mydumps/mytest/lists/userflgs.lst"
GZLIST="/mydumps/mytest/lists/gzfiles.lst"
#Find files
find "$FLGDIR" -name '*.done' -print > "$FLGLIST"
find "$GZDIR" -name '*.gz' -print > "$GZLIST"
#Get need all (10) flags found before we do the move
FLG_VAL=$(wc -l <"$FLGLIST") # Always prefer $( ... ) to backticks.
if [ "$FLG_VAL" -ge 10 ]; then
for FILE in $(cat "$GZLIST")
do
echo "mv $FILE $FINALDIR" 2>&1
done
for FLAG in $(cat "$FLGLIST")
do
echo "rmdir -f $FLAG" 2>&1
done
else
echo "Cannot move file" 2>&1
exit 0
fi
``` | First of all, I really recommend that you as the default approach always [test for exceptions](http://dl.dropbox.com/u/20930447/index.html), and do not include the "normal" case inside a test unless that is necessary.
```
...
FLG_VAL=`wc -l < $FLGLIST` # no need for cat, and no space before '='
export $FLG_VAL
if [ "$FLG_VAL" != "10" ]; then
echo "Cannot move file" 2>&1
exit 0
fi
for FILE in $GZLIST
do
echo "mv $GZLIST $FINALDIR" 2>&1
for FLAG in $FLGLIST
do
echo "rmdir -f $FLAG" 2>&1
done
done
```
See how much easier the code is to read now that the error check is extracted and stands by itself? |
16,781 | I am trying to design a filter whose magnitude is the same as that of a given signal. The given signal is wind turbine noise, so it has significant low-frequency content. After designing the filter, I want to filter white Gaussian noise so as to create a model of wind turbine noise. The two signals, that is the original and the filtered noise should sound similar.
I am using arbitrary magnitude filter design in Matlab for that (FIR, Order: 900, Single rate, 1-band, response specified by amplitudes, Sample rate 44100 Hz, Design method: firls). The problem is that, although I design the filter using the values from the original signal's magnitude, the filter magnitude fails to follow the magnitude at higher frequencies. Could you please help me with that?
The idea is that I am using a polynomial curve, to fit the shape of the spectrum of the original sound. Then, I filter the magnitude of the generated noise, by multiplying the extracted polynomial curve with the generated noise magnitude. Finally, after calculating the new magnitude and phase, I get back to the time domain.
```
[x,fs] = audioread('cotton_0115-0145.wav'); % original noise sample
x = x(:,1); % extract one channel
x = x.';
N = length (x);
% fft of original signal
Y = fft(x,N)/N;
fy = (0:N-1)'*fs/N;
% half-bandwidth selection for original signal
mag = abs(Y(1:N/2));
fmag = fy(1:N/2);
% polynomial fitting
degreesOfFreedom=40;
tempMag=20*log10(mag)'; % desired magnitude in dB
tempFmag=fmag;
figure(1)
plot(tempFmag,tempMag,'b');
title('Spectrum of original signal-Polynomial fitting')
xlabel('Frequency (Hz)');
ylabel('20log10(abs(fft(x)))');
axis([tempFmag(1) tempFmag(end) min(tempMag) 0]);
hold on
p = [];
for i=1:4
p=polyfit(tempFmag,tempMag,degreesOfFreedom);
pmag=polyval(p,tempFmag);
plot(tempFmag,pmag,'r');
pause
above=pmag<tempMag;
abovemag=tempMag(above);
abovefmag=tempFmag(above);
tempMag=abovemag;
tempFmag=abovefmag;
end
hold on
legend('signal magnitude','polynomial');
%
loc1 = find(fmag == 0);
loc2 = find(fmag == 22050);
Nmag = length(mag);
M=((Nmag-1)*max(tempFmag))/(tempFmag(end)-tempFmag(1));
freqFinal=tempFmag(1):max(tempFmag)/M:max(tempFmag);
freqFinal=tempFmag(1):max(tempFmag)/length(mag):max(tempFmag);
magnitudesFinal=polyval(p,freqFinal);
figure(2)
plot(fmag,20*log10(mag)');
hold on;
plot(freqFinal,magnitudesFinal,'g');
title('Spectrum of original signal-Choice of polynomial curve')
xlabel('Frequency (Hz)');
ylabel('abs(fft(x))');
axis([freqFinal(1) freqFinal(end) min(magnitudesFinal) max(magnitudesFinal)]);
%%
% noise generation
Nn = N;
noise = wgn(1,Nn,0);
noise = noise/(max(abs(noise)));
Ynoise = fft(noise,Nn)/Nn;
fn = (0:Nn-1)'*fs/Nn;
% polynomial for whole f range
newmagA = 10.^(magnitudesFinal/20);
newmagB = fliplr(newmagA);
newmagB(end+1) = newmagB(end);
newmag = [newmagA newmagB];
%filtering
Ynoisenew = newmag .* Ynoise;
figure(3)
magnoise = 20*log10(abs(Ynoisenew(1:Nn/2)));
fnoise = fn(1:Nn/2);
plot(fnoise, magnoise);
% magnitude and phase of filtered noise
magn = abs(Ynoisenew);
phn = unwrap(angle(Ynoisenew));
% Back to Time domain
sig_new=real(ifft(magn.*exp(1i*phn)));
figure(4)
sig_new = sig_new / max(abs(sig_new));
plot(t, sig_new);
Ysignew = fft(sig_new,Nn)/Nn;
fn = (0:Nn-1)'*fs/Nn;
figure(5); plot(fn(1:Nn/2),20*log10(abs(Ysignew(1:Nn/2))));
``` | 2014/06/10 | [
"https://dsp.stackexchange.com/questions/16781",
"https://dsp.stackexchange.com",
"https://dsp.stackexchange.com/users/10166/"
] | if you are only interested in designing a signal representing the wind turbine noise, you could just generate it from your magnitude. E.g., with your magnitude $A$ over frequency $f$ you can generate a random phase $\phi$ for each frequency and over a time $t$ and then add all together. Here a small code for illustration (I tried to use your varibles. However you need to check orientation etc.):
```
phi = rand(size(fmag))*2*pi;
x = (mag*sin(2*pi*fmag*t+repmat(phi,1,N)));
```
Hope this helps. | Does [*remez()*](https://octave.sourceforge.io/signal/function/remez.html) help you? Matlab has a similar one. This function receives some points of the spectrum response (PSD) and returns the coefficients of a filter with the desired response. |
33,554,536 | I want to create a string array between From and To input.
like From = 2000 To = 2003
I want to create a string[] as below:
>
>
> ```
> string[] arrayYear = new string[]{"2000","2001","2002","2003"};
>
> ```
>
>
Is there any easy way of building it dynamically for any range of year?
Please suggest me. | 2015/11/05 | [
"https://Stackoverflow.com/questions/33554536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1893874/"
] | You can use `Enumerable.Range`
```
int startYear = 2000, endYear = 2004;
string[] arrayYear = Enumerable.Range(startYear, endYear - startYear + 1).Select(i => i.ToString()).ToArray();
``` | You can use `Enumerable.Range()`
```
var arrayList = Enumerable.Range(2000, 2015-2000+1).ToList();
string[] arrayYear = arrayList.Select(i => i.ToString()).ToArray();
``` |
35,840 | I am using Cucumber through IntelliJ and am working on fixing a broken test. I was wondering when debugging, is there a way to save the state of the system up to a certain step in the feature file, if they all pass. For example, take this exaggerated example below
```
Given I am a New User
And There is an Event on a certain date
When I log in
And Go to the Events page
And I select the Event
And I go to the Payments Page
And I attempt to pay with credit card
(cont)
```
In the example above, if I am checking why credit card payments were failing in the test, I'd have to rerun the test loads of times to get the system into the state I wanted it in (user, event created). Is there a way to save the state of the system once a step passes? So, therefore, running the test above and it failing on the last step, means that if I run it again it will restore the state of the system based on a snapshot of how it was after the last step and continue to run from the next step. Example...
```
Given I am a New User
(snapshot of the system with a new user is recorded)
And There is an Event on a certain date
(snapshot of the system with a new user and event is recorded)
When I log in
(snapshot of the system with a new user and event is recorded and the user is logged in)
```
I worked in a place that used an in-house test runner and they were able to do it, just wondering if this is a feature that is available? | 2018/09/28 | [
"https://sqa.stackexchange.com/questions/35840",
"https://sqa.stackexchange.com",
"https://sqa.stackexchange.com/users/29912/"
] | Cucumber executes the step definitions glue that you provide it with, so it can't in any way control the state of your system. If you need to save snapshots of the system after each step, call a function that would do that for you at the end of every step. | ### Why don't use application to save state of data?
In similar situations, we saved the data state in the application itself as the automation cannot save the application state in the tests.
As we were working on the orders so we could save the order just before the payment. So that we can just the pick up the order from the saved state(based on order ID) and the test can execute the relevant steps only by commenting out the initial test steps. |
45,767 | Every now and then, I find myself reading papers/text talking about how *this* equation is a constraint but *that* equation is an equation of motion which satisfies *this* constraint.
For example, in the Hamiltonian formulation of Maxwell's theory, Gauss' law $\nabla\cdot\mathbf{E}=0$ is a constraint, whereas $\partial\_\mu F^{\mu\nu}=0$ is an equation of motion. But why then isn't $\partial\_\mu j^\mu=0$, the charge-conservation/continuity equation, called an equation of motion. Instead it is just a 'conservation law'.
Maybe first-order differentials aren't allowed to be equations of motion? Then what of the Dirac equation $(i\gamma^\mu\partial\_\mu-m)\psi=0$? This is a first-order differential, isn't it? Or perhaps when there is an $i$, all bets are off...
So, what counts as an equation of motion, and what doesn't?
How can I tell if I am looking at a constraint? or some conservation law? | 2012/12/03 | [
"https://physics.stackexchange.com/questions/45767",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/10456/"
] | In general, a dynamical equation of motion or evolution equation is a (hyperbolic) second order in time differential equation. They determine the evolution of the system.
$\partial\_{\mu}F^{i\mu}$ is a dynamical equation.
However, a constraint is a condition that must be verified at *every* time and, in particular, the initial conditions have to verify the constraints. Since equations of motion are of order two in time, constraints have to be at most order one.
The Gauss law $\partial\_{\mu}F^{0\mu}$ is a constraint because it only involves a first derivative in time in configuration space, i.e., when $\bf E$ it is expressed in function of $A\_0$ and $\bf A$. Furthermore, the gauss law is the generator of gauge transformations. In the quantum theory, only states which are annihilated by the gauss law are physical states.
Both dynamical equations and constraints may be called equations of motion or Euler-Lagrange equations of a given action functional. Or, one may keep the term equation of motion for dynamical equations. It is a matter of semantic. The important distinction is between constraints and evolution equations.
Conservation laws follow mainly from symmetries and from Noether theorem. Often but not always, equations of motion follow from conservation laws. Whether one considerers one more fundamental is a matter of personal taste.
Dirac equation relates several components of a Dirac spinor. Each component verifies the Klein-Gordon equation which is an evolution equation of order two. | In field theory, a conservation law just states that some quantity is conserved: if $\partial\_\mu \, \star = 0$ where $\star$ is a vector or a tensor, you can associate a conserved charge etc. - you know the spiel I guess.
Constraints are something you impose by hand (or by experiment).
Finally, equations of motion are dynamical equations that follow from the Euler-Lagrange equation. Both the Dirac equation and $\partial^\mu F\_{\mu \nu} = 0$ satisfy that criterion. [However, if you choose a gauge, it becomes much more clear that you're dealing with a PDE for the field $A\_\mu$, such as $\square A\_\mu = 0.$] Also note that both of them involve $\partial\_t$ or $\partial\_t^2$. Note that $\nabla \cdot \mathbf{E}$ only involves spatial derivatives, so it gives no dynamics.
In your example, $\partial^\mu j\_\mu = 0$ is a classical conservation law that doesn't describe how some microscopic quantity evolves in time - you don't derive it from Euler-Lagrange. |
45,767 | Every now and then, I find myself reading papers/text talking about how *this* equation is a constraint but *that* equation is an equation of motion which satisfies *this* constraint.
For example, in the Hamiltonian formulation of Maxwell's theory, Gauss' law $\nabla\cdot\mathbf{E}=0$ is a constraint, whereas $\partial\_\mu F^{\mu\nu}=0$ is an equation of motion. But why then isn't $\partial\_\mu j^\mu=0$, the charge-conservation/continuity equation, called an equation of motion. Instead it is just a 'conservation law'.
Maybe first-order differentials aren't allowed to be equations of motion? Then what of the Dirac equation $(i\gamma^\mu\partial\_\mu-m)\psi=0$? This is a first-order differential, isn't it? Or perhaps when there is an $i$, all bets are off...
So, what counts as an equation of motion, and what doesn't?
How can I tell if I am looking at a constraint? or some conservation law? | 2012/12/03 | [
"https://physics.stackexchange.com/questions/45767",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/10456/"
] | An equation of motion is a (system of) equation for the basic observables of a system involving a time derivative, for which some initial-value problem is well-posed.
Thus a continuity equation is normally not an equation of motion, though it can be part of one, if currents are basic fields. | In field theory, a conservation law just states that some quantity is conserved: if $\partial\_\mu \, \star = 0$ where $\star$ is a vector or a tensor, you can associate a conserved charge etc. - you know the spiel I guess.
Constraints are something you impose by hand (or by experiment).
Finally, equations of motion are dynamical equations that follow from the Euler-Lagrange equation. Both the Dirac equation and $\partial^\mu F\_{\mu \nu} = 0$ satisfy that criterion. [However, if you choose a gauge, it becomes much more clear that you're dealing with a PDE for the field $A\_\mu$, such as $\square A\_\mu = 0.$] Also note that both of them involve $\partial\_t$ or $\partial\_t^2$. Note that $\nabla \cdot \mathbf{E}$ only involves spatial derivatives, so it gives no dynamics.
In your example, $\partial^\mu j\_\mu = 0$ is a classical conservation law that doesn't describe how some microscopic quantity evolves in time - you don't derive it from Euler-Lagrange. |
45,767 | Every now and then, I find myself reading papers/text talking about how *this* equation is a constraint but *that* equation is an equation of motion which satisfies *this* constraint.
For example, in the Hamiltonian formulation of Maxwell's theory, Gauss' law $\nabla\cdot\mathbf{E}=0$ is a constraint, whereas $\partial\_\mu F^{\mu\nu}=0$ is an equation of motion. But why then isn't $\partial\_\mu j^\mu=0$, the charge-conservation/continuity equation, called an equation of motion. Instead it is just a 'conservation law'.
Maybe first-order differentials aren't allowed to be equations of motion? Then what of the Dirac equation $(i\gamma^\mu\partial\_\mu-m)\psi=0$? This is a first-order differential, isn't it? Or perhaps when there is an $i$, all bets are off...
So, what counts as an equation of motion, and what doesn't?
How can I tell if I am looking at a constraint? or some conservation law? | 2012/12/03 | [
"https://physics.stackexchange.com/questions/45767",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/10456/"
] | In general, a dynamical equation of motion or evolution equation is a (hyperbolic) second order in time differential equation. They determine the evolution of the system.
$\partial\_{\mu}F^{i\mu}$ is a dynamical equation.
However, a constraint is a condition that must be verified at *every* time and, in particular, the initial conditions have to verify the constraints. Since equations of motion are of order two in time, constraints have to be at most order one.
The Gauss law $\partial\_{\mu}F^{0\mu}$ is a constraint because it only involves a first derivative in time in configuration space, i.e., when $\bf E$ it is expressed in function of $A\_0$ and $\bf A$. Furthermore, the gauss law is the generator of gauge transformations. In the quantum theory, only states which are annihilated by the gauss law are physical states.
Both dynamical equations and constraints may be called equations of motion or Euler-Lagrange equations of a given action functional. Or, one may keep the term equation of motion for dynamical equations. It is a matter of semantic. The important distinction is between constraints and evolution equations.
Conservation laws follow mainly from symmetries and from Noether theorem. Often but not always, equations of motion follow from conservation laws. Whether one considerers one more fundamental is a matter of personal taste.
Dirac equation relates several components of a Dirac spinor. Each component verifies the Klein-Gordon equation which is an evolution equation of order two. | OP wrote(v2):
>
> *What makes an equation an 'equation of motion'?*
>
>
>
As David Zaslavsky mentions in a comment, in full generality, there isn't an exact definition. Loosely speaking, [equations of motion](http://en.wikipedia.org/wiki/Equations_of_motion) are [evolution equations](http://www.encyclopediaofmath.org/index.php/Evolution_equation), with which the dynamical variables' future (and past) behavior can be determined.
However, if a theory has an [action principle](http://en.wikipedia.org/wiki/Principle_of_least_action), then there exists a precedent within the physics community, see e.g. Ref. 1. Then only the [Euler-Lagrange equations](http://en.wikipedia.org/wiki/Euler%E2%80%93Lagrange_equation) are traditionally referred to as 'equations of motion', whether or not they are dynamical equations (i.e. contain time derivatives) or constraints (i.e. do not contain time derivatives).
References:
1. M. Henneaux and C. Teitelboim, *Quantization of Gauge Systems,* 1994. |
45,767 | Every now and then, I find myself reading papers/text talking about how *this* equation is a constraint but *that* equation is an equation of motion which satisfies *this* constraint.
For example, in the Hamiltonian formulation of Maxwell's theory, Gauss' law $\nabla\cdot\mathbf{E}=0$ is a constraint, whereas $\partial\_\mu F^{\mu\nu}=0$ is an equation of motion. But why then isn't $\partial\_\mu j^\mu=0$, the charge-conservation/continuity equation, called an equation of motion. Instead it is just a 'conservation law'.
Maybe first-order differentials aren't allowed to be equations of motion? Then what of the Dirac equation $(i\gamma^\mu\partial\_\mu-m)\psi=0$? This is a first-order differential, isn't it? Or perhaps when there is an $i$, all bets are off...
So, what counts as an equation of motion, and what doesn't?
How can I tell if I am looking at a constraint? or some conservation law? | 2012/12/03 | [
"https://physics.stackexchange.com/questions/45767",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/10456/"
] | An equation of motion is a (system of) equation for the basic observables of a system involving a time derivative, for which some initial-value problem is well-posed.
Thus a continuity equation is normally not an equation of motion, though it can be part of one, if currents are basic fields. | OP wrote(v2):
>
> *What makes an equation an 'equation of motion'?*
>
>
>
As David Zaslavsky mentions in a comment, in full generality, there isn't an exact definition. Loosely speaking, [equations of motion](http://en.wikipedia.org/wiki/Equations_of_motion) are [evolution equations](http://www.encyclopediaofmath.org/index.php/Evolution_equation), with which the dynamical variables' future (and past) behavior can be determined.
However, if a theory has an [action principle](http://en.wikipedia.org/wiki/Principle_of_least_action), then there exists a precedent within the physics community, see e.g. Ref. 1. Then only the [Euler-Lagrange equations](http://en.wikipedia.org/wiki/Euler%E2%80%93Lagrange_equation) are traditionally referred to as 'equations of motion', whether or not they are dynamical equations (i.e. contain time derivatives) or constraints (i.e. do not contain time derivatives).
References:
1. M. Henneaux and C. Teitelboim, *Quantization of Gauge Systems,* 1994. |
17,228 | I'm working with the following op-amps:
LM308AN
LM358P
UA741CP
I want to make a small box that will control the power to any string of christmas lights based off of music that is playing. I would like it to pulse with the base. I want the input to be the signal from the headphone jack of my computer and I want the output to be something that would operate any light that could be plugged into a wall outlet (120VAC?). | 2011/07/22 | [
"https://electronics.stackexchange.com/questions/17228",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/5100/"
] | Sometimes, simply stating what you're trying to accomplish is better than asking the question you *think* you want to ask. This could very well be the case here. So, indulge me as I try to restate your situation and provide some sort of answer.
You have a headphone jack with some music on it, and you want that music to control some lights. You probably want the lights to blink or pulse with the music. Right?
This type of device is called a [Light Organ](http://en.wikipedia.org/wiki/Light_organ). There are many forms of light organs, but I assure you that none of them use an op-amp driving a relay. There are several reasons for this:
1. Relays don't operate well from an audio signal. They really want a signal that stays on or off for a while and doesn't just oscillate like an audio signal does.
2. Relays can't dim a light. They can turn one on or off. Not so good at dimming.
3. Relays would make a lot of noise, chattering away with the music. Not a pleasant sound.
I would recommend that you Google for "Light Organ". When I did, I came up with 65 million pages. Some of them are selling completed units, some have kits, and some have schematics.
I hope that helps! | **\* See important addition at end \***
You have not provided enough information to allow a good answer. Provide more information and I'll upgrade this answer progressively.
You don't explain what you are trying to do. Do you you want the relay to operate on sound peaks, or when sound is present at all, or to latch on when sound is detected , or ... . You **MUST** provide a clear explanation of your actual requirement.
Saying that you had the '308 working and that now it isn't is like saying that "My car was running but now it is broken, what's wrong with it?"
However:
* The LM308 is a nice opamp but far better than is needed here.
* The LM741 is an OK opamp but has characteristics that will make it VERY hard for you to use here.
* The LM358P is just what you want - once we know what it is that you want :-)
There is a 95% chance that we can tell you how to do what you want using an LM358 once you give us enough details.
What are the relay's voltage and current ratings? They should be marked on it. Maybe also coil resistance, brand, model etc. The more we know the better.
Help us to help you - at present your question is unanswerable.
An explanation of what you are trying to achieve is still needed.
[A catalog of the D2w203F and similar relays is here](http://www.crydom.com/en/Tech/crydom_us.pdf)
and [the datasheet for the D2W203F relay is here](http://www.crydom.com/en/products/catalog/d_2w.pdf)
This is a somewhat expensive SSR ("Solid State Relay") with 3-32 VDC control input **BUT** AC output using an internal TRIAC. It's rated for switching from 24VAC to 280 VAC at 0.06 to 3 Amps. It is not suitable for controlling DC.
It could control AC powered Christmas tree lights either by mains switching or at low voltage. The 2A rating should not be exceeded.
This relay is made only for on/off operation. It may be able to be used to
modulate" the lights in time with the music, if that is the aim BUT the TRIAC switch will always turn on for at least half an AC cycle so use as a "color organ" would be limited.
Tell us what you want and we'll tell you what you need. :-) |
7,809,215 | I have a project of business objects and a data layer that could potentially be implemented in multiple interfaces (web site, web services, console app, etc).
My question deals with how to properly implement caching in the methods dealing with data retrieval. I'll be using SqlCacheDependency to determine when the cached objects need to be expired, but I'm unsure of the best way of implementing the cache itself:
If the library is being used for a web project, I'd like to use HttpRuntime.Cache; however, I'm guessing that would be an issue for console apps.
What is the best way of implementing caching in your data layer for a .Net project when allowing for multiple types of interfaces like this? | 2011/10/18 | [
"https://Stackoverflow.com/questions/7809215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30006/"
] | You can use "-sync y" on your qsub to cause the qsub to wait until the job(s) are finished. | Jenkins allows for you to submit the results of a build using a web based API. I currently use this to monitor a job remotely for a grid at my orginization. If you have the ability to perform a web post to the jenkins server you could use the below script to accomplish the job.
```
#!/bin/bash
MESSAGE="Some message about job success"
RUNTIME="Some calculation to estimate runtime"
USERNAME="userNameForJenkinsLogin"
PASSWORD="passwordForJenkinsLogin"
JENKINS_HOST="URLToJenkins"
TEST_NAME="Name of Test"
curl -i -X post -d "<run><log>$MESSAGE</log><result>0</result><duration>$RUNTIME</duration></run>" http://$USERNAME:$PASSWORD@$JENKINS_HOST/jenkins/job/$TEST_NAME/postBuildResult
``` |
7,809,215 | I have a project of business objects and a data layer that could potentially be implemented in multiple interfaces (web site, web services, console app, etc).
My question deals with how to properly implement caching in the methods dealing with data retrieval. I'll be using SqlCacheDependency to determine when the cached objects need to be expired, but I'm unsure of the best way of implementing the cache itself:
If the library is being used for a web project, I'd like to use HttpRuntime.Cache; however, I'm guessing that would be an issue for console apps.
What is the best way of implementing caching in your data layer for a .Net project when allowing for multiple types of interfaces like this? | 2011/10/18 | [
"https://Stackoverflow.com/questions/7809215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30006/"
] | You can use "-sync y" on your qsub to cause the qsub to wait until the job(s) are finished. | The [Jenkins SGE Cloud plugin](https://wiki.jenkins-ci.org/display/JENKINS/SGE+Cloud+Plugin) submits builds to the Sun Grid Engine (SGE) batch scheduler. Both the open source version of SGE and the commercial Univa Grid Engine (UGE) are supported.
This plugin adds a new type of build step *Run job on SGE* that submits batch jobs to SGE. The build step monitors the job status and periodically appends the progress to the build's *Console Output*. Should the build fail, errors and the exit status of the job also appear. If the job is terminated in Jenkins, it is also terminated in SGE.
Builds are submitted to SGE by a new type of cloud, SGE Cloud. The cloud is given a label like any other slave. When a job with a matching label is run, SGE Cloud submits the build to SGE. |
7,809,215 | I have a project of business objects and a data layer that could potentially be implemented in multiple interfaces (web site, web services, console app, etc).
My question deals with how to properly implement caching in the methods dealing with data retrieval. I'll be using SqlCacheDependency to determine when the cached objects need to be expired, but I'm unsure of the best way of implementing the cache itself:
If the library is being used for a web project, I'd like to use HttpRuntime.Cache; however, I'm guessing that would be an issue for console apps.
What is the best way of implementing caching in your data layer for a .Net project when allowing for multiple types of interfaces like this? | 2011/10/18 | [
"https://Stackoverflow.com/questions/7809215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30006/"
] | Jenkins allows for you to submit the results of a build using a web based API. I currently use this to monitor a job remotely for a grid at my orginization. If you have the ability to perform a web post to the jenkins server you could use the below script to accomplish the job.
```
#!/bin/bash
MESSAGE="Some message about job success"
RUNTIME="Some calculation to estimate runtime"
USERNAME="userNameForJenkinsLogin"
PASSWORD="passwordForJenkinsLogin"
JENKINS_HOST="URLToJenkins"
TEST_NAME="Name of Test"
curl -i -X post -d "<run><log>$MESSAGE</log><result>0</result><duration>$RUNTIME</duration></run>" http://$USERNAME:$PASSWORD@$JENKINS_HOST/jenkins/job/$TEST_NAME/postBuildResult
``` | The [Jenkins SGE Cloud plugin](https://wiki.jenkins-ci.org/display/JENKINS/SGE+Cloud+Plugin) submits builds to the Sun Grid Engine (SGE) batch scheduler. Both the open source version of SGE and the commercial Univa Grid Engine (UGE) are supported.
This plugin adds a new type of build step *Run job on SGE* that submits batch jobs to SGE. The build step monitors the job status and periodically appends the progress to the build's *Console Output*. Should the build fail, errors and the exit status of the job also appear. If the job is terminated in Jenkins, it is also terminated in SGE.
Builds are submitted to SGE by a new type of cloud, SGE Cloud. The cloud is given a label like any other slave. When a job with a matching label is run, SGE Cloud submits the build to SGE. |
161,751 | I've created a custom user role and am attempting to change the users role from CUSTOMER to ADVOCATE on purchase of a particular product (using WooCommerce). I'm really close but struggling to get the correctly serialized data into my table:
```
$order = new WC_Order( $order_id );
$items = $order->get_items();
$new_role = 'Array([advocate] => 1)';
$data = serialize( $new_role );
if ( $product_id == '786' ) {
update_user_meta( $order->user_id, 'wp_capabilities', $data );
}
```
The correct table is being populated at the correct time but as
```
s:30:"s:22:"Array([advocate] => 1)";";
```
rather than what I need it to be which is
```
a:1:{s:8:"advocate";b:1;}
```
Where is my serialization tripping up? | 2014/09/17 | [
"https://wordpress.stackexchange.com/questions/161751",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/45504/"
] | I think you are not handling the array part correctly.
The right syntax is -
```
$new_role = array("advocate" => 1);
```
The syntax that you have used is shown when you print some array on your screen but it should be written in above format in your PHP code. Currently, you are capturing it as a string and not an array. | In addition to syntax correction from WisdmLabs above I also found that I was effectively serialising the string TWICE as it will be automatically serialized when using update\_user\_meta. Not sure at which point I started serialising it myself but apparently that was completely unnecessary.
<http://codex.wordpress.org/Function_Reference/update_user_meta> |
161,751 | I've created a custom user role and am attempting to change the users role from CUSTOMER to ADVOCATE on purchase of a particular product (using WooCommerce). I'm really close but struggling to get the correctly serialized data into my table:
```
$order = new WC_Order( $order_id );
$items = $order->get_items();
$new_role = 'Array([advocate] => 1)';
$data = serialize( $new_role );
if ( $product_id == '786' ) {
update_user_meta( $order->user_id, 'wp_capabilities', $data );
}
```
The correct table is being populated at the correct time but as
```
s:30:"s:22:"Array([advocate] => 1)";";
```
rather than what I need it to be which is
```
a:1:{s:8:"advocate";b:1;}
```
Where is my serialization tripping up? | 2014/09/17 | [
"https://wordpress.stackexchange.com/questions/161751",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/45504/"
] | I think you are not handling the array part correctly.
The right syntax is -
```
$new_role = array("advocate" => 1);
```
The syntax that you have used is shown when you print some array on your screen but it should be written in above format in your PHP code. Currently, you are capturing it as a string and not an array. | The b in the serialized string means boolean. So you need to use true instead of one. And serializing it results in double serialization which explains "s:25:" in the beginning. Try this:
```
update_user_meta(46, 'wp_capabilities', array('employer'=>true));
``` |
161,751 | I've created a custom user role and am attempting to change the users role from CUSTOMER to ADVOCATE on purchase of a particular product (using WooCommerce). I'm really close but struggling to get the correctly serialized data into my table:
```
$order = new WC_Order( $order_id );
$items = $order->get_items();
$new_role = 'Array([advocate] => 1)';
$data = serialize( $new_role );
if ( $product_id == '786' ) {
update_user_meta( $order->user_id, 'wp_capabilities', $data );
}
```
The correct table is being populated at the correct time but as
```
s:30:"s:22:"Array([advocate] => 1)";";
```
rather than what I need it to be which is
```
a:1:{s:8:"advocate";b:1;}
```
Where is my serialization tripping up? | 2014/09/17 | [
"https://wordpress.stackexchange.com/questions/161751",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/45504/"
] | In addition to syntax correction from WisdmLabs above I also found that I was effectively serialising the string TWICE as it will be automatically serialized when using update\_user\_meta. Not sure at which point I started serialising it myself but apparently that was completely unnecessary.
<http://codex.wordpress.org/Function_Reference/update_user_meta> | The b in the serialized string means boolean. So you need to use true instead of one. And serializing it results in double serialization which explains "s:25:" in the beginning. Try this:
```
update_user_meta(46, 'wp_capabilities', array('employer'=>true));
``` |
37,826,786 | I need to create ordered lists for a specific type of genealogy report called a register. In a register, all children are numbered with lower-case Roman numerals, and those with descendants also get an Arabic numeral, like this:
```
First Generation
1. Joe Smith
2 i. Joe Smith Jr.
ii. Fred Smith
3 iii. Mary Smith
iv. Jane Smith
Second Generation
2. Joe Smith Jr.
i. Oscar Smith
4 ii. Amanda Smith
3. Mary Smith
5 i. Ann Evans
```
You can see my initial attempt on this fiddle: <https://jsfiddle.net/ericstoltz/gpqf0Ltu/>
The problem is that the Arabic numerals need to be consecutive from generation to generation, that is, over separate ordered lists. When you look at the fiddle, you can see the second generation begins again at 1 for Arabic numerals, but it should begin with 2 because that's the number assigned to that person as the child of 1, and the first of 2's children with descendants should be 4 instead of 5. So the counter is continuing on to the second list in some partial way when I need it to be more consistent.
To clarify: this is not just about sequential numbering. Each person with descendants is identified by a unique number, and that number will appear twice: With that person as a child and with that person as a parent.
The generations need to be separated because of the headings and sometimes there is narrative between them.
I feel I am very close and am just overlooking something to get this to work!
UPDATE: SOLVED. See fiddle for how I did this with two counters. | 2016/06/15 | [
"https://Stackoverflow.com/questions/37826786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5559646/"
] | The problem in that query is the semicolon, which is the default query delimiter.
In order to change the delimiter in HeidiSQL, add the DELIMITER client command above the `CREATE PROCEDURE` query:
```
DELIMITER \\
SELECT 1\\
CREATE PROCEDURE ...\\
DELIMITER ;
```
HeidiSQL also has a procedure designer, with no need to set the delimiter:
[](https://i.stack.imgur.com/FCwFm.png) | Try this one
```
DELIMITER //
CREATE PROCEDURE SP_FORM20_POST(
P_SESSIONID VARCHAR(256)
)
BEGIN
INSERT INTO tbForm20
( SESSIONID, RegDT)
VALUES
( P_SESSIONID, NOW());
END //
DELIMITER;
``` |
37,826,786 | I need to create ordered lists for a specific type of genealogy report called a register. In a register, all children are numbered with lower-case Roman numerals, and those with descendants also get an Arabic numeral, like this:
```
First Generation
1. Joe Smith
2 i. Joe Smith Jr.
ii. Fred Smith
3 iii. Mary Smith
iv. Jane Smith
Second Generation
2. Joe Smith Jr.
i. Oscar Smith
4 ii. Amanda Smith
3. Mary Smith
5 i. Ann Evans
```
You can see my initial attempt on this fiddle: <https://jsfiddle.net/ericstoltz/gpqf0Ltu/>
The problem is that the Arabic numerals need to be consecutive from generation to generation, that is, over separate ordered lists. When you look at the fiddle, you can see the second generation begins again at 1 for Arabic numerals, but it should begin with 2 because that's the number assigned to that person as the child of 1, and the first of 2's children with descendants should be 4 instead of 5. So the counter is continuing on to the second list in some partial way when I need it to be more consistent.
To clarify: this is not just about sequential numbering. Each person with descendants is identified by a unique number, and that number will appear twice: With that person as a child and with that person as a parent.
The generations need to be separated because of the headings and sometimes there is narrative between them.
I feel I am very close and am just overlooking something to get this to work!
UPDATE: SOLVED. See fiddle for how I did this with two counters. | 2016/06/15 | [
"https://Stackoverflow.com/questions/37826786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5559646/"
] | The problem is this. The database reads the `;` in your code as an end of the procedure. You probably don't intend it like that :). The `DELIMITER` command takes care of that by changing `;` to something customizable, like `$$`. Try this:
```
DELIMITER $$
CREATE PROCEDURE SP_FORM20_POST(
P_SESSIONID VARCHAR(256)
)
BEGIN
INSERT INTO tbForm20
( SESSIONID, RegDT)
VALUES
( P_SESSIONID, NOW());
END$$
DELIMITER ;
``` | Try this one
```
DELIMITER //
CREATE PROCEDURE SP_FORM20_POST(
P_SESSIONID VARCHAR(256)
)
BEGIN
INSERT INTO tbForm20
( SESSIONID, RegDT)
VALUES
( P_SESSIONID, NOW());
END //
DELIMITER;
``` |
3,151,938 | I want to create a site using a cms, but I want to use my own look and feel. I want to be able to upload downloadable content such as mp3 files with a flash player. I also want users to sign up and login. I want to be able to track and log downloads and uploads done by users. Any suggestions? | 2010/06/30 | [
"https://Stackoverflow.com/questions/3151938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/220007/"
] | There are dozens of different CMS systems and each works slightly different and is geared for a specific use case. Some of the most popular PHP CMS systems are:
[Drupal](http://drupal.org) - One of my favorites. Very powerful and extensible but a large learning curve and for most projects it can be overkill.
[Joomla](http://www.joomla.org/) - Similar to drupal. Easier to use for sure but a little less powerful. For most projects it can be overkill.
[Wordpress](http://wordpress.org) - The premier PHP blog engine. Designed for blogging but can handle most any site type. Very easy to use but you sacrifice some extensibility.
All of these CMS systems have very popular and well documented theme engines and active development communities. I think a choice of CMS has more to do with how you want to use your site rather than your technical needs because at this point there is a large amount of feature parity ( no flaming on this, I know in some cases this is not true but for most mainstream needs they all offer similar features in third-party modules if not built in). For your specific needs you mentioned any of these will probably work. Download them all and try them out. Why not? They're free.
For a full list of PHP CMS try [Wikipedia](http://en.wikipedia.org/wiki/List_of_content_management_systems#PHP_2) | Sounds like [Drupal](http://drupal.org/) could satisfy your requirements.
* It would allow you to create a template for your own look and feel
* You can use the CCK and Views modules to create your own content types that support your downloadable files.
* Drupal has a robust built-in user account system.
* There are at least a couple of modules that can be used to track downloads. |
3,151,938 | I want to create a site using a cms, but I want to use my own look and feel. I want to be able to upload downloadable content such as mp3 files with a flash player. I also want users to sign up and login. I want to be able to track and log downloads and uploads done by users. Any suggestions? | 2010/06/30 | [
"https://Stackoverflow.com/questions/3151938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/220007/"
] | There are dozens of different CMS systems and each works slightly different and is geared for a specific use case. Some of the most popular PHP CMS systems are:
[Drupal](http://drupal.org) - One of my favorites. Very powerful and extensible but a large learning curve and for most projects it can be overkill.
[Joomla](http://www.joomla.org/) - Similar to drupal. Easier to use for sure but a little less powerful. For most projects it can be overkill.
[Wordpress](http://wordpress.org) - The premier PHP blog engine. Designed for blogging but can handle most any site type. Very easy to use but you sacrifice some extensibility.
All of these CMS systems have very popular and well documented theme engines and active development communities. I think a choice of CMS has more to do with how you want to use your site rather than your technical needs because at this point there is a large amount of feature parity ( no flaming on this, I know in some cases this is not true but for most mainstream needs they all offer similar features in third-party modules if not built in). For your specific needs you mentioned any of these will probably work. Download them all and try them out. Why not? They're free.
For a full list of PHP CMS try [Wikipedia](http://en.wikipedia.org/wiki/List_of_content_management_systems#PHP_2) | The two major ones that I can pick out off the top of my head are Drupal and Joomla, so I'd check both of those out. For a good comparison, read [this](http://www.topnotchthemes.com/blog/090224/drupal-vs-joomla-frank-comparison-ibm-consultant) article. |
3,151,938 | I want to create a site using a cms, but I want to use my own look and feel. I want to be able to upload downloadable content such as mp3 files with a flash player. I also want users to sign up and login. I want to be able to track and log downloads and uploads done by users. Any suggestions? | 2010/06/30 | [
"https://Stackoverflow.com/questions/3151938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/220007/"
] | There are dozens of different CMS systems and each works slightly different and is geared for a specific use case. Some of the most popular PHP CMS systems are:
[Drupal](http://drupal.org) - One of my favorites. Very powerful and extensible but a large learning curve and for most projects it can be overkill.
[Joomla](http://www.joomla.org/) - Similar to drupal. Easier to use for sure but a little less powerful. For most projects it can be overkill.
[Wordpress](http://wordpress.org) - The premier PHP blog engine. Designed for blogging but can handle most any site type. Very easy to use but you sacrifice some extensibility.
All of these CMS systems have very popular and well documented theme engines and active development communities. I think a choice of CMS has more to do with how you want to use your site rather than your technical needs because at this point there is a large amount of feature parity ( no flaming on this, I know in some cases this is not true but for most mainstream needs they all offer similar features in third-party modules if not built in). For your specific needs you mentioned any of these will probably work. Download them all and try them out. Why not? They're free.
For a full list of PHP CMS try [Wikipedia](http://en.wikipedia.org/wiki/List_of_content_management_systems#PHP_2) | I prefer [Typo3](http://typo3.org/).
Very powerful and great extension repository. For you requirements you dont even need any extension. But it will take a lot of time to get in. |
5,476,647 | I'm running into a problem submitting my application through the Application Loader. I'm receiving the message "This bundle is invalid. Apple is not currently accepting applications built with this version of the SDK."
I've installed Xcode 4.0.1 w/SDK 4.3 ("4A1006", March 24), and I've reinstalled both MonoDevelop and MonoTouch. I've also made sure my build/bundle settings are using SDK 4.3, and I've tried each of the min versions of 4.0, 4.1, 4.2, and 4.3.
Suggestions?
Update: I've uninstalled Xcode 4 (rebooted), installed latest Xcode 3 same w/SDK (rebooted), and reinstalled MonoDevelop & MonoTouch. Still no luck unfortunately. I tried with and without manually specifying DTXcode:0400.
I've been reinstalling MonoTouch by re-running the installer. Is there a way to do a clean uninstall of MT and could that help in this case? | 2011/03/29 | [
"https://Stackoverflow.com/questions/5476647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29152/"
] | Apple changed the keys required in the application manifest in iOS SDK 4.3.1. We've released a new MonoDevelop build to track this. | Xcode 4.0.1 was released last week with the iOS 4.3.1 SDK, you need to install that. |
5,476,647 | I'm running into a problem submitting my application through the Application Loader. I'm receiving the message "This bundle is invalid. Apple is not currently accepting applications built with this version of the SDK."
I've installed Xcode 4.0.1 w/SDK 4.3 ("4A1006", March 24), and I've reinstalled both MonoDevelop and MonoTouch. I've also made sure my build/bundle settings are using SDK 4.3, and I've tried each of the min versions of 4.0, 4.1, 4.2, and 4.3.
Suggestions?
Update: I've uninstalled Xcode 4 (rebooted), installed latest Xcode 3 same w/SDK (rebooted), and reinstalled MonoDevelop & MonoTouch. Still no luck unfortunately. I tried with and without manually specifying DTXcode:0400.
I've been reinstalling MonoTouch by re-running the installer. Is there a way to do a clean uninstall of MT and could that help in this case? | 2011/03/29 | [
"https://Stackoverflow.com/questions/5476647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29152/"
] | Apple changed the keys required in the application manifest in iOS SDK 4.3.1. We've released a new MonoDevelop build to track this. | One thought: Double-check that you're building/signing for release, and not e.g. for ad-hoc distribution. |
5,476,647 | I'm running into a problem submitting my application through the Application Loader. I'm receiving the message "This bundle is invalid. Apple is not currently accepting applications built with this version of the SDK."
I've installed Xcode 4.0.1 w/SDK 4.3 ("4A1006", March 24), and I've reinstalled both MonoDevelop and MonoTouch. I've also made sure my build/bundle settings are using SDK 4.3, and I've tried each of the min versions of 4.0, 4.1, 4.2, and 4.3.
Suggestions?
Update: I've uninstalled Xcode 4 (rebooted), installed latest Xcode 3 same w/SDK (rebooted), and reinstalled MonoDevelop & MonoTouch. Still no luck unfortunately. I tried with and without manually specifying DTXcode:0400.
I've been reinstalling MonoTouch by re-running the installer. Is there a way to do a clean uninstall of MT and could that help in this case? | 2011/03/29 | [
"https://Stackoverflow.com/questions/5476647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29152/"
] | Apple changed the keys required in the application manifest in iOS SDK 4.3.1. We've released a new MonoDevelop build to track this. | i had this problem for one week and i just solve it today , it seems that SDK 4.3 has a problem with the monotouch anyway
the one works with me i uninstall the SDK and install SDK 4.2 with Xcode 3.2.5 and Remove monorouch 3.2.6 and install 3.2.3 . and it will work. |
13,594,537 | what does the "overused deferral" warning mean in iced coffeescript? It seems to happen when I throw an uncaught error in the code. How can I let the error bubble up as I need it be an uncaught error for unit testing. For instance, if my getByName method throws an error it bubbles up that iced coffeescript warning rather than bubbling up the exception.
```
await Profile.getByName p.uname, defer(err, existingUser)
return done new errors.DuplicateUserName(), 409 if existingUser isnt null
return done new Error("error in looking up user name " + err), 500 if err
``` | 2012/11/27 | [
"https://Stackoverflow.com/questions/13594537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/611750/"
] | This error is generated when a callback generated by `defer` is called more than once. In your case, it could be that `Profile.getByName` is calling its callback twice (or more). This warning almost always indicates an error in my experience.
You can disable this warning if you create a callback from a Rendezvous and explicitly make it a "multi" callback. Otherwise, it only makes sense to have the return from `defer` give you a one-shot callback.
More info here: <https://github.com/maxtaco/coffee-script/blob/iced/iced.md#icedrendezvousidimultidefer-slots>
A small note on terminology: in IcedCoffeeScript, a callback generated by `defer` is known as a "deferral" in error messages and the documentation. | On top of Max's answer, the appropriate usage of the continuation style programming should be to replace the one-off callbacks, not the repetitive callbacks. All `await` does is to wait for all its deferrals to complete so it can move on. The following example using `node.js`'s `fs` module to read a large file would reproduce this error:
```
toread = process.argv[2]
fs = require 'fs'
rs = fs.createReadStream toread
await rs.on 'data', defer content
console.log "content: #{content}"
```
Now run this script with a huge text file. Since the `data` event will fire more than once as the large file content doesn't fit the buffer, it fires multiple times to the generated defer callback, thus giving the same error.
```
<partial file contents...>
ICED warning: overused deferral at <anonymous> (C:\Users\kk\3.coffee:4)
ICED warning: overused deferral at <anonymous> (C:\Users\kk\3.coffee:4)
ICED warning: overused deferral at <anonymous> (C:\Users\kk\3.coffee:4)
...
```
In this case, it is wrong to use `await/defer` since the `content` won't be complete. This is exactly why Max mentioned the presence of this error would usually indicate a code bug. In fact IMO it should throw an error rather than a warning that can be silenced. |
107,653 | In legal texts, at least in Sweden and Germany, it is common to print some parts of the body text in a smaller font. Is there a name for this typographic convention?
Examples:
[](https://i.stack.imgur.com/sLyzz.jpg)
[](https://i.stack.imgur.com/vZnb3.png) | 2018/04/05 | [
"https://graphicdesign.stackexchange.com/questions/107653",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/12723/"
] | I believe it is called an "Inline Citation" or "In-Text Citation"
<https://owl.english.purdue.edu/owl/resource/560/02/>
Here: <http://www.easybib.com/guides/citation-guides/chicago-turabian/notes/> I believe they could be referring to the "same thing" but lacking an actual citation (as in your example) simply as a "note".
**Update:** During some further research I found this document from Harvard: <https://utas.libguides.com/ld.php?content_id=21757697> a solid 48 pages just concerning notes and citations. I stand by my original answer that this is simply an "in text note", or possibly a "parenthetical reference" (also known as Harvard referencing) but the document does provide fascinating (to text nerds!) further reading. | In Polish text Norm such things are called "Additions", "interjected terms" by publishers and "bracket definition" by lawyers. Or "Parenthesis" by linguistics.
The short definition of such text is
>
> two-side isolated intra-wording sequence
>
>
>
And in proofreading marks they are symbolised by **[p]** and **[w]** |
22,348,782 | I'm using Json.Net to DeserializeObject Json data.
This is my Json
```
string datosContratos = {"Total":1,"Contrato":[{"Numero":1818,"CUPS":"ES003L0P","Direccion":"C. O ","TextoCiudad":"MADRID","Tarifa":"2"}]}
```
My classes are:
```
public class Contrato
{
public int Numero;
public String Cups;
public String Direccion;
public String TextoCiudad;
public String Tarifa;
}
public class Contratos
{
public int Total { get; set; }
public List<Contrato> ListaContratos { get; set; }
}
```
when I deseralize:
```
Contratos contratos = JsonConvert.DeserializeObject<Contratos>(datosContratos);
```
And the result is that contratos.Total is correct (in this case 1) but the `ListaContratos` is null although it should be filled with the data. I don't see the problem!!! | 2014/03/12 | [
"https://Stackoverflow.com/questions/22348782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/979048/"
] | Just `IF(@CustomerID IS NULL)` is enough
```
IF(@CustomerID IS NULL)
BEGIN
--insert here..
INSERT INTO [tblCustomerMaster]
([CustomerName]
VALUES
(CustomerName)
SET @CustomerID = Scope_Identity() -- sql server syntax to get the ID after insert..
END
ELSE
BEGIN
-- update perhaps..
END
``` | You may try like this:
```
if (isnull(@customerID) == 1)
BEGIN
--Your code
END
ELSE
BEGIN
-- code
END
```
Also change this line
```
declare @CustomerID numeric(18,0)= (SELECT distinct [CustomerID] FROM [tblCustomerMaster] where CustomerName = @CustomerName)
```
with this:
```
declare @CustomerID numeric(18,0)
(SELECT @CustomerID := [CustomerID]
FROM [tblCustomerMaster]
where CustomerName = @CustomerName)
``` |
22,340,864 | I am a VHDL coder, and haven't coded much with Verilog. I am going through someone else's code, and I came across this:
```
always@(posedge asix_clk_bufg or negedge pll_asix_locked)
begin
if (~pll_asix_locked)
asix_rst <= 0;
else if (timer[5]) // 355us between asix_clk and asix_rst (min is 200us)
asix_rst <= 1;
end
```
I am not sure if I agree with the above code ! Isn't a possible latch scenario ? I see it is waiting for the pll to lock and then bring the system out of reset, but is this coded correctly?
I don't like to combine sequential and combinatorial code together, but what is the value of "asix\_rst" when timer[5] = 0 ?!?
Thanks,
--Rudy | 2014/03/12 | [
"https://Stackoverflow.com/questions/22340864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2002041/"
] | This is the way to infer a flip-flop with a positive edge clock (asix\_clk\_bufg) an asynchronous active low reset (pll\_asix\_locked) and a clock enable (timer[5]). There is a D input (tied to 1) and a Q output (asix\_rst).
I assume that the PLL starts off not locked so `asix_rst` is 0 until the first clock edge when `timer[5] == 1`. It will then stay high until the PLL loses lock. The reset must be asynchronous since the clock will stop when the PLL loses lock.
I am guessing that the timer[5] bit goes high 5 or 6 clock cycles after the PLL is locked ensuring that there is a stable clock before the rest of the system comes out of reset.
This would be a latch if instead of the clock you had `timer[5]` in the sensitivity list like this:
```
always@(timer[5] or pll_asix_locked)
begin
if (~pll_asix_locked)
asix_rst <= 0;
else if (timer[5]) // 355us between asix_clk and asix_rst (min is 200us)
asix_rst <= 1;
end
``` | Latches are only generated with combinational always blocks. Since the signal in the sensitivity list is looking for the posedge of the clock, the code is generating sequential logic. Sequential logic will never generate a latch.
For more information read about [how transparent latches are created and how to avoid inferring latches](http://www.nandland.com/articles/how-to-avoid-transparent-latches-in-vhdl-and-verlog.html) |
25,291,730 | I have and 3 images that I need to change like so:
Image 1 > Image 2 > Image 3 > Image 1 and so on in that loop.
**JavaScript**
```
function changeImage() {
if (document.getElementById("imgClickAndChange").src = "Webfiles/SUB15_15A.bmp")
{
document.getElementById("imgClickAndChange").src = "Webfiles/SUB15.bmp";
}
else if (document.getElementById("imgClickAndChange").src = "Webfiles/SUB15.bmp")
{
document.getElementById("imgClickAndChange").src = "Webfiles/SUB15A.bmp";
}
else
{
document.getElementById("imgClickAndChange").src = "Webfiles/SUB15_15A.bmp"
}
}
```
**HTML**
```
<img src="Webfiles/SUB15_15A.bmp" id="imgClickAndChange" onclick="changeImage()" usemap="#SUB15" />
```
Any suggestions are appreciated. Everything else I have tried has not worked. | 2014/08/13 | [
"https://Stackoverflow.com/questions/25291730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3854096/"
] | On *img* click change the *src* attribute of the img tag and using a counter would help more rather checking the previous image source.
HTML :
```
<img src="http://www.clipartbest.com/cliparts/RiA/66K/RiA66KbMT.png" id="imgClickAndChange" onclick="changeImage()" usemap="#SUB15" />
```
JS :
```
var counter = 1;
imgClickAndChange.onclick = function(){
if(counter == 0){
document.getElementById("imgClickAndChange").src = "http://www.clipartbest.com/cliparts/RiA/66K/RiA66KbMT.png";
counter++;
}
else if(counter == 1){
document.getElementById("imgClickAndChange").src = "http://www.wpclipart.com/education/animal_numbers/animal_number_2.png";
counter++;
}
else if(counter == 2){
document.getElementById("imgClickAndChange").src = "http://upload.wikimedia.org/wikipedia/commons/thumb/e/e4/Number_3_in_yellow_rounded_square.svg/512px-Number_3_in_yellow_rounded_square.svg.png";
counter = 0;
}
};
```
[***jsFiddle***](http://jsfiddle.net/codeSpy/6an7kkmm/) | Use the triple equals '===' to check when if the src is equivalent or not. Using one equal '=' means you are assigning the value so you'll never get past the first if. |
25,291,730 | I have and 3 images that I need to change like so:
Image 1 > Image 2 > Image 3 > Image 1 and so on in that loop.
**JavaScript**
```
function changeImage() {
if (document.getElementById("imgClickAndChange").src = "Webfiles/SUB15_15A.bmp")
{
document.getElementById("imgClickAndChange").src = "Webfiles/SUB15.bmp";
}
else if (document.getElementById("imgClickAndChange").src = "Webfiles/SUB15.bmp")
{
document.getElementById("imgClickAndChange").src = "Webfiles/SUB15A.bmp";
}
else
{
document.getElementById("imgClickAndChange").src = "Webfiles/SUB15_15A.bmp"
}
}
```
**HTML**
```
<img src="Webfiles/SUB15_15A.bmp" id="imgClickAndChange" onclick="changeImage()" usemap="#SUB15" />
```
Any suggestions are appreciated. Everything else I have tried has not worked. | 2014/08/13 | [
"https://Stackoverflow.com/questions/25291730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3854096/"
] | On *img* click change the *src* attribute of the img tag and using a counter would help more rather checking the previous image source.
HTML :
```
<img src="http://www.clipartbest.com/cliparts/RiA/66K/RiA66KbMT.png" id="imgClickAndChange" onclick="changeImage()" usemap="#SUB15" />
```
JS :
```
var counter = 1;
imgClickAndChange.onclick = function(){
if(counter == 0){
document.getElementById("imgClickAndChange").src = "http://www.clipartbest.com/cliparts/RiA/66K/RiA66KbMT.png";
counter++;
}
else if(counter == 1){
document.getElementById("imgClickAndChange").src = "http://www.wpclipart.com/education/animal_numbers/animal_number_2.png";
counter++;
}
else if(counter == 2){
document.getElementById("imgClickAndChange").src = "http://upload.wikimedia.org/wikipedia/commons/thumb/e/e4/Number_3_in_yellow_rounded_square.svg/512px-Number_3_in_yellow_rounded_square.svg.png";
counter = 0;
}
};
```
[***jsFiddle***](http://jsfiddle.net/codeSpy/6an7kkmm/) | You're using an assignment operator instead of a comparison operator in your if statements
```
if (document.getElementById("imgClickAndChange").src = "Webfiles/SUB15_15A.bmp")
```
should be
```
if (document.getElementById("imgClickAndChange").src == "Webfiles/SUB15_15A.bmp")
// ^
```
Also using the `src` property as a comparison might not be a good idea as the browser might have it as an absolute url rather than the relative url in the html `src` attribute, which might be better to use.
```
if (document.getElementById("imgClickAndChange").getAttribute("src") == "Webfiles/SUB15_15A.bmp")
```
<http://jsfiddle.net/rzannv33/>
I'd suggest using a variable to keep the state of the image, like a counter probably. |
63,844,611 | In most recent django documentation "Overriding from the project’s templates directory"
<https://docs.djangoproject.com/en/3.1/howto/overriding-templates/>
it shows that you can use the following path for templates:
```
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'templates'],
'APP_DIRS': True,
...
},
]
```
I tried using `[BASE_DIR / 'templates']` but I keep getting the following error:
`TypeError: unsupported operand type(s) for /: 'str' and 'str'`
It all works fine when I change the code to: `[BASE_DIR , 'templates']` or `[os.path.join(BASE_DIR , 'templates')]`, no problem in such case.
Can someone explain what am I missing with the `[BASE_DIR / 'templates']` line?
Thank you.
I'm using Python 3.8 and Django 3.1. | 2020/09/11 | [
"https://Stackoverflow.com/questions/63844611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5934625/"
] | In order to use `BASE_DIR / 'templates'`, you need `BASE_DIR` to be a [`Path()`](https://docs.python.org/3/library/pathlib.html#pathlib.Path).
```
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
```
I suspect that your settings.py was created with an earlier version of Django, and therefore `BASE_DIR` is a string, e.g.
```
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
``` | Thank you
```
from pathlib import Path
import os
BASE_DIR = Path(__file__).resolve().parent.parent
``` |
3,486,881 | Group $G$ is abelian and finite. $\langle g\rangle = G$. $p$ is order of $G$ (and $\langle g\rangle$). $p=mn$, $m > 1$, $n > 1$. Why $\langle g^m\rangle < G$ (not $\langle g^m\rangle \le G$)? | 2019/12/25 | [
"https://math.stackexchange.com/questions/3486881",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/736839/"
] | Basic result in theory of cyclic groups: $\langle g\rangle =G\implies |g^m|=\dfrac n{\operatorname {gcd}(n,m)}$, where $n=|G|$. | As $|\langle g^m \rangle | = \dfrac {|G|} m$ and $m > 1$, so $|\langle g^m \rangle | < |G|$. |
45,724 | I just made the switch from Windows to Mac, and one thing that's been bothering me is that on a Mac, I can't see multiple Word documents that I have open. On Windows, they all appear in the taskbar (after checking the option to not collapse instances of the same program) and I can quickly switch between them, which is useful for a variety of reasons. On a mac, I can't do that. The best way I've discovered so far is to go into mission control, but then I still have to make two gestures instead of one, and it's hard to see which window is which. What's the best way to do this? | 2012/03/24 | [
"https://apple.stackexchange.com/questions/45724",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/20621/"
] | App Exposé
==========
Trigger using swipe gesture:
* **System Preferences → Trackpad → More Gestures → App Exposé**
Trigger using keys or mouse:
* **System Preferences → Mission Control**

Dock Icon:
* You can trigger App Exposé by right-clicking the Word icon in the Dock and choosing the option **Show All Windows**.
Alternatively you can cycle all Windows of the same application using:
* `⌘`+`~` (US keyboard layout)
 | You can use `⌘` + `~` to toggle between multiple windows of the same app.
This is an OS X-wide keyboard shortcut, so it works in Word for Mac 2011, too. |
45,724 | I just made the switch from Windows to Mac, and one thing that's been bothering me is that on a Mac, I can't see multiple Word documents that I have open. On Windows, they all appear in the taskbar (after checking the option to not collapse instances of the same program) and I can quickly switch between them, which is useful for a variety of reasons. On a mac, I can't do that. The best way I've discovered so far is to go into mission control, but then I still have to make two gestures instead of one, and it's hard to see which window is which. What's the best way to do this? | 2012/03/24 | [
"https://apple.stackexchange.com/questions/45724",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/20621/"
] | App Exposé
==========
Trigger using swipe gesture:
* **System Preferences → Trackpad → More Gestures → App Exposé**
Trigger using keys or mouse:
* **System Preferences → Mission Control**

Dock Icon:
* You can trigger App Exposé by right-clicking the Word icon in the Dock and choosing the option **Show All Windows**.
Alternatively you can cycle all Windows of the same application using:
* `⌘`+`~` (US keyboard layout)
 | In system preferences you can turn on the gesture for Application Exposè which is essentially Mission Control but only for either the current application or the one your cursor was hovering over in the dock at the time.
This should make it easier to see what it what, but overall it's simply not realistic to force Windows methods of UI interaction onto a Mac desktop. For every person switcher wanting to see a Dock icon per document window are a probably more non-switchers who want to use the Mac method of seeing an icon for the app, and one for each minimised windows - unless even this is switched off and the document minimise to the app icon.
It's one of the fundamental difference between the Doc and the Task Bar. The Dock is an application launcher/switcher, and a minimised window holder. The Task Bar is essentially an area for any and all running Windows. |
45,724 | I just made the switch from Windows to Mac, and one thing that's been bothering me is that on a Mac, I can't see multiple Word documents that I have open. On Windows, they all appear in the taskbar (after checking the option to not collapse instances of the same program) and I can quickly switch between them, which is useful for a variety of reasons. On a mac, I can't do that. The best way I've discovered so far is to go into mission control, but then I still have to make two gestures instead of one, and it's hard to see which window is which. What's the best way to do this? | 2012/03/24 | [
"https://apple.stackexchange.com/questions/45724",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/20621/"
] | * [Hyperdock](http://hyperdock.bahoom.com/) will give you window previews of each open window
belonging to an application by hovering over the dock icon, which you
can then click to activate.

* [Witch](http://manytricks.com/witch/) has a popup panel that displays the open
windows belonging to an application and also gives you a preview if
you hover over it.
 
* [Fantasktik](http://dj50.ro/fantasktik/) probably offers the most
similar functionality to the Windows taskbar. However, the original
developer seems to have disappeared and this hasn't been updated in a
while (and therefore probably won't ever be). The new
"owner" claims it works on Lion, so it might be worth a try.
 | App Exposé
==========
Trigger using swipe gesture:
* **System Preferences → Trackpad → More Gestures → App Exposé**
Trigger using keys or mouse:
* **System Preferences → Mission Control**

Dock Icon:
* You can trigger App Exposé by right-clicking the Word icon in the Dock and choosing the option **Show All Windows**.
Alternatively you can cycle all Windows of the same application using:
* `⌘`+`~` (US keyboard layout)
 |
45,724 | I just made the switch from Windows to Mac, and one thing that's been bothering me is that on a Mac, I can't see multiple Word documents that I have open. On Windows, they all appear in the taskbar (after checking the option to not collapse instances of the same program) and I can quickly switch between them, which is useful for a variety of reasons. On a mac, I can't do that. The best way I've discovered so far is to go into mission control, but then I still have to make two gestures instead of one, and it's hard to see which window is which. What's the best way to do this? | 2012/03/24 | [
"https://apple.stackexchange.com/questions/45724",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/20621/"
] | You can use `⌘` + `~` to toggle between multiple windows of the same app.
This is an OS X-wide keyboard shortcut, so it works in Word for Mac 2011, too. | In system preferences you can turn on the gesture for Application Exposè which is essentially Mission Control but only for either the current application or the one your cursor was hovering over in the dock at the time.
This should make it easier to see what it what, but overall it's simply not realistic to force Windows methods of UI interaction onto a Mac desktop. For every person switcher wanting to see a Dock icon per document window are a probably more non-switchers who want to use the Mac method of seeing an icon for the app, and one for each minimised windows - unless even this is switched off and the document minimise to the app icon.
It's one of the fundamental difference between the Doc and the Task Bar. The Dock is an application launcher/switcher, and a minimised window holder. The Task Bar is essentially an area for any and all running Windows. |
45,724 | I just made the switch from Windows to Mac, and one thing that's been bothering me is that on a Mac, I can't see multiple Word documents that I have open. On Windows, they all appear in the taskbar (after checking the option to not collapse instances of the same program) and I can quickly switch between them, which is useful for a variety of reasons. On a mac, I can't do that. The best way I've discovered so far is to go into mission control, but then I still have to make two gestures instead of one, and it's hard to see which window is which. What's the best way to do this? | 2012/03/24 | [
"https://apple.stackexchange.com/questions/45724",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/20621/"
] | * [Hyperdock](http://hyperdock.bahoom.com/) will give you window previews of each open window
belonging to an application by hovering over the dock icon, which you
can then click to activate.

* [Witch](http://manytricks.com/witch/) has a popup panel that displays the open
windows belonging to an application and also gives you a preview if
you hover over it.
 
* [Fantasktik](http://dj50.ro/fantasktik/) probably offers the most
similar functionality to the Windows taskbar. However, the original
developer seems to have disappeared and this hasn't been updated in a
while (and therefore probably won't ever be). The new
"owner" claims it works on Lion, so it might be worth a try.
 | You can use `⌘` + `~` to toggle between multiple windows of the same app.
This is an OS X-wide keyboard shortcut, so it works in Word for Mac 2011, too. |
45,724 | I just made the switch from Windows to Mac, and one thing that's been bothering me is that on a Mac, I can't see multiple Word documents that I have open. On Windows, they all appear in the taskbar (after checking the option to not collapse instances of the same program) and I can quickly switch between them, which is useful for a variety of reasons. On a mac, I can't do that. The best way I've discovered so far is to go into mission control, but then I still have to make two gestures instead of one, and it's hard to see which window is which. What's the best way to do this? | 2012/03/24 | [
"https://apple.stackexchange.com/questions/45724",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/20621/"
] | * [Hyperdock](http://hyperdock.bahoom.com/) will give you window previews of each open window
belonging to an application by hovering over the dock icon, which you
can then click to activate.

* [Witch](http://manytricks.com/witch/) has a popup panel that displays the open
windows belonging to an application and also gives you a preview if
you hover over it.
 
* [Fantasktik](http://dj50.ro/fantasktik/) probably offers the most
similar functionality to the Windows taskbar. However, the original
developer seems to have disappeared and this hasn't been updated in a
while (and therefore probably won't ever be). The new
"owner" claims it works on Lion, so it might be worth a try.
 | In system preferences you can turn on the gesture for Application Exposè which is essentially Mission Control but only for either the current application or the one your cursor was hovering over in the dock at the time.
This should make it easier to see what it what, but overall it's simply not realistic to force Windows methods of UI interaction onto a Mac desktop. For every person switcher wanting to see a Dock icon per document window are a probably more non-switchers who want to use the Mac method of seeing an icon for the app, and one for each minimised windows - unless even this is switched off and the document minimise to the app icon.
It's one of the fundamental difference between the Doc and the Task Bar. The Dock is an application launcher/switcher, and a minimised window holder. The Task Bar is essentially an area for any and all running Windows. |
26,683,840 | I am trying to create a ListView inside a ListFragment. My list is customize, so it has been created with an adapter. But the aplication crass and give me this error *your content must have a listview whose id attribute is 'android.r.id.list*
This is the ListFragment class:
```
public static class DummySectionFragment extends ListFragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_section_dummy, container, false);
Vector<String> names=new Vector<String>();
names.add("Alex");
names.add("Julia");
setListAdapter(new MyAdapter(getActivity(), names));
return rootView;
}
}
```
This is MyAdapter class:
```
public class MiAdaptador extends BaseAdapter {
private final Activity activ;
private final Vector<String> list;
public MiAdaptador(Activity activ, Vector<String> list) {
super();
this.actividad = activ;
this.list = list;
}
public View getView(int position, View convertView,
ViewGroup parent) {
LayoutInflater inflater = activ.getLayoutInflater();
View view = inflater.inflate(R.layout.adapter_view, null, true);
TextView textView =(TextView)view.findViewById(R.id.titulo);
textView.setText(lista.elementAt(position));
return view;
}
}
```
My fragment\_section\_dummy layout:
```
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Name list"
android:gravity="center"
android:layout_margin="10px"
android:textSize="10pt"/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1">
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:drawSelectorOnTop="false" />
<TextView
android:id="@android:id/empty"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
</LinearLayout>
```
And my adapter\_view layout:
```
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="?android:attr/listPreferredItemHeight">
<TextView android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:textAppearance="?android:attr/textAppearanceLarge"
android:singleLine="true"
android:text="title"
android:gravity="center"/>
<TextView android:id="@+id/subtitle"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Other text"
android:layout_below="@id/title"
android:layout_alignParentBottom="true"
android:gravity="center"/>
</RelativeLayout>
```
How could I solve this problem? | 2014/10/31 | [
"https://Stackoverflow.com/questions/26683840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3507510/"
] | Ignoring the issue of non-linear state machines, I've found the following to work well for my needs on a few projects with simple state machines:
```
# Check if the stage is in or before the supplied stage (stage_to_check).
def in_or_before_stage?(stage_to_check)
if stage_to_check.present? && self.stage.present?
STAGES_IN_ORDER.reverse.lazy.drop_while { |stg| stg != stage_to_check }.include?(self.stage)
else
false
end
end
```
and the other check is sometimes desired as well:
```
# Check if the stage is in or after the supplied stage (stage_to_check).
def in_or_after_stage?(stage_to_check)
if stage_to_check.present? && self.stage.present?
# Get all the stages that are in and after the stage we want to check (stage_to_check),
# and then see if the stage is in that list (well, technically in a lazy enumerable).
STAGES_IN_ORDER.lazy.drop_while { |stg| stg != stage_to_check }.include?(self.stage)
else
false
end
end
```
Where "STAGES\_IN\_ORDER" is just an array with the stages in order from initial to final.
We're just removing items from the list and then checking if our object's current stage is in our resulting list. If we want to know if it's in or before some stage we remove the later stages until we reach our supplied test stage, if we want to know if it's after some given stage we remove items from the front of the list.
I realize you probably don't need this answer anymore, but hopefully it helps someone =] | The problem here is that you don't have order inside state machine. You need to provide and declare one.
I would stick to this solution:
1. first declare constant in your model, containing states (in order!), so:
`STATES = [:new, :in_process, :done, :verified]`
2. And later, inside your model:
```
def current_state_index
return state_index(self.state)
end
def state_index(state)
return STATES.index(state)
end
def some_action
return unless current_state_index > state_index(:in_process)
#do some work end
end
``` |
26,683,840 | I am trying to create a ListView inside a ListFragment. My list is customize, so it has been created with an adapter. But the aplication crass and give me this error *your content must have a listview whose id attribute is 'android.r.id.list*
This is the ListFragment class:
```
public static class DummySectionFragment extends ListFragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_section_dummy, container, false);
Vector<String> names=new Vector<String>();
names.add("Alex");
names.add("Julia");
setListAdapter(new MyAdapter(getActivity(), names));
return rootView;
}
}
```
This is MyAdapter class:
```
public class MiAdaptador extends BaseAdapter {
private final Activity activ;
private final Vector<String> list;
public MiAdaptador(Activity activ, Vector<String> list) {
super();
this.actividad = activ;
this.list = list;
}
public View getView(int position, View convertView,
ViewGroup parent) {
LayoutInflater inflater = activ.getLayoutInflater();
View view = inflater.inflate(R.layout.adapter_view, null, true);
TextView textView =(TextView)view.findViewById(R.id.titulo);
textView.setText(lista.elementAt(position));
return view;
}
}
```
My fragment\_section\_dummy layout:
```
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Name list"
android:gravity="center"
android:layout_margin="10px"
android:textSize="10pt"/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1">
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:drawSelectorOnTop="false" />
<TextView
android:id="@android:id/empty"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
</LinearLayout>
```
And my adapter\_view layout:
```
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="?android:attr/listPreferredItemHeight">
<TextView android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:textAppearance="?android:attr/textAppearanceLarge"
android:singleLine="true"
android:text="title"
android:gravity="center"/>
<TextView android:id="@+id/subtitle"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Other text"
android:layout_below="@id/title"
android:layout_alignParentBottom="true"
android:gravity="center"/>
</RelativeLayout>
```
How could I solve this problem? | 2014/10/31 | [
"https://Stackoverflow.com/questions/26683840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3507510/"
] | Ignoring the issue of non-linear state machines, I've found the following to work well for my needs on a few projects with simple state machines:
```
# Check if the stage is in or before the supplied stage (stage_to_check).
def in_or_before_stage?(stage_to_check)
if stage_to_check.present? && self.stage.present?
STAGES_IN_ORDER.reverse.lazy.drop_while { |stg| stg != stage_to_check }.include?(self.stage)
else
false
end
end
```
and the other check is sometimes desired as well:
```
# Check if the stage is in or after the supplied stage (stage_to_check).
def in_or_after_stage?(stage_to_check)
if stage_to_check.present? && self.stage.present?
# Get all the stages that are in and after the stage we want to check (stage_to_check),
# and then see if the stage is in that list (well, technically in a lazy enumerable).
STAGES_IN_ORDER.lazy.drop_while { |stg| stg != stage_to_check }.include?(self.stage)
else
false
end
end
```
Where "STAGES\_IN\_ORDER" is just an array with the stages in order from initial to final.
We're just removing items from the list and then checking if our object's current stage is in our resulting list. If we want to know if it's in or before some stage we remove the later stages until we reach our supplied test stage, if we want to know if it's after some given stage we remove items from the front of the list.
I realize you probably don't need this answer anymore, but hopefully it helps someone =] | If one takes care in defining the correct order in AASM and makes sure *not* to override any states (to specify extra options, for example), it is possible to use them.
The following mixin defines scopes like `Model.done_or_before` and `Model.in_process_or_after`, as well as methods like `m.done_or_before?`.
```
module AASMLinearity
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def aasm(*args, &block)
r = super(*args, &block)
if block
states = r.state_machine.states.map(&:name)
column = r.attribute_name
states.each_with_index do |state, i|
scope "#{state}_or_after", ->{ where(column => states[i..-1]) }
scope "#{state}_or_before", ->{ where(column => states[0..i]) }
define_method "#{state}_or_after?", ->{ states[i..-1].include? read_attribute(column).to_sym }
define_method "#{state}_or_before?", ->{ states[0..i].include? read_attribute(column).to_sym }
end
end
r
end
end
end
```
You can put this in something like `app/models/concerns/aasm_linearity.rb`, and `include AASMLinearity` *after* `include AASM`, but before the statemachine definition. |
34,051,203 | I had a question about the return statement that is by itself in the control flow.
```
var rockPaperScissors = function(n) {
var rounds = n;
var results = [];
var weapons = ['rock', 'paper', 'scissors'];
var recurse = function(roundsLeft, played) {
if( roundsLeft === 0) {
results.push(played);
return;
}
for(var i = 0; i<weapons.length; i++) {
var current = weapons[i];
recurse( roundsLeft-1, played.concat(current) );
}
};
recurse(rounds; []);
return results;
}
```
I was wondering why the return statement is not written as:
```
return results.push(played);
```
Is there any benefits? If so, why and when should you write it that way? | 2015/12/02 | [
"https://Stackoverflow.com/questions/34051203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4785557/"
] | You don't need to find the item, you can use `wxMenuBar::IsChecked()`, which will do it for you, directly. And you can either just store the menu bar in `self.menuBar` or retrieve it from the frame using its `GetMenuBar()` method. | It's a bit convoluted, but not too bad. Basically you need to use the menu's `FindItem` method, which takes the string name of the menu item. This returns its id, which you can then use the menu's `FindItemById` method for. Here's a quick and dirty example:
```
import wx
########################################################################
class MyForm(wx.Frame):
""""""
#----------------------------------------------------------------------
def __init__(self):
"""Constructor"""
wx.Frame.__init__(self, None, title="wx.Menu Tutorial")
self.panel = wx.Panel(self, wx.ID_ANY)
# Create menu bar
menuBar = wx.MenuBar()
# create check menu
checkMenu = wx.Menu()
wgItem = checkMenu.Append(wx.NewId(), "Wells Fargo", "", wx.ITEM_CHECK)
self.Bind(wx.EVT_MENU, self.onFargo, wgItem)
citiItem = checkMenu.Append(wx.NewId(), "Citibank", "", wx.ITEM_CHECK)
geItem = checkMenu.Append(wx.NewId(), "GE Money Bank", "", wx.ITEM_CHECK)
menuBar.Append(checkMenu, "&Check")
# Attach menu bar to frame
self.SetMenuBar(menuBar)
#----------------------------------------------------------------------
def onFargo(self, event):
""""""
menu = event.GetEventObject()
item_id = menu.FindItem("Wells Fargo")
item = menu.FindItemById(item_id)
print item.IsChecked()
#----------------------------------------------------------------------
# Run the program
if __name__ == "__main__":
app = wx.App(False)
frame = MyForm().Show()
app.MainLoop()
``` |
34,051,203 | I had a question about the return statement that is by itself in the control flow.
```
var rockPaperScissors = function(n) {
var rounds = n;
var results = [];
var weapons = ['rock', 'paper', 'scissors'];
var recurse = function(roundsLeft, played) {
if( roundsLeft === 0) {
results.push(played);
return;
}
for(var i = 0; i<weapons.length; i++) {
var current = weapons[i];
recurse( roundsLeft-1, played.concat(current) );
}
};
recurse(rounds; []);
return results;
}
```
I was wondering why the return statement is not written as:
```
return results.push(played);
```
Is there any benefits? If so, why and when should you write it that way? | 2015/12/02 | [
"https://Stackoverflow.com/questions/34051203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4785557/"
] | It's a bit convoluted, but not too bad. Basically you need to use the menu's `FindItem` method, which takes the string name of the menu item. This returns its id, which you can then use the menu's `FindItemById` method for. Here's a quick and dirty example:
```
import wx
########################################################################
class MyForm(wx.Frame):
""""""
#----------------------------------------------------------------------
def __init__(self):
"""Constructor"""
wx.Frame.__init__(self, None, title="wx.Menu Tutorial")
self.panel = wx.Panel(self, wx.ID_ANY)
# Create menu bar
menuBar = wx.MenuBar()
# create check menu
checkMenu = wx.Menu()
wgItem = checkMenu.Append(wx.NewId(), "Wells Fargo", "", wx.ITEM_CHECK)
self.Bind(wx.EVT_MENU, self.onFargo, wgItem)
citiItem = checkMenu.Append(wx.NewId(), "Citibank", "", wx.ITEM_CHECK)
geItem = checkMenu.Append(wx.NewId(), "GE Money Bank", "", wx.ITEM_CHECK)
menuBar.Append(checkMenu, "&Check")
# Attach menu bar to frame
self.SetMenuBar(menuBar)
#----------------------------------------------------------------------
def onFargo(self, event):
""""""
menu = event.GetEventObject()
item_id = menu.FindItem("Wells Fargo")
item = menu.FindItemById(item_id)
print item.IsChecked()
#----------------------------------------------------------------------
# Run the program
if __name__ == "__main__":
app = wx.App(False)
frame = MyForm().Show()
app.MainLoop()
``` | Use the event to access the data you want.
```
print event.Id
print event.Selection # returns 1 if checked 0 if not checked
print event.IsChecked() # returns True if checked False if not checked
```
print out all of the attributes with:
```
print dir(event)
``` |
34,051,203 | I had a question about the return statement that is by itself in the control flow.
```
var rockPaperScissors = function(n) {
var rounds = n;
var results = [];
var weapons = ['rock', 'paper', 'scissors'];
var recurse = function(roundsLeft, played) {
if( roundsLeft === 0) {
results.push(played);
return;
}
for(var i = 0; i<weapons.length; i++) {
var current = weapons[i];
recurse( roundsLeft-1, played.concat(current) );
}
};
recurse(rounds; []);
return results;
}
```
I was wondering why the return statement is not written as:
```
return results.push(played);
```
Is there any benefits? If so, why and when should you write it that way? | 2015/12/02 | [
"https://Stackoverflow.com/questions/34051203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4785557/"
] | You don't need to find the item, you can use `wxMenuBar::IsChecked()`, which will do it for you, directly. And you can either just store the menu bar in `self.menuBar` or retrieve it from the frame using its `GetMenuBar()` method. | Use the event to access the data you want.
```
print event.Id
print event.Selection # returns 1 if checked 0 if not checked
print event.IsChecked() # returns True if checked False if not checked
```
print out all of the attributes with:
```
print dir(event)
``` |
73,752,793 | We are using ObjectMapper. When using ObjectMapper with RowMapper, should it be declared inside each mapRow (seen below), or outside of mapRow as a class public member? I assume it should be outside as a public class member per this article. [Should I declare Jackson's ObjectMapper as a static field?](https://stackoverflow.com/questions/3907929/should-i-declare-jacksons-objectmapper-as-a-static-field)
Currently using Spring boot with SQL Server database. Researching thread safety with thousands/millions of sql rows its getting.
```
List<Product> productList = namedParameterJdbcTemplate.query(sqlQuery,
parameters,
new ProductMapper(productRequest));
public class ProductMapper implements RowMapper<Product> {
@Override
public Product mapRow(ResultSet rs, int rowNum) throws SQLException {
ObjectMapper objectMapper = new ObjectMapper()
Product product = new Product();
product.setProductId(rs.getLong("ProductId"));
product.setProductType(rs.getString("ProductType"));
product.setLocations(objectMapper.readValue(rs.getString("Locations"), new TypeReference<List<ServiceLocation>>(){}));
} catch (Exception e) {
throw new ServiceException(e);
}
}
```
Note: Please don't ask why we are writing this manual mapper with ObjectMapper, we are doing legacy coding, and architects requested to do this. | 2022/09/17 | [
"https://Stackoverflow.com/questions/73752793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15435022/"
] | An [`ObjectMapper`](https://fasterxml.github.io/jackson-databind/javadoc/2.7/com/fasterxml/jackson/databind/ObjectMapper.html) instance is not immutable but, as stated in the documentation:
>
> Mapper instances are fully thread-safe provided that ALL configuration of the instance occurs before ANY
> read or write calls.
>
>
>
Which means that this code is perfectly thread-safe:
```
public class ProductMapper implements RowMapper<Product> {
private ObjectMapper mapper;
public ProductMapper()
{
objectMapper = new ObjectMapper();
}
@Override
public Product mapRow(ResultSet rs, int rowNum) throws SQLException {
Product product = new Product();
product.setLocations(objectMapper.readValue(rs.getString("Locations"), new TypeReference<List<ServiceLocation>>(){}));
return product;
}
}
```
However, the `TypeReference` object is still created for each row, which is not very efficient. A better way is to create
an [`ObjectReader`](https://fasterxml.github.io/jackson-databind/javadoc/2.7/com/fasterxml/jackson/databind/ObjectReader.html)
instance via the [`readerFor()`](https://fasterxml.github.io/jackson-databind/javadoc/2.7/com/fasterxml/jackson/databind/ObjectMapper.html#readerFor(com.fasterxml.jackson.core.type.TypeReference)) method:
```
public class ProductMapper implements RowMapper<Product> {
private ObjectReader objectReader;
public ProductMapper()
{
ObjectMapper objectMapper = new ObjectMapper();
objectReader = objectMapper.readerFor(new TypeReference<List<ServiceLocation>>(){});
}
@Override
public Product mapRow(ResultSet rs, int rowNum) throws SQLException {
Product product = new Product();
product.setLocations(objectReader.readValue(rs.getString("Locations")));
return product;
}
}
```
An `ObjectReader` instance is immutable and thread-safe. | Yes, probably you should declare it is a class level field.
It's never recommended to create redundant objects. |
19,666,102 | >
> A certain string-processing language offers a primitive operation which splits a string into two pieces. Since this operation involves copying the original string, it takes n units of time for a string of length n, regardless of the location of the cut. Suppose, now, that you want to break a string into many pieces. The order in which the breaks are made can affect the total running time. For example, if you want to cut a 20-character string at positions 3 and 10, then making the first cut at position 3 incurs a total cost of 20+17=37, while doing position 10 first has a better cost of 20+10=30.
>
>
> Give a dynamic programming algorithm that, given the locations of m cuts in a string of length n, finds the minimum cost of breaking the string into m + 1 pieces.
>
>
>
This problem is from "Algorithms" chapter6 6.9.
Since there is no answer for this problem, This is what I thought.
Define `OPT(i,j,n)` as the minimum cost of breaking the string, `i` for start index, `j` for end index of String and `n` for the remaining number of cut I can use.
Here is what I get:
`OPT(i,j,n) = min {OPT(i,k,w) + OPT(k+1,j,n-w) + j-i} for i<=k<j and 0<=w<=n`
Is it right or not? Please help, thx! | 2013/10/29 | [
"https://Stackoverflow.com/questions/19666102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2925372/"
] | I think your recurrence relation can become more better. Here's what I came up with, define cost(i,j) to be the cost of cutting the string from index i to j. Then,
```
cost(i,j) = min {length of substring + cost(i,k) + cost(k,j) where i < k < j}
``` | ```
void s_cut()
{
int l,p;
int temp=0;
//ArrayList<Integer> al = new ArrayList<Integer>();
int al[];
Scanner s=new Scanner(System.in);
int table[][];
ArrayList<Integer> values[][];
int low=0,high=0;
int min=0;
l=s.nextInt();
p=s.nextInt();
System.out.println("The values are "+l+" "+p);
table= new int[l+1][l+1];
values= new ArrayList[l+1][l+1];
al= new int[p];
for(int i=0;i<p;i++)
{
al[i]=s.nextInt();
}
for(int i=0;i<=l;i++)
for(int j=0;j<=l;j++)
values[i][j]=new ArrayList<Integer>();
System.out.println();
for(int i=1;i<=l;i++)
table[i][i]=0;
//Arrays.s
Arrays.sort(al);
for(int i=0;i<p;i++)
{
System.out.print(al[i]+ " ");
}
for(int len=2;len<=l;len++)
{
//System.out.println("The length is "+len);
for(int i=1,j=i+len-1;j<=l;i++,j++)
{
high= min_index(al,j-1);
low= max_index(al,i);
System.out.println("Indices are "+low+" "+high);
if(low<=high && low!=-1 && high!=-1)
{
int cost=Integer.MAX_VALUE;;
for(int k=low;k<=high;k++)
{
//if(al[k]!=j)
temp=cost;
cost=Math.min(cost, table[i][al[k]]+table[al[k]+1][j]);
if(temp!=cost)
{
min=k;
//values[i][j].add(al[k]);
//values[i][j].addAll(values[i][al[k]]);
//values[i][j].addAll(values[al[k]+1][j]);
//values[i][j].addAll(values[i][al[k]]);
}
//else
//cost=0;
}
table[i][j]= len+cost;
values[i][j].add(al[min]);
//values[i][j].addAll(values[i][al[min]]);
values[i][j].addAll(values[al[min]+1][j]);
values[i][j].addAll(values[i][al[min]]);
}
else
table[i][j]=0;
System.out.println(" values are "+i+" "+j+" "+table[i][j]);
}
}
System.out.println(" The minimum cost is "+table[1][l]);
//temp=values[1][l];
for(int e: values[1][l])
{
System.out.print(e+"-->");
}
}
```
The above solution has the complexity of O(n^3). |
54,794,538 | I have two dataframes
**df1**
```
+----+-------+
| | Key |
|----+-------|
| 0 | 30 |
| 1 | 31 |
| 2 | 32 |
| 3 | 33 |
| 4 | 34 |
| 5 | 35 |
+----+-------+
```
**df2**
```
+----+-------+--------+
| | Key | Test |
|----+-------+--------|
| 0 | 30 | Test4 |
| 1 | 30 | Test5 |
| 2 | 30 | Test6 |
| 3 | 31 | Test4 |
| 4 | 31 | Test5 |
| 5 | 31 | Test6 |
| 6 | 32 | Test3 |
| 7 | 33 | Test3 |
| 8 | 33 | Test3 |
| 9 | 34 | Test1 |
| 10 | 34 | Test1 |
| 11 | 34 | Test2 |
| 12 | 34 | Test3 |
| 13 | 34 | Test3 |
| 14 | 34 | Test3 |
| 15 | 35 | Test3 |
| 16 | 35 | Test3 |
| 17 | 35 | Test3 |
| 18 | 35 | Test3 |
| 19 | 35 | Test3 |
+----+-------+--------+
```
I want to count how many times each `Test` is listed for each `Key`.
```
+----+-------+-------+-------+-------+-------+-------+-------+
| | Key | Test1 | Test2 | Test3 | Test4 | Test5 | Test6 |
|----+-------|-------|-------|-------|-------|-------|-------|
| 0 | 30 | | | | 1 | 1 | 1 |
| 1 | 31 | | | | 1 | 1 | 1 |
| 2 | 32 | | | 1 | | | |
| 3 | 33 | | | 2 | | | |
| 4 | 34 | 2 | 1 | 3 | | | |
| 5 | 35 | | | 5 | | | |
+----+-------+-------+-------+-------+-------+-------+-------+
```
**What I've tried**
Using join and groupby, I first got the count for each `Key`, regardless of `Test`.
```
result_df = df1.join(df2.groupby('Key').size().rename('Count'), on='Key')
+----+-------+---------+
| | Key | Count |
|----+-------+---------|
| 0 | 30 | 3 |
| 1 | 31 | 3 |
| 2 | 32 | 1 |
| 3 | 33 | 2 |
| 4 | 34 | 6 |
| 5 | 35 | 5 |
+----+-------+---------+
```
I tried to group the `Key` with the `Test`
```
result_df = df1.join(df2.groupby(['Key', 'Test']).size().rename('Count'), on='Key')
```
but this returns an error
`ValueError: len(left_on) must equal the number of levels in the index of "right"` | 2019/02/20 | [
"https://Stackoverflow.com/questions/54794538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10540565/"
] | Check with `crosstab`
```
pd.crosstab(df2.Key,df2.Test).reindex(df1.Key).replace({0:''})
``` | Here another solution with groupby & pivot. Using this solution you don't need df1 at all.
```
# | create some dummy data
tests = ['Test' + str(i) for i in range(1,7)]
df = pd.DataFrame({'Test': np.random.choice(tests, size=100), 'Key': np.random.randint(30, 35, size=100)})
df['Count Variable'] = 1
# | group & count aggregation
df = df.groupby(['Key', 'Test']).count()
df = df.pivot(index="Key", columns="Test", values="Count Variable").reset_index()
``` |
4,712,335 | I want to convert a string which contains the date in `yyyyMMdd` format to `mm-dd-yyyy` DateTime format. How do I get it? | 2011/01/17 | [
"https://Stackoverflow.com/questions/4712335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/578083/"
] | ```
var dateString = "20050802";
var date = myDate = DateTime.ParseExact(dateString,
"yyyyMMdd",
System.Globalization.CultureInfo.InvariantCulture);
``` | ```
public static DateTime ConvertDate(string date, string pattern)
{
DateTime retval = DateTime.MinValue;
if (System.DateTime.TryParseExact(date, pattern, System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out retval))
return retval;
// Could not convert date..
return DateTime.MinValue;
}
DateTime myDate = ConvertDate("20101230", "yyyyMMdd");
``` |
4,712,335 | I want to convert a string which contains the date in `yyyyMMdd` format to `mm-dd-yyyy` DateTime format. How do I get it? | 2011/01/17 | [
"https://Stackoverflow.com/questions/4712335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/578083/"
] | ```
var dateString = "20050802";
var date = myDate = DateTime.ParseExact(dateString,
"yyyyMMdd",
System.Globalization.CultureInfo.InvariantCulture);
``` | ```
CultureInfo provider = CultureInfo.CreateSpecificCulture("en-UK");
string dateString = "19850121"; //in yyyyMMdd format
string oldFormat = "yyyyMMdd";
DateTime result = DateTime.ParseExact(dateString, oldFormat, provider); //MM/dd/yyyyformat
``` |
4,712,335 | I want to convert a string which contains the date in `yyyyMMdd` format to `mm-dd-yyyy` DateTime format. How do I get it? | 2011/01/17 | [
"https://Stackoverflow.com/questions/4712335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/578083/"
] | ```
public static DateTime ConvertDate(string date, string pattern)
{
DateTime retval = DateTime.MinValue;
if (System.DateTime.TryParseExact(date, pattern, System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out retval))
return retval;
// Could not convert date..
return DateTime.MinValue;
}
DateTime myDate = ConvertDate("20101230", "yyyyMMdd");
``` | ```
CultureInfo provider = CultureInfo.CreateSpecificCulture("en-UK");
string dateString = "19850121"; //in yyyyMMdd format
string oldFormat = "yyyyMMdd";
DateTime result = DateTime.ParseExact(dateString, oldFormat, provider); //MM/dd/yyyyformat
``` |
75,038 | I want it to perform good enough as a multimedia machine. Should I get one that is fan cooled or passively cooled? I think I want one with an HDMI port.
What chipset should I look for? | 2009/11/25 | [
"https://superuser.com/questions/75038",
"https://superuser.com",
"https://superuser.com/users/-1/"
] | I agree with an Ion chipset, there's really no competition in the quiet/ITX space. I've got one of [these](http://www.newegg.com/Product/Product.aspx?Item=N82E16813500035&cm_re=zotac-_-13-500-035-_-Product) powering a secondary HTPC for my bedroom. It has a [Celeron 430](http://www.newegg.com/Product/Product.aspx?Item=N82E16819116039) 35W chip in it, and it runs good and quiet. HD playback is no problem, once I got a codec that uses the hardware decoder instead of trying to shove it through the CPU.
My original thought was to go with the Atom 330 version of this board, but what I've seen about it lead me to believe that it would be too sluggish when using the VMC interface. 4 l-cores or not, its still an in-order architecture. If silence is more important to you, there are some Atom Zotac boards that are passively cooled, and have a power brick instead of a normal PSU. | If you want a really small system, look for a machine based on Nvidia ION - basically, it has a Atom CPU and can do 1080p output whilst keeping electricity usage low.
I have not seen many machines recently that are passively cooled, but a lot of the newer Atom boards have low noise fans. |
75,038 | I want it to perform good enough as a multimedia machine. Should I get one that is fan cooled or passively cooled? I think I want one with an HDMI port.
What chipset should I look for? | 2009/11/25 | [
"https://superuser.com/questions/75038",
"https://superuser.com",
"https://superuser.com/users/-1/"
] | I agree with an Ion chipset, there's really no competition in the quiet/ITX space. I've got one of [these](http://www.newegg.com/Product/Product.aspx?Item=N82E16813500035&cm_re=zotac-_-13-500-035-_-Product) powering a secondary HTPC for my bedroom. It has a [Celeron 430](http://www.newegg.com/Product/Product.aspx?Item=N82E16819116039) 35W chip in it, and it runs good and quiet. HD playback is no problem, once I got a codec that uses the hardware decoder instead of trying to shove it through the CPU.
My original thought was to go with the Atom 330 version of this board, but what I've seen about it lead me to believe that it would be too sluggish when using the VMC interface. 4 l-cores or not, its still an in-order architecture. If silence is more important to you, there are some Atom Zotac boards that are passively cooled, and have a power brick instead of a normal PSU. | +1 for an ion as a multimedia machine. low power (both CPU and Wattage) but with a graphics chipset that can hadnle FULL 1080p HD.
some even come with an HDMI port.
If you want a nice easy answer, some pre built ion nettops exist such as the Acer revo, or asus ionstar |
2,305 | Over on Twitter, @kelvinfichter [gave an analysis](https://twitter.com/kelvinfichter/status/1425217046636371969) (included below) of the recent Poly Network hack.
***Without any of the benefits of hindsight, are there reasons why the exploit would have been less likely to occur in Plutus on Cardano?***
>
> Poly has this contract called the `EthCrossChainManager`. It's basically a privileged contract that has the right to trigger messages from another chain. It's a pretty standard thing for cross-chain projects.
>
>
> There's this function `verifyHeaderAndExecuteTx` that anyone can call to execute a cross-chain transaction. Basically it:
>
>
> 1. Verifies that the block header is correct by checking signatures (seems the other chain was a poa sidechain or something) and... then
> 2. Checks that the transaction was included within that block with a Merkle proof. Here's the code, it's pretty simple: [EthCrossChainManager.sol#L127](https://github.com/polynetwork/eth-contracts/blob/d16252b2b857eecf8e558bd3e1f3bb14cff30e9b/contracts/core/cross_chain_manager/logic/EthCrossChainManager.sol#L127)
>
>
> One of the last things the function does is call `_executeCrossChainTx`, which actually makes the call to the target contract. Here's where the critical flaw sits.
>
>
> Poly checks that the target is a contract [EthCrossChainManager.sol#L185](https://github.com/polynetwork/eth-contracts/blob/d16252b2b857eecf8e558bd3e1f3bb14cff30e9b/contracts/core/cross_chain_manager/logic/EthCrossChainManager.sol#L185). But Poly forgot to prevent users from calling a very important target... the `EthCrossChainData` contract: [EthCrossChainData.sol](https://github.com/polynetwork/eth-contracts/blob/master/contracts/core/cross_chain_manager/data/EthCrossChainData.sol).
>
>
> Why is this target so important? It keeps track of the list of public keys that authenticate data coming from the other chain. If you can modify that list, you don't even need to hack private keys. You just set the public keys to match your own private keys. See here for where that list is tracked: [EthCrossChainData.sol#L22](https://github.com/polynetwork/eth-contracts/blob/d16252b2b857eecf8e558bd3e1f3bb14cff30e9b/contracts/core/cross_chain_manager/data/EthCrossChainData.sol#L22).
>
>
> So someone realized that they could send an cross-chain message directly to the `EthCrossChainData` contract.
>
>
> What good does that do them? Well, guess which contracted owned the EthCrossChainData contract... yep. The `EthCrossChainManager`. By sending this cross-chain message, the user could trick the `EthCrossChainManager` into calling the `EthCrossChainData` contract, passing the `onlyOwner` check.
>
>
> Now the user just had to craft the right data to be able to trigger the function that changes the public keys. Link to that function here: [EthCrossChainData.sol#L45](https://github.com/polynetwork/eth-contracts/blob/d16252b2b857eecf8e558bd3e1f3bb14cff30e9b/contracts/core/cross_chain_manager/data/EthCrossChainData.sol#L45).
>
>
> The only remaining challenge was to figure out how to make the `EthCrossChainManager` call the right function. Now comes a little bit of complexity around how Solidity picks which function you're trying to call.
>
>
> The first four bytes of transaction input data is called the "signature hash" or "sighash" for short. It's a short piece of information that tells a Solidity contract what you're trying to do. The sighash of a function is calculated by taking the first four bytes of the hash of "()".
>
>
> For example, the sighash of the ERC20 transfer function is the first four bytes of the hash of `transfer(address,uint256)`. Poly's contract was willing to call *any* contract. However, it would only call the contract function that corresponded to the following sighash: Errr but wait... `_method` here was user input.
>
>
> All the attacker had to do to call the right function was figure out *some* value for `_method` that, when combined with those other values and hashed, had the same leading four bytes as the sighash of our target function.
>
>
> With just a little bit of grinding, you can *easily* find some input that produces the right sighash. You don't need to find a full hash collision, you're only checking the first four bytes.
>
>
> So is this theory correct? Well... here's the actual sighash of the target function:
>
>
>
> ```
> > ethers.utils.id ('putCurEpochConPubKeyBytes(bytes)').slice(0, 10)
> '0x41973cd9'`
>
> ```
>
> And the sighash that the attacker crafted...
>
>
>
> ```
> > ethers.utils.id ('f1121318093(bytes,bytes,uint64)').slice(0, 10)
> '0x41973cd9'
>
> ```
>
> Fantastic. No private key compromise required! Just craft the right data and boom... the contract will just hack itself!
>
>
>
The author then goes on to [give lessons learned](https://twitter.com/kelvinfichter/status/1425220160814784512).
***Do Plutus developers also need to learn from these lessons or are they specific to Solidity?***
>
> One of the biggest design lessons that people need to take away from this is: if you have cross-chain relay contracts like this, MAKE SURE THAT THEY CAN'T BE USED TO CALL SPECIAL CONTRACTS.
>
>
> The `EthCrossDomainManager` shouldn't have owned the `EthCrossDomainData` contract. Separate concerns.
>
>
> If your contract absolutely need to have special privileges like this, make sure that users can't use cross-chain messages to call those special contracts.
>
>
> And just for good measure, here's the function to trigger a cross-chain message: [EthCrossChainManager.sol#L91](https://github.com/polynetwork/eth-contracts/blob/d16252b2b857eecf8e558bd3e1f3bb14cff30e9b/contracts/core/cross_chain_manager/logic/EthCrossChainManager.sol#L91). Nothing here prevents you from sending a message to the `EthCrossChainData` contract.
>
>
>
@kelvinfichter also gives a simplified summary of the attack: <https://twitter.com/kelvinfichter/status/1425290462076747777> | 2021/08/11 | [
"https://cardano.stackexchange.com/questions/2305",
"https://cardano.stackexchange.com",
"https://cardano.stackexchange.com/users/1903/"
] | This one is a bit technical it has to do with looking up and updating the constraints of an already existing transaction (that belongs to the script address). See Case ii) to skip my synopsis.
Just a little synopsis for future readers: The [`Core.hs`](https://github.com/input-output-hk/plutus-pioneer-program/blob/main/code/week06/src/Week06/Oracle/Core.hs) script is an Oracle, that has to update its datum regarding Ada price. The lines in which lookups occur are in the function `updateOracle` that has the purpose of building a transaction and then submitting it. To accomplish this the constraints need to refer to typed script inputs and outputs. In `updateOracle` we dealt with two cases
```
.
.
case m of
Nothing -> do
ledgerTx <- submitTxConstraints (typedOracleValidator oracle) c
.
.
Just (oref, o, _) -> do
let lookups = Constraints.unspentOutputs (Map.singleton oref o) <>
Constraints.typedValidatorLookups (typedOracleValidator oracle) <>
Constraints.otherScript (oracleValidator oracle)
tx = c <> Constraints.mustSpendScriptOutput oref (Redeemer $ PlutusTx.toBuiltinData Update)
ledgerTx <- submitTxConstraintsWith @Oracling lookups tx
.
.
```
* i) Create the Oracle (if it doesn't exists) at the same time of submission and add datum.
* ii) Just update the datum of an existing Oracle
Case i) uses `submitTxConstraints` which takes the constraints as inputs in the form of a script instance (with typed validator hash & the compiled program) and the locked value with the script.
Case ii) on the other hand, uses `submitTxConstraintsWith` which takes the updated constraints as `ScriptLookup` type rather than a script instance. To your question, we need to semigroup:
* `Constraints.typedValidatorLookups` (this gets the previous
parameters of the `ScriptLookup`)
* `Constraints.unspentOutputs` (updates `slTxOutputs` from
`ScriptLookup`, which are the unspent outputs that the script wants to
spend)
* `Constraints.otherScript` (updates `slOtherScripts` from
`ScriptLookup`, which are validators of the script other than our
script)
The reason why `Constraints.typedValidatorLookups` alone is not enough is because we would not be updating anything without semigrouping `ScriptLookup` element by element as defined in [`OffChain.hs`](https://github.com/input-output-hk/plutus/blob/master/plutus-ledger/src/Ledger/Constraints/OffChain.hs)) | I share your confusion around this. I think a lot of it is due to the flux in the codebase.
On the other hand, I don't think it is anything complicated. The main purpose of Lookups, and thus also those two lines is to supply information needed for the transaction.
I noted that `Constraints.otherScript` seems to be consistently used where a transaction consumes uTxOs and needs to supply the validator script.
Have a look at Lars explanation in the [Iteration #2 Lecture #6](https://www.youtube.com/watch?v=24SHPHEc3zo) video at 00:50h. In it he mentions that two scripts need to be supplied: one for the input uTxO (consume) and one for output uTxO. This explains why there are two entries, and my guess is that otherScript entry is to be able to consume a script uTxO. |
72,528,078 | I have a csv file that looks like:
```
,,,,,,,,
,,,,a,b,c,d,e
,,,"01.01.2022, 00:00 - 01:00",82.7,57.98,0.0,0.0,0.0
,,,"01.01.2022, 01:00 - 02:00",87.6,50.05,15.0,25.570000000000004,383.55000000000007
,,,"01.01.2022, 02:00 - 03:00",87.6,41.33,0.0,0.0,0.0
```
And I want to import headers first and then the data, and finally insert headers to the names of the table with data
```
file <- "path"
pnl <- read.csv(file, dec = ",") #, skip = 1, header = TRUE)
headers <- read.csv(file, skip = 1, header = F, nrows = 1, as.is = T)
df <- read.csv(file, skip = 2, header = F, as.is = T)
#or this
#df <- read.csv(file, skip = 2, header = F, nrow = 1,dec = ".",sep=",", quote = "\"")
colnames(df) <- headers
```
When importing headers I have multiple columns with the headers entries. However, when importing table all entries are put inside one column, the same as in csv file (should be multiple columns). How can I solve it with read.csv() function? | 2022/06/07 | [
"https://Stackoverflow.com/questions/72528078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15184843/"
] | like this?
```
data.table::fread(',,,,,,,,
,,,,a,b,c,d,e
,,,"01.01.2022, 00:00 - 01:00",82.7,57.98,0.0,0.0,0.0
,,,"01.01.2022, 01:00 - 02:00",87.6,50.05,15.0,25.570000000000004,383.55000000000007
,,,"01.01.2022, 02:00 - 03:00",87.6,41.33,0.0,0.0,0.0',
skip = 1)
V1 V2 V3 V4 a b c d e
1: NA NA NA 01.01.2022, 00:00 - 01:00 82.7 57.98 0 0.00 0.00
2: NA NA NA 01.01.2022, 01:00 - 02:00 87.6 50.05 15 25.57 383.55
3: NA NA NA 01.01.2022, 02:00 - 03:00 87.6 41.33 0 0.00 0.00
``` | Without using any libraries:
```r
colClasses <- c("NULL", "NULL", "NULL", "character", "numeric", "numeric", "numeric", "numeric")
read.csv(file, header = TRUE, skip = 1, colClasses = colClasses)
# X.3 a b c d
# 1 01.01.2022, 00:00 - 01:00 82.7 57.98 0 0.00
# 2 01.01.2022, 01:00 - 02:00 87.6 50.05 15 25.57
# 3 01.01.2022, 02:00 - 03:00 87.6 41.33 0 0.00
```
You will want to rename the first column. |
3,349,400 | I have a question, which might also fit on stackoverflow, but due to I think I made some mistake in my mathematical considerations I think math.stackexchange is more proper for my question.
Currently I'm writing a (python) program, where a small part of it deals with matrix logarithms. Due to I'm looking for a mistake, I could locate the error in the program part, which does the matrix logarithm. While looking where exactly the error might be, I got quite unsure whether my notion about matrix logarithm is correct.
For testing purposes I calculate the matrix logarithm by using scipy.linalg.logm() and some matrices, which are derived from random matrices. To ensure, that the input has full rank, I add $\delta \cdot \mathbf{1}$ for some little $\delta > 0$.
Although I insert a real matrix $M$, most of the time $logm(M)$ is complex valued. The complex values don't seem to be numerical artefacts, since their magnitude is the same as the magnitude of the real values.
My question now is, whether it can be correct, that real matrices have complex logarithms?
On the one hand I know, that logm uses approximations, since not all matrices are can be diagonalized. According to the sourcecode logm uses techniques from Nicholas J. Higham's "Functions of Matrices: Theory and Computation", so (beside the fact, that scipy is tested quite well) I think the algorithm works correctly.
On the other hand both ways of calculating matrix logarithm I know about (diagonalizing and power series, which both of course don't work in all cases) give real logarithms for real matrices. So, since complex logarithms for real matrices don't occur in this cases, I cannot imagine whether such a result might be correct.
Does anyone have some argument which can confirm or deny my concerns?
Or do I have to look for the problem in the program code, as my cosiderations are correct?
Thanks in advance! | 2019/09/09 | [
"https://math.stackexchange.com/questions/3349400",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/432130/"
] | Well, a quick search revealed the following answer (from [Wikipedia](https://en.wikipedia.org/wiki/Logarithm_of_a_matrix)):
>
> The answer is more involved in the real setting. **A real matrix has a real logarithm if and only if it is invertible and each Jordan block belonging to a negative eigenvalue occurs an even number of times.** If an invertible real matrix does not satisfy the condition with the Jordan blocks, then it has only non-real logarithms. This can already be seen in the scalar case: no branch of the logarithm can be real at -1. The existence of real matrix logarithms of real 2×2 matrices is considered in a later section.
>
>
>
You should check if in your case you verify the property underlined above. | It's clear that the logarithm of a real matrix *can* be complex; for example if $A=[-1]$ then $\log A=[\log -1]$. For equally simple $n\times n$ examples with $n>1$ consider diagonal matrices... |
66,025,267 | On Qt Creator `Tools`>`Options`>`Build & Run`>`Default Build Properties` the `Default build directory`
has the value defined in terms of variables
```
../%{JS: Util.asciify("_build-%{CurrentProject:Name}-%{CurrentKit:FileSystemName}-%{CurrentBuild:Name}")}
```
which result in something like
```
_build-Project1-Desktop_Qt_5_15_2_MSVC2019_64bit-Debug
```
1. From where those variables (CurrentProject:Name, CurrentKit:FileSystemName and CurrentBuild:Name) come from?
2. I would like to generate something different (shorter), perhaps like
`_x86-debug` or `_x86d` or `_x64-debug` or `_x64d`
which variables should I look for? | 2021/02/03 | [
"https://Stackoverflow.com/questions/66025267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5082463/"
] | This worked for me.
```
:host ::ng-deep .multiselect-dropdown .dropdown-btn {
padding: 6px 24px 6px 12px !important;
}
``` | ```
.multiselect-dropdown .dropdown-btn {
padding :6px 12px !important;
}
``` |
66,025,267 | On Qt Creator `Tools`>`Options`>`Build & Run`>`Default Build Properties` the `Default build directory`
has the value defined in terms of variables
```
../%{JS: Util.asciify("_build-%{CurrentProject:Name}-%{CurrentKit:FileSystemName}-%{CurrentBuild:Name}")}
```
which result in something like
```
_build-Project1-Desktop_Qt_5_15_2_MSVC2019_64bit-Debug
```
1. From where those variables (CurrentProject:Name, CurrentKit:FileSystemName and CurrentBuild:Name) come from?
2. I would like to generate something different (shorter), perhaps like
`_x86-debug` or `_x86d` or `_x64-debug` or `_x64d`
which variables should I look for? | 2021/02/03 | [
"https://Stackoverflow.com/questions/66025267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5082463/"
] | This worked for me.
```
:host ::ng-deep .multiselect-dropdown .dropdown-btn {
padding: 6px 24px 6px 12px !important;
}
``` | This worked for me.
```
:host ::ng-deep .multiselect-dropdown .dropdown-btn .selected-item {
width: 90%;
}
``` |
29,413,180 | I have a multiple select option that display the result in a div container, when click on ctrl+"orange""apple""banana" the result display: "orange, apple, banana" in one line, but i want to display each result in a new single line with a link that goes to different page like this:
Orange - "goes to a link"
Apple - "goes to a link"
Banana - "goes to a link"
Here are my codes below:
```
<script src="jquery-mobile/jquery-1.8.3.min.js" type="text/javascript">
</script>
<select name="" multiple="multiple" id="select-custom-19">
<option>Add Fruits</option>
<option value="orange" selected>orange</option>
<option value="apple">apple</option>
<option value="banana">banana</option> </select>
<div style="width:300px; height:70px; background-color:#E1D903;
color:#000000; margin: 10px; "> <span id="yourfruit"> </span>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#select-custom-19').change(function() {
/* setting currently changed option value to option variable */
var option = $(this).find('option:selected').val();
/* setting input box value to selected option value */
$('#yourfruit').text($(this).val());
});
});
</script>
```
your help will be highly appreciated.
Thanks | 2015/04/02 | [
"https://Stackoverflow.com/questions/29413180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4742303/"
] | You can try adding `<br/>` element after every selected option. I have used `<label>` element but you can add link or any other element you want
```
$(document).ready( function ()
{
$('#select-custom-19').change(function(){
$('#yourfruit').empty();
var values = $(this).val();
for(var i=0; i < values.length ; i++)
{
$('#yourfruit').append('<lable>'+values[i]+'</label><br/>');
}
});
});
```
**[JSFiddle Demo](http://jsfiddle.net/yqjwa93d/5/)** | try below
```
<script src="jquery-mobile/jquery-1.8.3.min.js" type="text/javascript"></script>
<select name="" multiple="multiple" id="select-custom-19">
<option>Add Fruits</option>
<option value="orange" selected>orange</option>
<option value="apple">apple</option>
<option value="banana">banana</option>
</select>
<div style="width:300px; height:70px; background-color:#E1D903; color:#000000; margin: 10px; ">
<ul id="yourfruit">
</ul>
</div>
<script type="text/javascript">
$(document).ready( function ()
{
$('#select-custom-19').change(function()
{
/* setting currently changed option value to option variable */
var option = $(this).find('option:selected').val();
/* setting input box value to selected option value */
$('#yourfruit').append('<li>'+$(this).val()+'</li>');
}
);
});
</script>
``` |
29,413,180 | I have a multiple select option that display the result in a div container, when click on ctrl+"orange""apple""banana" the result display: "orange, apple, banana" in one line, but i want to display each result in a new single line with a link that goes to different page like this:
Orange - "goes to a link"
Apple - "goes to a link"
Banana - "goes to a link"
Here are my codes below:
```
<script src="jquery-mobile/jquery-1.8.3.min.js" type="text/javascript">
</script>
<select name="" multiple="multiple" id="select-custom-19">
<option>Add Fruits</option>
<option value="orange" selected>orange</option>
<option value="apple">apple</option>
<option value="banana">banana</option> </select>
<div style="width:300px; height:70px; background-color:#E1D903;
color:#000000; margin: 10px; "> <span id="yourfruit"> </span>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#select-custom-19').change(function() {
/* setting currently changed option value to option variable */
var option = $(this).find('option:selected').val();
/* setting input box value to selected option value */
$('#yourfruit').text($(this).val());
});
});
</script>
```
your help will be highly appreciated.
Thanks | 2015/04/02 | [
"https://Stackoverflow.com/questions/29413180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4742303/"
] | You can iterate throug items and display them, append an anchor (`<a />`) and use `<br />` for a new line.
Make sure to add `.empty()` to clean the fruits from list before `.append()` other items to `$('#yourfruit')`, like in example below.
```
var fruits = $(this).val();
$('#yourfruit').empty();
for (var fruit in fruits) {
var label = $('<label/> ').text(fruits[fruit]+" - ");
$('#yourfruit').append(label)
.append($('<a class="tab-btn" />').text(fruits[fruit]).attr('href', fruits[fruit] + '.html'))
.append('<br />');
}
```
```js
$(document).ready(function() {
$('#select-custom-19').change(function() {
/* setting currently changed option value to option variable */
var option = $(this).find('option:selected').val();
/* setting input box value to selected option value */
var fruits = $(this).val();
$('#yourfruit').empty();
for (var fruit in fruits) {
var label = $('<label/> ').text(fruits[fruit] + " - ");
$('#yourfruit').append(label)
.append($('<a class="tab-btn" />').text(fruits[fruit]).attr('href', fruits[fruit] + '.html'))
.append('<br />');
}
});
});
```
```css
.tab-btn {
color: red;
}
.tab-btn:hover {
color: blue;
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="" multiple="multiple" id="select-custom-19">
<option>Add Fruits</option>
<option value="orange" selected>orange</option>
<option value="apple">apple</option>
<option value="banana">banana</option>
</select>
<div style="width:300px; height:70px; background-color:#E1D903;
color:#000000; margin: 10px; ">
<span id="yourfruit"> </span>
</div>
``` | try below
```
<script src="jquery-mobile/jquery-1.8.3.min.js" type="text/javascript"></script>
<select name="" multiple="multiple" id="select-custom-19">
<option>Add Fruits</option>
<option value="orange" selected>orange</option>
<option value="apple">apple</option>
<option value="banana">banana</option>
</select>
<div style="width:300px; height:70px; background-color:#E1D903; color:#000000; margin: 10px; ">
<ul id="yourfruit">
</ul>
</div>
<script type="text/javascript">
$(document).ready( function ()
{
$('#select-custom-19').change(function()
{
/* setting currently changed option value to option variable */
var option = $(this).find('option:selected').val();
/* setting input box value to selected option value */
$('#yourfruit').append('<li>'+$(this).val()+'</li>');
}
);
});
</script>
``` |
29,413,180 | I have a multiple select option that display the result in a div container, when click on ctrl+"orange""apple""banana" the result display: "orange, apple, banana" in one line, but i want to display each result in a new single line with a link that goes to different page like this:
Orange - "goes to a link"
Apple - "goes to a link"
Banana - "goes to a link"
Here are my codes below:
```
<script src="jquery-mobile/jquery-1.8.3.min.js" type="text/javascript">
</script>
<select name="" multiple="multiple" id="select-custom-19">
<option>Add Fruits</option>
<option value="orange" selected>orange</option>
<option value="apple">apple</option>
<option value="banana">banana</option> </select>
<div style="width:300px; height:70px; background-color:#E1D903;
color:#000000; margin: 10px; "> <span id="yourfruit"> </span>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#select-custom-19').change(function() {
/* setting currently changed option value to option variable */
var option = $(this).find('option:selected').val();
/* setting input box value to selected option value */
$('#yourfruit').text($(this).val());
});
});
</script>
```
your help will be highly appreciated.
Thanks | 2015/04/02 | [
"https://Stackoverflow.com/questions/29413180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4742303/"
] | You can try adding `<br/>` element after every selected option. I have used `<label>` element but you can add link or any other element you want
```
$(document).ready( function ()
{
$('#select-custom-19').change(function(){
$('#yourfruit').empty();
var values = $(this).val();
for(var i=0; i < values.length ; i++)
{
$('#yourfruit').append('<lable>'+values[i]+'</label><br/>');
}
});
});
```
**[JSFiddle Demo](http://jsfiddle.net/yqjwa93d/5/)** | You may add `HTML` tags as per your requirements, like `<a>` or `</br>`
```js
$(document).ready(function () {
$('#select-custom-19').change(function () {
$('#yourfruit').text("");
if($(this).val() != null)
{
$(this).val().forEach(function (value, index) {
$('#yourfruit').append("<a href='#'>" + value + "</a></br>");
});
}
});
});
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<select name="" multiple="multiple" id="select-custom-19">
<option>Add Fruits</option>
<option value="orange" selected>orange</option>
<option value="apple">apple</option>
<option value="banana">banana</option>
</select>
<div style="width:300px; height:70px; background-color:#E1D903;
color:#000000; margin: 10px; "> <span id="yourfruit"> </span>
</div>
``` |
29,413,180 | I have a multiple select option that display the result in a div container, when click on ctrl+"orange""apple""banana" the result display: "orange, apple, banana" in one line, but i want to display each result in a new single line with a link that goes to different page like this:
Orange - "goes to a link"
Apple - "goes to a link"
Banana - "goes to a link"
Here are my codes below:
```
<script src="jquery-mobile/jquery-1.8.3.min.js" type="text/javascript">
</script>
<select name="" multiple="multiple" id="select-custom-19">
<option>Add Fruits</option>
<option value="orange" selected>orange</option>
<option value="apple">apple</option>
<option value="banana">banana</option> </select>
<div style="width:300px; height:70px; background-color:#E1D903;
color:#000000; margin: 10px; "> <span id="yourfruit"> </span>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#select-custom-19').change(function() {
/* setting currently changed option value to option variable */
var option = $(this).find('option:selected').val();
/* setting input box value to selected option value */
$('#yourfruit').text($(this).val());
});
});
</script>
```
your help will be highly appreciated.
Thanks | 2015/04/02 | [
"https://Stackoverflow.com/questions/29413180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4742303/"
] | You can iterate throug items and display them, append an anchor (`<a />`) and use `<br />` for a new line.
Make sure to add `.empty()` to clean the fruits from list before `.append()` other items to `$('#yourfruit')`, like in example below.
```
var fruits = $(this).val();
$('#yourfruit').empty();
for (var fruit in fruits) {
var label = $('<label/> ').text(fruits[fruit]+" - ");
$('#yourfruit').append(label)
.append($('<a class="tab-btn" />').text(fruits[fruit]).attr('href', fruits[fruit] + '.html'))
.append('<br />');
}
```
```js
$(document).ready(function() {
$('#select-custom-19').change(function() {
/* setting currently changed option value to option variable */
var option = $(this).find('option:selected').val();
/* setting input box value to selected option value */
var fruits = $(this).val();
$('#yourfruit').empty();
for (var fruit in fruits) {
var label = $('<label/> ').text(fruits[fruit] + " - ");
$('#yourfruit').append(label)
.append($('<a class="tab-btn" />').text(fruits[fruit]).attr('href', fruits[fruit] + '.html'))
.append('<br />');
}
});
});
```
```css
.tab-btn {
color: red;
}
.tab-btn:hover {
color: blue;
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="" multiple="multiple" id="select-custom-19">
<option>Add Fruits</option>
<option value="orange" selected>orange</option>
<option value="apple">apple</option>
<option value="banana">banana</option>
</select>
<div style="width:300px; height:70px; background-color:#E1D903;
color:#000000; margin: 10px; ">
<span id="yourfruit"> </span>
</div>
``` | You may add `HTML` tags as per your requirements, like `<a>` or `</br>`
```js
$(document).ready(function () {
$('#select-custom-19').change(function () {
$('#yourfruit').text("");
if($(this).val() != null)
{
$(this).val().forEach(function (value, index) {
$('#yourfruit').append("<a href='#'>" + value + "</a></br>");
});
}
});
});
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<select name="" multiple="multiple" id="select-custom-19">
<option>Add Fruits</option>
<option value="orange" selected>orange</option>
<option value="apple">apple</option>
<option value="banana">banana</option>
</select>
<div style="width:300px; height:70px; background-color:#E1D903;
color:#000000; margin: 10px; "> <span id="yourfruit"> </span>
</div>
``` |
72,889,130 | I am currently doing the US Medical Insurance Cost Portfolio Project through Code Academy and am having trouble combining two lists into a single dictionary. I created two new lists (`smoking_status` and `insurance_costs`) in hope of investigating how insurance costs differ between smokers and non-smokers. When I try to zip these two lists together, however, the new dictionary only has two components. It should have well over a thousand. Where did I go wrong? Below is my code and output. It is worth nothing that the output seen is the last two data points in my original csv file.
```
import csv
insurance_db =
with open('insurance.csv',newline='') as insurance_csv:
insurance_reader = csv.DictReader(insurance_csv)
for row in insurance_reader:
insurance_db.append(row)
smoking_status = []
for person in insurance_db:
smoking_status.append(person.get('smoker'))
insurance_costs = []
for person in insurance_db:
insurance_costs.append(person.get('charges'))
smoker_dictionary = {key:value for key,value in zip(smoking_status,insurance_costs)}
print(smoker_dictionary)
```
Output:
```none
{'yes': '29141.3603', 'no': '2007.945'}
``` | 2022/07/06 | [
"https://Stackoverflow.com/questions/72889130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19497618/"
] | >
> Is there a way to update Progressbar from another thread
>
>
>
Short answer: No. A control can only be updated on the thread on which it was originally created.
What you can do is to display the `ProgressBar` in another window that runs on another thread and then close this window when the `RichTextBox` on the original thread has been updated. | Create a method on your form to update the element you want to update and use invoke to run it from your thread
like that:
```
private void Form1_Load(object sender, EventArgs e)
{
Thread _thread = new Thread(() =>
{
//do some work
upDateUiElements();//pass any parameters you want
});
_thread.Start();
}
public void upDateUiElements()//input any parameters you need
{
BeginInvoke(new MethodInvoker(() =>
{
//update ui elements
}));
}
```
If you need to invoke it from a different class you can pass your form as an object and then access the method through that object
Like that:
```
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
OtherClass _class = new OtherClass(this);
_class.runthread();
}
public void upDateUiElements()//input any parameters you need
{
BeginInvoke(new MethodInvoker(() =>
{
//update ui elements
}));
}
}
class OtherClass
{
private Form1 _accessForm1;
public OtherClass(Form1 accessform1)
{
_accessForm1 = accessform1;
}
public void runthread()
{
Thread _thread = new Thread(() =>
{
//do some work
_accessForm1.upDateUiElements();
});
_thread.Start();
}
}
``` |
72,889,130 | I am currently doing the US Medical Insurance Cost Portfolio Project through Code Academy and am having trouble combining two lists into a single dictionary. I created two new lists (`smoking_status` and `insurance_costs`) in hope of investigating how insurance costs differ between smokers and non-smokers. When I try to zip these two lists together, however, the new dictionary only has two components. It should have well over a thousand. Where did I go wrong? Below is my code and output. It is worth nothing that the output seen is the last two data points in my original csv file.
```
import csv
insurance_db =
with open('insurance.csv',newline='') as insurance_csv:
insurance_reader = csv.DictReader(insurance_csv)
for row in insurance_reader:
insurance_db.append(row)
smoking_status = []
for person in insurance_db:
smoking_status.append(person.get('smoker'))
insurance_costs = []
for person in insurance_db:
insurance_costs.append(person.get('charges'))
smoker_dictionary = {key:value for key,value in zip(smoking_status,insurance_costs)}
print(smoker_dictionary)
```
Output:
```none
{'yes': '29141.3603', 'no': '2007.945'}
``` | 2022/07/06 | [
"https://Stackoverflow.com/questions/72889130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19497618/"
] | >
> Is there a way to update Progressbar from another thread
>
>
>
Short answer: No. A control can only be updated on the thread on which it was originally created.
What you can do is to display the `ProgressBar` in another window that runs on another thread and then close this window when the `RichTextBox` on the original thread has been updated. | You can add this to your usings:
```
using System.Windows.Threading;
```
For .NET 5/6, that is enough. For .NET framework you must also add a reference to `System.Windows.Presentation.dll`.
And this type of code will work fine:
```
private void Button_Click(object sender, RoutedEventArgs e)
{
// here we're in UI thread
var max = 100;
pg.Maximum = max; // pg is a progress bar
Task.Run(() =>
{
// here we're in another thread
for (var i = 0; i < max; i++)
{
Thread.Sleep(100);
// this needs the System.Windows.Threading using to support lambda expressions
Dispatcher.BeginInvoke(() =>
{
// this will run in UI thread
pg.Value = i;
});
}
});
}
``` |
26,480,683 | I used code for sum cells of `datagridview1` like below
```
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
int sum = 0;
for (i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
if (dataGridView1.Rows[i].Cells[0].Value != null)
{
sum += Convert.ToInt32(dataGridView1.Rows[i].Cells[0].Value.ToString());
label1.Text = Convert.ToString(sum);
}
}
}
```
but i want my `cell[0].value` sum is shown in `label1` is ok like below,but if i can use multiplied by any numbers in other cells like below image the answer should be = `60`
see below details how its come
>
> 5+4 = 9 \* 2 = 18
>
>
> (18+2) \* 3 = 60
>
>
>
 | 2014/10/21 | [
"https://Stackoverflow.com/questions/26480683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4085654/"
] | Try this solution:
```
int sum = 0;
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
//for 1st column
if (dataGridView1.Rows[i].Cells[0].Value != null && !String.IsNullOrEmpty(dataGridView1.Rows[i].Cells[0].Value.ToString()))
sum += Convert.ToInt32(dataGridView1.Rows[i].Cells[0].Value.ToString());
//for 2nd column
if (dataGridView1.Rows[i].Cells[1].Value != null && !String.IsNullOrEmpty(dataGridView1.Rows[i].Cells[1].Value.ToString()))
sum *= Convert.ToInt32(dataGridView1.Rows[i].Cells[1].Value.ToString());
//for 3rd column
if (dataGridView1.Rows[i].Cells[2].Value != null && !String.IsNullOrEmpty(dataGridView1.Rows[i].Cells[2].Value.ToString()))
sum *= Convert.ToInt32(dataGridView1.Rows[i].Cells[2].Value.ToString());
}
label1.Text = Convert.ToString(sum);
```
Assign `sum` to `label1` after all calculations. Its useless to do it in every iteration. | I think i have a solution for you, but it requires a Gridview, and not a datagridview so leave a comment if you will use it otherwise ill delete this.
```
foreach(GridViewRow row in gridCriteria.Rows)
{
foreach(TableCell cell in row.Cells)
{
if(cell.Text != "")
{
int indexOf = row.Cells.GetCellIndex(cell);
if(indexOf == 0)
{
Sum += Convert.ToInt32(cell.Text);
}
else
{
Sum *= Convert.ToInt32(cell.Text);
}
}
}
}
``` |
49,646,601 | So I've literally copy-pasted the code from <https://codepen.io/hellokatili/pen/rVvMZb> (HTML in a template, CSS in styles.css and JS using this plugin <https://wordpress.org/plugins/header-and-footer-scripts/>)
I added the JS script within tags.
Here is the above code from codepen (after converting from HAML to HTML and SCSS to CSS).
HTML:
```
> <div class="content">
<script type="text/javascript"> </script>
<div class="slider single-item">
> <div class="quote-container">
> <div class="portrait octogon">
> <img src="http://www.tuacahntech.com/uploads/6/1/7/9/6179841/6166205_orig.jpg"/>
> </div>
> <div class="quote">
> <blockquote>
> <p>Meditation shabby chic master cleanse banh mi Godard. Asymmetrical Wes Anderson Intelligentsia you probably haven't heard of
> them.</p>
> <cite>
> <span>Kristi McSweeney</span>
> <br/>
> Thundercats twee
> <br/>
> Austin selvage beard
> </cite>
> </blockquote>
> </div>
> </div>
> <div class="quote-container">
> <div class="portrait octogon">
> <img src="http://static1.squarespace.com/static/51579fb2e4b0fc0d9469ff97/56cc83dfe707ebc39cf3269f/56d0b59e27d4bde4665fded3/1457365822199/"/>
> </div>
> <div class="quote">
> <blockquote>
> <p>Bespoke occupy cred seitan. Austin street art freegan Truffaut leggings aesthetic, salvia chia Brooklyn flexitarian.
> Single-origin coffee before they sold out health goth, cornhole irony
> keffiyeh Austin taxidermy mlkshk blog trust fund banh mi you probably
> haven't heard of them.</p>
> <cite>
> <span>Dina Anderson</span>
> <br/>
> Blue Bottle keffiyeh
> <br/>
> Sartorial locavore Schlitz ennui
> </cite>
> </blockquote>
> </div>
> </div> </div> </div> <svg> <defs>
> <clipPath clipPathUnits="objectBoundingBox" id="octogon">
> <polygon points="0.50001 0.00000, 0.61887 0.06700, 0.75011 0.06721, 0.81942 0.18444, 0.93300 0.25001, 0.93441 0.38641, 1.00000 0.49999, 0.93300 0.61887, 0.93300 0.75002, 0.81556 0.81944, 0.74999 0.93302, 0.61357 0.93444, 0.50001 1.00000, 0.38118 0.93302, 0.24998 0.93302, 0.18056 0.81556, 0.06700 0.74899, 0.06559 0.61359, 0.00000 0.49999, 0.06700 0.38111, 0.06700 0.25001, 0.18440 0.18058, 0.25043 0.06700, 0.38641 0.06559, 0.50001 0.00000"></polygon>
> </clipPath> </defs> </svg>
```
CSS:
```
html {
height: 100%;
}
body {
background: linear-gradient(130deg, #1abc9c, #d1f2eb);
background-size: 400% 400%;
-webkit-animation: gradient 16s ease infinite;
-moz-animation: gradient 16s ease infinite;
animation: gradient 16s ease infinite;
}
.content {
margin: auto;
padding: 20px;
width: 80%;
max-width: 1200px;
min-width: 300px;
}
.slick-slider {
margin: 30px auto 50px;
}
.slick-prev, .slick-next {
color: white;
opacity: 1;
height: 40px;
width: 40px;
margin-top: -20px;
}
.slick-prev path, .slick-next path {
fill: rgba(255, 255, 255, 0.4);
}
.slick-prev:hover path, .slick-next:hover path {
fill: #fff;
}
.slick-prev {
left: -35px;
}
.slick-next {
right: -35px;
}
.slick-prev:before, .slick-next:before {
content: none;
}
.slick-dots li button:before {
color: rgba(255, 255, 255, 0.4);
opacity: 1;
font-size: 8px;
}
.slick-dots li.slick-active button:before {
color: #fff;
}
.quote-container {
min-height: 200px;
color: #666;
font-size: 36px;
margin: 0 20px;
position: relative;
}
.quote-container:hover {
cursor: grab;
}
.quote-container .portrait {
position: absolute;
top: 0;
bottom: 0;
margin: auto;
height: 140px;
width: 140px;
overflow: hidden;
}
.quote-container .portrait img {
display: block;
height: auto;
width: 100%;
}
.quote-container .quote {
position: relative;
z-index: 600;
padding: 40px 0 40px 180px;
margin: 0;
font-size: 20px;
font-style: italic;
line-height: 1.4 !important;
font-family: Calibri;
color: white;
}
.quote-container .quote p {
position: relative;
margin-bottom: 20px;
}
.quote-container .quote p:first-child:before {
content: '\201C';
color: rgba(255, 255, 255, 0.44);
font-size: 7.5em;
font-weight: 700;
opacity: 1;
position: absolute;
top: -0.4em;
left: -0.2em;
text-shadow: none;
z-index: -10;
}
.quote-container .quote cite {
display: block;
font-size: 14px;
}
.quote-container .quote cite span {
font-size: 16px;
font-style: normal;
letter-spacing: 1px;
text-transform: uppercase;
}
.dragging .quote-container {
cursor: grabbing;
}
.octogon {
-webkit-clip-path: polygon(50% 0%, 38.11% 6.7%, 24.99% 6.72%, 18.06% 18.44%, 6.7% 25%, 6.56% 38.64%, 0% 50%, 6.7% 61.89%, 6.7% 75%, 18.44% 81.94%, 25% 93.3%, 38.64% 93.44%, 50% 100%, 61.88% 93.3%, 75% 93.3%, 81.94% 81.56%, 93.3% 74.9%, 93.44% 61.36%, 100% 50%, 93.3% 38.11%, 93.3% 25%, 81.56% 18.06%, 74.96% 6.7%, 61.36% 6.56%, 50% 0%);
clip-path: url(#octogon);
height: 140px;
width: 140px;
}
@-webkit-keyframes gradient {
0% {
background-position: 5% 0%;
}
50% {
background-position: 96% 100%;
}
100% {
background-position: 5% 0%;
}
}
@-moz-keyframes gradient {
0% {
background-position: 5% 0%;
}
50% {
background-position: 96% 100%;
}
100% {
background-position: 5% 0%;
}
}
@keyframes gradient {
0% {
background-position: 5% 0%;
}
50% {
background-position: 96% 100%;
}
100% {
background-position: 5% 0%;
}
}
```
JS:
```
var prevButton = '<button type="button" data-role="none" class="slick-prev" aria-label="prev"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" version="1.1"><path fill="#FFFFFF" d="M 16,16.46 11.415,11.875 16,7.29 14.585,5.875 l -6,6 6,6 z" /></svg></button>',
nextButton = '<button type="button" data-role="none" class="slick-next" aria-label="next"><svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path fill="#FFFFFF" d="M8.585 16.46l4.585-4.585-4.585-4.585 1.415-1.415 6 6-6 6z"></path></svg></button>';
$('.single-item').slick({
infinite: true,
dots: true,
autoplay: true,
autoplaySpeed: 4000,
speed: 1000,
cssEase: 'ease-in-out',
prevArrow: prevButton,
nextArrow: nextButton
});
$('.quote-container').mousedown(function(){
$('.single-item').addClass('dragging');
});
$('.quote-container').mouseup(function(){
$('.single-item').removeClass('dragging');
});
```
The HTML and CSS part work fine but the JS isn't functioning. I'm using a different JS script on the same WP site and it works just fine. Is there anything I'm missing? | 2018/04/04 | [
"https://Stackoverflow.com/questions/49646601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1889865/"
] | You can also try the code by writing inside **jquery** ready :
```
(function($){
'use strict';
var prevButton = '<button type="button" data-role="none" class="slick-prev" aria-label="prev"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" version="1.1"><path fill="#FFFFFF" d="M 16,16.46 11.415,11.875 16,7.29 14.585,5.875 l -6,6 6,6 z" /></svg></button>',
nextButton = '<button type="button" data-role="none" class="slick-next" aria-label="next"><svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path fill="#FFFFFF" d="M8.585 16.46l4.585-4.585-4.585-4.585 1.415-1.415 6 6-6 6z"></path></svg></button>';
$('.single-item').slick({
infinite: true,
dots: true,
autoplay: true,
autoplaySpeed: 4000,
speed: 1000,
cssEase: 'ease-in-out',
prevArrow: prevButton,
nextArrow: nextButton
});
$('.quote-container').mousedown(function(){
$('.single-item').addClass('dragging');
});
$('.quote-container').mouseup(function(){
$('.single-item').removeClass('dragging');
});
})(jQuery);
```
Hope this will work. | **Can you try to add this jquery script in theme's footer.php for testing purpose like:**
var prevButton = '',
nextButton = '';
```
jQuery('.single-item').slick({
infinite: true,
dots: true,
autoplay: true,
autoplaySpeed: 4000,
speed: 1000,
cssEase: 'ease-in-out',
prevArrow: prevButton,
nextArrow: nextButton
});
jQuery('.quote-container').mousedown(function(){
jQuery('.single-item').addClass('dragging');
});
jQuery('.quote-container').mouseup(function(){
jQuery('.single-item').removeClass('dragging');
});
```
And also open inspect console for check any error. |
53,111,297 | My function is given a 'to\_find\_value' then I have 2 lists which are the same in length and index values. Once I find the index value in list 1 that 'to\_find\_value' is in, I want to take that index of list 2 and return the value found at list 2.
Ex:
```
function_name('tree', ['bush', 'tree', 'shrub'], ['red', 'green', 'yellow'])
'green'
```
So in the above function I was given tree, and I found it at index 1 in list 1 so then I go to index 1 in list 2 and return the value at that index
This is what I have started so far but I am unsure how to format an 'unknown' index:
```
for plant in plant_data:
if plant in list1:
list1[?] == list2[?]
return list2[?}
```
\*The '?' represents the part I'm unsure about | 2018/11/02 | [
"https://Stackoverflow.com/questions/53111297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10438529/"
] | Something like:
```
def f(a,b,c):
return c[b.index(a)]
```
Then call it like:
```
print(f('tree', ['bush', 'tree', 'shrub'], ['red', 'green', 'yellow']))
```
Output is:
```
green
``` | Use the index method:
```
return list2[list1.index(plant)]
``` |
53,111,297 | My function is given a 'to\_find\_value' then I have 2 lists which are the same in length and index values. Once I find the index value in list 1 that 'to\_find\_value' is in, I want to take that index of list 2 and return the value found at list 2.
Ex:
```
function_name('tree', ['bush', 'tree', 'shrub'], ['red', 'green', 'yellow'])
'green'
```
So in the above function I was given tree, and I found it at index 1 in list 1 so then I go to index 1 in list 2 and return the value at that index
This is what I have started so far but I am unsure how to format an 'unknown' index:
```
for plant in plant_data:
if plant in list1:
list1[?] == list2[?]
return list2[?}
```
\*The '?' represents the part I'm unsure about | 2018/11/02 | [
"https://Stackoverflow.com/questions/53111297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10438529/"
] | Something like:
```
def f(a,b,c):
return c[b.index(a)]
```
Then call it like:
```
print(f('tree', ['bush', 'tree', 'shrub'], ['red', 'green', 'yellow']))
```
Output is:
```
green
``` | You can use index method for list
```
>>> ["foo", "bar", "baz"].index("bar")
1
```
This will return the index of the first occurrence |
53,111,297 | My function is given a 'to\_find\_value' then I have 2 lists which are the same in length and index values. Once I find the index value in list 1 that 'to\_find\_value' is in, I want to take that index of list 2 and return the value found at list 2.
Ex:
```
function_name('tree', ['bush', 'tree', 'shrub'], ['red', 'green', 'yellow'])
'green'
```
So in the above function I was given tree, and I found it at index 1 in list 1 so then I go to index 1 in list 2 and return the value at that index
This is what I have started so far but I am unsure how to format an 'unknown' index:
```
for plant in plant_data:
if plant in list1:
list1[?] == list2[?]
return list2[?}
```
\*The '?' represents the part I'm unsure about | 2018/11/02 | [
"https://Stackoverflow.com/questions/53111297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10438529/"
] | Something like:
```
def f(a,b,c):
return c[b.index(a)]
```
Then call it like:
```
print(f('tree', ['bush', 'tree', 'shrub'], ['red', 'green', 'yellow']))
```
Output is:
```
green
``` | If I'm understanding you correctly, the function your looking for is index, which will return the index of the element in the list if it exists (and throw a value error if it doesn't). You can do something like this:
```
list2[list1.index("tree")]
```
list1.index("tree") will return 1, which you can then use to access list2. |
53,111,297 | My function is given a 'to\_find\_value' then I have 2 lists which are the same in length and index values. Once I find the index value in list 1 that 'to\_find\_value' is in, I want to take that index of list 2 and return the value found at list 2.
Ex:
```
function_name('tree', ['bush', 'tree', 'shrub'], ['red', 'green', 'yellow'])
'green'
```
So in the above function I was given tree, and I found it at index 1 in list 1 so then I go to index 1 in list 2 and return the value at that index
This is what I have started so far but I am unsure how to format an 'unknown' index:
```
for plant in plant_data:
if plant in list1:
list1[?] == list2[?]
return list2[?}
```
\*The '?' represents the part I'm unsure about | 2018/11/02 | [
"https://Stackoverflow.com/questions/53111297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10438529/"
] | Something like:
```
def f(a,b,c):
return c[b.index(a)]
```
Then call it like:
```
print(f('tree', ['bush', 'tree', 'shrub'], ['red', 'green', 'yellow']))
```
Output is:
```
green
``` | You can use the built-in `enumerate` function to keep track of the index and the item at the same time:
```
for idx, plant in enumerate(plant_data):
if plant in list1:
list1[idx] = list2[idx]
``` |
19,166,342 | I am using a list view in which I have an xml referencing drawable/list as follows:
```
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
//For the borders
<item>
<shape android:shape="rectangle">
<solid android:color="@color/white" />
<corners android:radius="0dp" />
</shape>
</item>
//For the background color of cells
<item android:top="1px"
android:left="0dp"
android:right="0dp"
android:bottom="1px">
<shape android:shape="rectangle">
<solid android:color="#262626" />
<corners android:radius="0dp" />
</shape>
</item>
</layer-list>
```
The above code is basically used to define the borders and the background color of cells. However, I want to be able to use line for the borders instead of rectangle so that the bottom border of one rectangle doesnt leave a 1 dp gap between the top border of another rectangle below it.
Please refer the image below:

As you can see from the image, the rectangular bottom border below BOK.L is a little off showing a gap between the top rectangular border of GOOG.OQ Is there a way to fix this such that both the borders either overlap on top of each other and no such double line gap appears or is there a way I can define a line shape such that it is defined above and below all the cells in the pic without a gap?
Any clue?
Thanks!
Justin
The xml file referencing the same (drawable/list) is as follows :
```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/list"
android:padding="4dp"
>
<TextView
android:id="@+id/symbol"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="2dp"
android:paddingLeft="8dp"
android:textColor="@color/search_autosuggest_header_text"
foo:customFont="Roboto-Bold.ttf"
android:singleLine="true"
android:layout_toLeftOf="@+id/last_container"
android:ellipsize="end"
android:gravity="left"
android:textSize="14sp"/>
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="8dp"
foo:customFont="Roboto-Regular.ttf"
android:layout_alignParentLeft="true"
android:layout_below="@id/symbol"
android:layout_toLeftOf="@+id/last_container"
android:paddingBottom="4dp"
android:textColor="@color/search_autosuggest_item_subtitle"
android:singleLine="true"
android:ellipsize="end"
android:textSize="11sp" />
<FrameLayout
android:id="@+id/last_container"
android:layout_width="87dp"
android:layout_height="wrap_content"
android:layout_margin="1dp"
android:layout_toLeftOf="@+id/net_change_container" >
<TextView
android:id="@+id/last_back"
style="@style/TextView.ListsTextView"
android:layout_width="87dp"
android:layout_height="wrap_content"
android:padding="3dp" />
<TextView
android:id="@+id/last"
style="@style/TextView.ListsTextView"
android:layout_width="87dp"
android:textSize="12sp"
android:layout_height="wrap_content" />
</FrameLayout>
<FrameLayout
android:id="@+id/net_change_container"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_margin="1dp"
android:layout_toLeftOf="@+id/percent_change_container" >
<TextView
android:id="@+id/net_change_back"
style="@style/TextView.ListsTextView"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:padding="3dp" />
<TextView
android:id="@+id/net_change"
style="@style/TextView.ListsTextView"
android:layout_width="80dp"
android:textSize="12sp"
android:layout_height="wrap_content" />
</FrameLayout>
<FrameLayout
android:id="@+id/percent_change_container"
android:layout_width="65dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_margin="1dp" >
<TextView
android:id="@+id/percent_change_back"
style="@style/TextView.ListsTextView"
android:layout_width="65dp"
android:textSize="14sp"
foo:customFont="Roboto-Regular.ttf"
android:layout_height="wrap_content"
android:padding="3dp" />
<TextView
android:id="@+id/percent_change"
style="@style/TextView.ListsTextView"
android:layout_width="65dp"
android:textSize="12sp"
android:layout_height="wrap_content"/>
</FrameLayout>
</RelativeLayout>
```
Also,@jboi with with your fix the screen that I get is:
 | 2013/10/03 | [
"https://Stackoverflow.com/questions/19166342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Just going to take an initial stab at this, I can update this is you add more tests cases or details to your question:
```
\w+="<.*>(.*)</.*>"
```
This matches your provided example, in addition it doesn't matter if:
* the variable name is different
* the tag or contents of the tag wrapping the text are different
What will break this, specifically, is if there are angle brackets inside your html tag, which is possible.
**Note:** It is a much better idea to do this using html as other answers have attempted, I only answered this with a regex because that was what OP asked for. To OP, if you can do this without a regex, do that instead. You should not attempt to parse HTML with javascript when possible, and this regex is not comparable to a full html parser. | No need for a regex, just parse the string with [DOMParser](https://developer.mozilla.org/en-US/docs/Web/API/DOMParser) and get the element and then use the DOM object methods/attributes
```
var parser = new DOMParser();
var str='<a href='www.google.com'>Google</a>";
var dom = parser.parseFromString(str,"text/xml");
//From there use dom like you would use document
var atags = dom.getElementsByTagName("a");
console.log( atags[0].textContent );
//Or
var atag = dom.querySelector("a");
console.log( atag.textContent );
//Or
var atag = dom.childNodes[0];
console.log( atag.textContent );
```
Only catch is DOMParser is not supported in IE lower than 9. |
19,166,342 | I am using a list view in which I have an xml referencing drawable/list as follows:
```
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
//For the borders
<item>
<shape android:shape="rectangle">
<solid android:color="@color/white" />
<corners android:radius="0dp" />
</shape>
</item>
//For the background color of cells
<item android:top="1px"
android:left="0dp"
android:right="0dp"
android:bottom="1px">
<shape android:shape="rectangle">
<solid android:color="#262626" />
<corners android:radius="0dp" />
</shape>
</item>
</layer-list>
```
The above code is basically used to define the borders and the background color of cells. However, I want to be able to use line for the borders instead of rectangle so that the bottom border of one rectangle doesnt leave a 1 dp gap between the top border of another rectangle below it.
Please refer the image below:

As you can see from the image, the rectangular bottom border below BOK.L is a little off showing a gap between the top rectangular border of GOOG.OQ Is there a way to fix this such that both the borders either overlap on top of each other and no such double line gap appears or is there a way I can define a line shape such that it is defined above and below all the cells in the pic without a gap?
Any clue?
Thanks!
Justin
The xml file referencing the same (drawable/list) is as follows :
```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/list"
android:padding="4dp"
>
<TextView
android:id="@+id/symbol"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="2dp"
android:paddingLeft="8dp"
android:textColor="@color/search_autosuggest_header_text"
foo:customFont="Roboto-Bold.ttf"
android:singleLine="true"
android:layout_toLeftOf="@+id/last_container"
android:ellipsize="end"
android:gravity="left"
android:textSize="14sp"/>
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="8dp"
foo:customFont="Roboto-Regular.ttf"
android:layout_alignParentLeft="true"
android:layout_below="@id/symbol"
android:layout_toLeftOf="@+id/last_container"
android:paddingBottom="4dp"
android:textColor="@color/search_autosuggest_item_subtitle"
android:singleLine="true"
android:ellipsize="end"
android:textSize="11sp" />
<FrameLayout
android:id="@+id/last_container"
android:layout_width="87dp"
android:layout_height="wrap_content"
android:layout_margin="1dp"
android:layout_toLeftOf="@+id/net_change_container" >
<TextView
android:id="@+id/last_back"
style="@style/TextView.ListsTextView"
android:layout_width="87dp"
android:layout_height="wrap_content"
android:padding="3dp" />
<TextView
android:id="@+id/last"
style="@style/TextView.ListsTextView"
android:layout_width="87dp"
android:textSize="12sp"
android:layout_height="wrap_content" />
</FrameLayout>
<FrameLayout
android:id="@+id/net_change_container"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_margin="1dp"
android:layout_toLeftOf="@+id/percent_change_container" >
<TextView
android:id="@+id/net_change_back"
style="@style/TextView.ListsTextView"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:padding="3dp" />
<TextView
android:id="@+id/net_change"
style="@style/TextView.ListsTextView"
android:layout_width="80dp"
android:textSize="12sp"
android:layout_height="wrap_content" />
</FrameLayout>
<FrameLayout
android:id="@+id/percent_change_container"
android:layout_width="65dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_margin="1dp" >
<TextView
android:id="@+id/percent_change_back"
style="@style/TextView.ListsTextView"
android:layout_width="65dp"
android:textSize="14sp"
foo:customFont="Roboto-Regular.ttf"
android:layout_height="wrap_content"
android:padding="3dp" />
<TextView
android:id="@+id/percent_change"
style="@style/TextView.ListsTextView"
android:layout_width="65dp"
android:textSize="12sp"
android:layout_height="wrap_content"/>
</FrameLayout>
</RelativeLayout>
```
Also,@jboi with with your fix the screen that I get is:
 | 2013/10/03 | [
"https://Stackoverflow.com/questions/19166342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Insert the HTML string into an element, and then just get the text ?
```
var str = "<a href=www.google.com>Google</a>";
var div = document.createElement('div');
div.innerHTML = str;
var txt = div.textContent ? div.textContent : div.innerText;
```
[**FIDDLE**](http://jsfiddle.net/ScacH/1/)
In jQuery this would be :
```
var str = "<a href=www.google.com>Google</a>";
var txt = $(str).text();
```
[**FIDDLE**](http://jsfiddle.net/ScacH/2/) | No need for a regex, just parse the string with [DOMParser](https://developer.mozilla.org/en-US/docs/Web/API/DOMParser) and get the element and then use the DOM object methods/attributes
```
var parser = new DOMParser();
var str='<a href='www.google.com'>Google</a>";
var dom = parser.parseFromString(str,"text/xml");
//From there use dom like you would use document
var atags = dom.getElementsByTagName("a");
console.log( atags[0].textContent );
//Or
var atag = dom.querySelector("a");
console.log( atag.textContent );
//Or
var atag = dom.childNodes[0];
console.log( atag.textContent );
```
Only catch is DOMParser is not supported in IE lower than 9. |
19,166,342 | I am using a list view in which I have an xml referencing drawable/list as follows:
```
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
//For the borders
<item>
<shape android:shape="rectangle">
<solid android:color="@color/white" />
<corners android:radius="0dp" />
</shape>
</item>
//For the background color of cells
<item android:top="1px"
android:left="0dp"
android:right="0dp"
android:bottom="1px">
<shape android:shape="rectangle">
<solid android:color="#262626" />
<corners android:radius="0dp" />
</shape>
</item>
</layer-list>
```
The above code is basically used to define the borders and the background color of cells. However, I want to be able to use line for the borders instead of rectangle so that the bottom border of one rectangle doesnt leave a 1 dp gap between the top border of another rectangle below it.
Please refer the image below:

As you can see from the image, the rectangular bottom border below BOK.L is a little off showing a gap between the top rectangular border of GOOG.OQ Is there a way to fix this such that both the borders either overlap on top of each other and no such double line gap appears or is there a way I can define a line shape such that it is defined above and below all the cells in the pic without a gap?
Any clue?
Thanks!
Justin
The xml file referencing the same (drawable/list) is as follows :
```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/list"
android:padding="4dp"
>
<TextView
android:id="@+id/symbol"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="2dp"
android:paddingLeft="8dp"
android:textColor="@color/search_autosuggest_header_text"
foo:customFont="Roboto-Bold.ttf"
android:singleLine="true"
android:layout_toLeftOf="@+id/last_container"
android:ellipsize="end"
android:gravity="left"
android:textSize="14sp"/>
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="8dp"
foo:customFont="Roboto-Regular.ttf"
android:layout_alignParentLeft="true"
android:layout_below="@id/symbol"
android:layout_toLeftOf="@+id/last_container"
android:paddingBottom="4dp"
android:textColor="@color/search_autosuggest_item_subtitle"
android:singleLine="true"
android:ellipsize="end"
android:textSize="11sp" />
<FrameLayout
android:id="@+id/last_container"
android:layout_width="87dp"
android:layout_height="wrap_content"
android:layout_margin="1dp"
android:layout_toLeftOf="@+id/net_change_container" >
<TextView
android:id="@+id/last_back"
style="@style/TextView.ListsTextView"
android:layout_width="87dp"
android:layout_height="wrap_content"
android:padding="3dp" />
<TextView
android:id="@+id/last"
style="@style/TextView.ListsTextView"
android:layout_width="87dp"
android:textSize="12sp"
android:layout_height="wrap_content" />
</FrameLayout>
<FrameLayout
android:id="@+id/net_change_container"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_margin="1dp"
android:layout_toLeftOf="@+id/percent_change_container" >
<TextView
android:id="@+id/net_change_back"
style="@style/TextView.ListsTextView"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:padding="3dp" />
<TextView
android:id="@+id/net_change"
style="@style/TextView.ListsTextView"
android:layout_width="80dp"
android:textSize="12sp"
android:layout_height="wrap_content" />
</FrameLayout>
<FrameLayout
android:id="@+id/percent_change_container"
android:layout_width="65dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_margin="1dp" >
<TextView
android:id="@+id/percent_change_back"
style="@style/TextView.ListsTextView"
android:layout_width="65dp"
android:textSize="14sp"
foo:customFont="Roboto-Regular.ttf"
android:layout_height="wrap_content"
android:padding="3dp" />
<TextView
android:id="@+id/percent_change"
style="@style/TextView.ListsTextView"
android:layout_width="65dp"
android:textSize="12sp"
android:layout_height="wrap_content"/>
</FrameLayout>
</RelativeLayout>
```
Also,@jboi with with your fix the screen that I get is:
 | 2013/10/03 | [
"https://Stackoverflow.com/questions/19166342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Just going to take an initial stab at this, I can update this is you add more tests cases or details to your question:
```
\w+="<.*>(.*)</.*>"
```
This matches your provided example, in addition it doesn't matter if:
* the variable name is different
* the tag or contents of the tag wrapping the text are different
What will break this, specifically, is if there are angle brackets inside your html tag, which is possible.
**Note:** It is a much better idea to do this using html as other answers have attempted, I only answered this with a regex because that was what OP asked for. To OP, if you can do this without a regex, do that instead. You should not attempt to parse HTML with javascript when possible, and this regex is not comparable to a full html parser. | Assuming that you are using java, from the provided code.
I would recommend you to use [JSoup](http://jsoup.org/cookbook/extracting-data/attributes-text-html) to extract text inside anchor tag.
Here's a reason why. [Using regular expressions to parse HTML: why not?](https://stackoverflow.com/questions/590747/using-regular-expressions-to-parse-html-why-not)
```
String html = "<a href='www.google.com'>Google</a>";
Document doc = Jsoup.parse(html);
Element link = doc.select("a").first();
String linkHref = link.attr("href"); // "www.google.com"
String linkText = link.text(); // "Google""
String linkOuterH = link.outerHtml();
// "<a href='www.google.com'>Google</a>";
String linkInnerH = link.html(); // "<b>example</b>"
``` |
19,166,342 | I am using a list view in which I have an xml referencing drawable/list as follows:
```
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
//For the borders
<item>
<shape android:shape="rectangle">
<solid android:color="@color/white" />
<corners android:radius="0dp" />
</shape>
</item>
//For the background color of cells
<item android:top="1px"
android:left="0dp"
android:right="0dp"
android:bottom="1px">
<shape android:shape="rectangle">
<solid android:color="#262626" />
<corners android:radius="0dp" />
</shape>
</item>
</layer-list>
```
The above code is basically used to define the borders and the background color of cells. However, I want to be able to use line for the borders instead of rectangle so that the bottom border of one rectangle doesnt leave a 1 dp gap between the top border of another rectangle below it.
Please refer the image below:

As you can see from the image, the rectangular bottom border below BOK.L is a little off showing a gap between the top rectangular border of GOOG.OQ Is there a way to fix this such that both the borders either overlap on top of each other and no such double line gap appears or is there a way I can define a line shape such that it is defined above and below all the cells in the pic without a gap?
Any clue?
Thanks!
Justin
The xml file referencing the same (drawable/list) is as follows :
```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/list"
android:padding="4dp"
>
<TextView
android:id="@+id/symbol"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="2dp"
android:paddingLeft="8dp"
android:textColor="@color/search_autosuggest_header_text"
foo:customFont="Roboto-Bold.ttf"
android:singleLine="true"
android:layout_toLeftOf="@+id/last_container"
android:ellipsize="end"
android:gravity="left"
android:textSize="14sp"/>
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="8dp"
foo:customFont="Roboto-Regular.ttf"
android:layout_alignParentLeft="true"
android:layout_below="@id/symbol"
android:layout_toLeftOf="@+id/last_container"
android:paddingBottom="4dp"
android:textColor="@color/search_autosuggest_item_subtitle"
android:singleLine="true"
android:ellipsize="end"
android:textSize="11sp" />
<FrameLayout
android:id="@+id/last_container"
android:layout_width="87dp"
android:layout_height="wrap_content"
android:layout_margin="1dp"
android:layout_toLeftOf="@+id/net_change_container" >
<TextView
android:id="@+id/last_back"
style="@style/TextView.ListsTextView"
android:layout_width="87dp"
android:layout_height="wrap_content"
android:padding="3dp" />
<TextView
android:id="@+id/last"
style="@style/TextView.ListsTextView"
android:layout_width="87dp"
android:textSize="12sp"
android:layout_height="wrap_content" />
</FrameLayout>
<FrameLayout
android:id="@+id/net_change_container"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_margin="1dp"
android:layout_toLeftOf="@+id/percent_change_container" >
<TextView
android:id="@+id/net_change_back"
style="@style/TextView.ListsTextView"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:padding="3dp" />
<TextView
android:id="@+id/net_change"
style="@style/TextView.ListsTextView"
android:layout_width="80dp"
android:textSize="12sp"
android:layout_height="wrap_content" />
</FrameLayout>
<FrameLayout
android:id="@+id/percent_change_container"
android:layout_width="65dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_margin="1dp" >
<TextView
android:id="@+id/percent_change_back"
style="@style/TextView.ListsTextView"
android:layout_width="65dp"
android:textSize="14sp"
foo:customFont="Roboto-Regular.ttf"
android:layout_height="wrap_content"
android:padding="3dp" />
<TextView
android:id="@+id/percent_change"
style="@style/TextView.ListsTextView"
android:layout_width="65dp"
android:textSize="12sp"
android:layout_height="wrap_content"/>
</FrameLayout>
</RelativeLayout>
```
Also,@jboi with with your fix the screen that I get is:
 | 2013/10/03 | [
"https://Stackoverflow.com/questions/19166342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Insert the HTML string into an element, and then just get the text ?
```
var str = "<a href=www.google.com>Google</a>";
var div = document.createElement('div');
div.innerHTML = str;
var txt = div.textContent ? div.textContent : div.innerText;
```
[**FIDDLE**](http://jsfiddle.net/ScacH/1/)
In jQuery this would be :
```
var str = "<a href=www.google.com>Google</a>";
var txt = $(str).text();
```
[**FIDDLE**](http://jsfiddle.net/ScacH/2/) | Well, if you're using JQuery this should be an easy task.
I would just create an invisible div and render this anchor () on it. Afterwards you could simply select the anchor and get it's inner text.
```
$('body').append('<div id="invisibleDiv" style="display:none;"></div>'); //create a new invisible div
$('#invisibleDiv').html(str); //Include yours "str" content on the invisible DIV
console.log($('a', '#invisibleDiv').html()); //And this should output the text of any anchor inside that invisible DIV.
```
Remember, to do this way you must have JQuery loaded on your page.
EDIT: Use only if you've already have JQuery on your project, since as stated below, something simple as this should not be a reason for the inclusion of this entire library. |
19,166,342 | I am using a list view in which I have an xml referencing drawable/list as follows:
```
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
//For the borders
<item>
<shape android:shape="rectangle">
<solid android:color="@color/white" />
<corners android:radius="0dp" />
</shape>
</item>
//For the background color of cells
<item android:top="1px"
android:left="0dp"
android:right="0dp"
android:bottom="1px">
<shape android:shape="rectangle">
<solid android:color="#262626" />
<corners android:radius="0dp" />
</shape>
</item>
</layer-list>
```
The above code is basically used to define the borders and the background color of cells. However, I want to be able to use line for the borders instead of rectangle so that the bottom border of one rectangle doesnt leave a 1 dp gap between the top border of another rectangle below it.
Please refer the image below:

As you can see from the image, the rectangular bottom border below BOK.L is a little off showing a gap between the top rectangular border of GOOG.OQ Is there a way to fix this such that both the borders either overlap on top of each other and no such double line gap appears or is there a way I can define a line shape such that it is defined above and below all the cells in the pic without a gap?
Any clue?
Thanks!
Justin
The xml file referencing the same (drawable/list) is as follows :
```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/list"
android:padding="4dp"
>
<TextView
android:id="@+id/symbol"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="2dp"
android:paddingLeft="8dp"
android:textColor="@color/search_autosuggest_header_text"
foo:customFont="Roboto-Bold.ttf"
android:singleLine="true"
android:layout_toLeftOf="@+id/last_container"
android:ellipsize="end"
android:gravity="left"
android:textSize="14sp"/>
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="8dp"
foo:customFont="Roboto-Regular.ttf"
android:layout_alignParentLeft="true"
android:layout_below="@id/symbol"
android:layout_toLeftOf="@+id/last_container"
android:paddingBottom="4dp"
android:textColor="@color/search_autosuggest_item_subtitle"
android:singleLine="true"
android:ellipsize="end"
android:textSize="11sp" />
<FrameLayout
android:id="@+id/last_container"
android:layout_width="87dp"
android:layout_height="wrap_content"
android:layout_margin="1dp"
android:layout_toLeftOf="@+id/net_change_container" >
<TextView
android:id="@+id/last_back"
style="@style/TextView.ListsTextView"
android:layout_width="87dp"
android:layout_height="wrap_content"
android:padding="3dp" />
<TextView
android:id="@+id/last"
style="@style/TextView.ListsTextView"
android:layout_width="87dp"
android:textSize="12sp"
android:layout_height="wrap_content" />
</FrameLayout>
<FrameLayout
android:id="@+id/net_change_container"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_margin="1dp"
android:layout_toLeftOf="@+id/percent_change_container" >
<TextView
android:id="@+id/net_change_back"
style="@style/TextView.ListsTextView"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:padding="3dp" />
<TextView
android:id="@+id/net_change"
style="@style/TextView.ListsTextView"
android:layout_width="80dp"
android:textSize="12sp"
android:layout_height="wrap_content" />
</FrameLayout>
<FrameLayout
android:id="@+id/percent_change_container"
android:layout_width="65dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_margin="1dp" >
<TextView
android:id="@+id/percent_change_back"
style="@style/TextView.ListsTextView"
android:layout_width="65dp"
android:textSize="14sp"
foo:customFont="Roboto-Regular.ttf"
android:layout_height="wrap_content"
android:padding="3dp" />
<TextView
android:id="@+id/percent_change"
style="@style/TextView.ListsTextView"
android:layout_width="65dp"
android:textSize="12sp"
android:layout_height="wrap_content"/>
</FrameLayout>
</RelativeLayout>
```
Also,@jboi with with your fix the screen that I get is:
 | 2013/10/03 | [
"https://Stackoverflow.com/questions/19166342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | From the suggestions given by you all I got answer and works for me
```
function extractText(){
var anchText = "<a href=www.google.com>Google</a>";
var str1 = document.createElement('str1');
str1.innerHTML = anchText;
alert("hi "+str1.innerText);
return anc;
}
```
Thanks everyone for the support | No need for a regex, just parse the string with [DOMParser](https://developer.mozilla.org/en-US/docs/Web/API/DOMParser) and get the element and then use the DOM object methods/attributes
```
var parser = new DOMParser();
var str='<a href='www.google.com'>Google</a>";
var dom = parser.parseFromString(str,"text/xml");
//From there use dom like you would use document
var atags = dom.getElementsByTagName("a");
console.log( atags[0].textContent );
//Or
var atag = dom.querySelector("a");
console.log( atag.textContent );
//Or
var atag = dom.childNodes[0];
console.log( atag.textContent );
```
Only catch is DOMParser is not supported in IE lower than 9. |
19,166,342 | I am using a list view in which I have an xml referencing drawable/list as follows:
```
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
//For the borders
<item>
<shape android:shape="rectangle">
<solid android:color="@color/white" />
<corners android:radius="0dp" />
</shape>
</item>
//For the background color of cells
<item android:top="1px"
android:left="0dp"
android:right="0dp"
android:bottom="1px">
<shape android:shape="rectangle">
<solid android:color="#262626" />
<corners android:radius="0dp" />
</shape>
</item>
</layer-list>
```
The above code is basically used to define the borders and the background color of cells. However, I want to be able to use line for the borders instead of rectangle so that the bottom border of one rectangle doesnt leave a 1 dp gap between the top border of another rectangle below it.
Please refer the image below:

As you can see from the image, the rectangular bottom border below BOK.L is a little off showing a gap between the top rectangular border of GOOG.OQ Is there a way to fix this such that both the borders either overlap on top of each other and no such double line gap appears or is there a way I can define a line shape such that it is defined above and below all the cells in the pic without a gap?
Any clue?
Thanks!
Justin
The xml file referencing the same (drawable/list) is as follows :
```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/list"
android:padding="4dp"
>
<TextView
android:id="@+id/symbol"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="2dp"
android:paddingLeft="8dp"
android:textColor="@color/search_autosuggest_header_text"
foo:customFont="Roboto-Bold.ttf"
android:singleLine="true"
android:layout_toLeftOf="@+id/last_container"
android:ellipsize="end"
android:gravity="left"
android:textSize="14sp"/>
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="8dp"
foo:customFont="Roboto-Regular.ttf"
android:layout_alignParentLeft="true"
android:layout_below="@id/symbol"
android:layout_toLeftOf="@+id/last_container"
android:paddingBottom="4dp"
android:textColor="@color/search_autosuggest_item_subtitle"
android:singleLine="true"
android:ellipsize="end"
android:textSize="11sp" />
<FrameLayout
android:id="@+id/last_container"
android:layout_width="87dp"
android:layout_height="wrap_content"
android:layout_margin="1dp"
android:layout_toLeftOf="@+id/net_change_container" >
<TextView
android:id="@+id/last_back"
style="@style/TextView.ListsTextView"
android:layout_width="87dp"
android:layout_height="wrap_content"
android:padding="3dp" />
<TextView
android:id="@+id/last"
style="@style/TextView.ListsTextView"
android:layout_width="87dp"
android:textSize="12sp"
android:layout_height="wrap_content" />
</FrameLayout>
<FrameLayout
android:id="@+id/net_change_container"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_margin="1dp"
android:layout_toLeftOf="@+id/percent_change_container" >
<TextView
android:id="@+id/net_change_back"
style="@style/TextView.ListsTextView"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:padding="3dp" />
<TextView
android:id="@+id/net_change"
style="@style/TextView.ListsTextView"
android:layout_width="80dp"
android:textSize="12sp"
android:layout_height="wrap_content" />
</FrameLayout>
<FrameLayout
android:id="@+id/percent_change_container"
android:layout_width="65dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_margin="1dp" >
<TextView
android:id="@+id/percent_change_back"
style="@style/TextView.ListsTextView"
android:layout_width="65dp"
android:textSize="14sp"
foo:customFont="Roboto-Regular.ttf"
android:layout_height="wrap_content"
android:padding="3dp" />
<TextView
android:id="@+id/percent_change"
style="@style/TextView.ListsTextView"
android:layout_width="65dp"
android:textSize="12sp"
android:layout_height="wrap_content"/>
</FrameLayout>
</RelativeLayout>
```
Also,@jboi with with your fix the screen that I get is:
 | 2013/10/03 | [
"https://Stackoverflow.com/questions/19166342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | From the suggestions given by you all I got answer and works for me
```
function extractText(){
var anchText = "<a href=www.google.com>Google</a>";
var str1 = document.createElement('str1');
str1.innerHTML = anchText;
alert("hi "+str1.innerText);
return anc;
}
```
Thanks everyone for the support | Assuming that you are using java, from the provided code.
I would recommend you to use [JSoup](http://jsoup.org/cookbook/extracting-data/attributes-text-html) to extract text inside anchor tag.
Here's a reason why. [Using regular expressions to parse HTML: why not?](https://stackoverflow.com/questions/590747/using-regular-expressions-to-parse-html-why-not)
```
String html = "<a href='www.google.com'>Google</a>";
Document doc = Jsoup.parse(html);
Element link = doc.select("a").first();
String linkHref = link.attr("href"); // "www.google.com"
String linkText = link.text(); // "Google""
String linkOuterH = link.outerHtml();
// "<a href='www.google.com'>Google</a>";
String linkInnerH = link.html(); // "<b>example</b>"
``` |
19,166,342 | I am using a list view in which I have an xml referencing drawable/list as follows:
```
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
//For the borders
<item>
<shape android:shape="rectangle">
<solid android:color="@color/white" />
<corners android:radius="0dp" />
</shape>
</item>
//For the background color of cells
<item android:top="1px"
android:left="0dp"
android:right="0dp"
android:bottom="1px">
<shape android:shape="rectangle">
<solid android:color="#262626" />
<corners android:radius="0dp" />
</shape>
</item>
</layer-list>
```
The above code is basically used to define the borders and the background color of cells. However, I want to be able to use line for the borders instead of rectangle so that the bottom border of one rectangle doesnt leave a 1 dp gap between the top border of another rectangle below it.
Please refer the image below:

As you can see from the image, the rectangular bottom border below BOK.L is a little off showing a gap between the top rectangular border of GOOG.OQ Is there a way to fix this such that both the borders either overlap on top of each other and no such double line gap appears or is there a way I can define a line shape such that it is defined above and below all the cells in the pic without a gap?
Any clue?
Thanks!
Justin
The xml file referencing the same (drawable/list) is as follows :
```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/list"
android:padding="4dp"
>
<TextView
android:id="@+id/symbol"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="2dp"
android:paddingLeft="8dp"
android:textColor="@color/search_autosuggest_header_text"
foo:customFont="Roboto-Bold.ttf"
android:singleLine="true"
android:layout_toLeftOf="@+id/last_container"
android:ellipsize="end"
android:gravity="left"
android:textSize="14sp"/>
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="8dp"
foo:customFont="Roboto-Regular.ttf"
android:layout_alignParentLeft="true"
android:layout_below="@id/symbol"
android:layout_toLeftOf="@+id/last_container"
android:paddingBottom="4dp"
android:textColor="@color/search_autosuggest_item_subtitle"
android:singleLine="true"
android:ellipsize="end"
android:textSize="11sp" />
<FrameLayout
android:id="@+id/last_container"
android:layout_width="87dp"
android:layout_height="wrap_content"
android:layout_margin="1dp"
android:layout_toLeftOf="@+id/net_change_container" >
<TextView
android:id="@+id/last_back"
style="@style/TextView.ListsTextView"
android:layout_width="87dp"
android:layout_height="wrap_content"
android:padding="3dp" />
<TextView
android:id="@+id/last"
style="@style/TextView.ListsTextView"
android:layout_width="87dp"
android:textSize="12sp"
android:layout_height="wrap_content" />
</FrameLayout>
<FrameLayout
android:id="@+id/net_change_container"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_margin="1dp"
android:layout_toLeftOf="@+id/percent_change_container" >
<TextView
android:id="@+id/net_change_back"
style="@style/TextView.ListsTextView"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:padding="3dp" />
<TextView
android:id="@+id/net_change"
style="@style/TextView.ListsTextView"
android:layout_width="80dp"
android:textSize="12sp"
android:layout_height="wrap_content" />
</FrameLayout>
<FrameLayout
android:id="@+id/percent_change_container"
android:layout_width="65dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_margin="1dp" >
<TextView
android:id="@+id/percent_change_back"
style="@style/TextView.ListsTextView"
android:layout_width="65dp"
android:textSize="14sp"
foo:customFont="Roboto-Regular.ttf"
android:layout_height="wrap_content"
android:padding="3dp" />
<TextView
android:id="@+id/percent_change"
style="@style/TextView.ListsTextView"
android:layout_width="65dp"
android:textSize="12sp"
android:layout_height="wrap_content"/>
</FrameLayout>
</RelativeLayout>
```
Also,@jboi with with your fix the screen that I get is:
 | 2013/10/03 | [
"https://Stackoverflow.com/questions/19166342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I dont think you would like to use Regex for this. You may try simply like this:-
```
<a id="myLink" href="http://www.google.com">Google</a>
var anchor = document.getElementById("myLink");
alert(anchor.getAttribute("href")); // Extract link
alert(anchor.innerHTML); // Extract Text
```
[Sample DEMO](http://jsfiddle.net/Ms7bc/3/)
**EDIT:-**(As rightly commented by Patrick Evans)
```
var str = "<a href=www.google.com>Google</a>";
var str1 = document.createElement('str1');
str1.innerHTML = str;
alert(str1.textContent);
alert( str1.innerText);
```
[Sample DEMO](http://jsfiddle.net/ScacH/3/) | No need for a regex, just parse the string with [DOMParser](https://developer.mozilla.org/en-US/docs/Web/API/DOMParser) and get the element and then use the DOM object methods/attributes
```
var parser = new DOMParser();
var str='<a href='www.google.com'>Google</a>";
var dom = parser.parseFromString(str,"text/xml");
//From there use dom like you would use document
var atags = dom.getElementsByTagName("a");
console.log( atags[0].textContent );
//Or
var atag = dom.querySelector("a");
console.log( atag.textContent );
//Or
var atag = dom.childNodes[0];
console.log( atag.textContent );
```
Only catch is DOMParser is not supported in IE lower than 9. |
19,166,342 | I am using a list view in which I have an xml referencing drawable/list as follows:
```
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
//For the borders
<item>
<shape android:shape="rectangle">
<solid android:color="@color/white" />
<corners android:radius="0dp" />
</shape>
</item>
//For the background color of cells
<item android:top="1px"
android:left="0dp"
android:right="0dp"
android:bottom="1px">
<shape android:shape="rectangle">
<solid android:color="#262626" />
<corners android:radius="0dp" />
</shape>
</item>
</layer-list>
```
The above code is basically used to define the borders and the background color of cells. However, I want to be able to use line for the borders instead of rectangle so that the bottom border of one rectangle doesnt leave a 1 dp gap between the top border of another rectangle below it.
Please refer the image below:

As you can see from the image, the rectangular bottom border below BOK.L is a little off showing a gap between the top rectangular border of GOOG.OQ Is there a way to fix this such that both the borders either overlap on top of each other and no such double line gap appears or is there a way I can define a line shape such that it is defined above and below all the cells in the pic without a gap?
Any clue?
Thanks!
Justin
The xml file referencing the same (drawable/list) is as follows :
```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/list"
android:padding="4dp"
>
<TextView
android:id="@+id/symbol"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="2dp"
android:paddingLeft="8dp"
android:textColor="@color/search_autosuggest_header_text"
foo:customFont="Roboto-Bold.ttf"
android:singleLine="true"
android:layout_toLeftOf="@+id/last_container"
android:ellipsize="end"
android:gravity="left"
android:textSize="14sp"/>
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="8dp"
foo:customFont="Roboto-Regular.ttf"
android:layout_alignParentLeft="true"
android:layout_below="@id/symbol"
android:layout_toLeftOf="@+id/last_container"
android:paddingBottom="4dp"
android:textColor="@color/search_autosuggest_item_subtitle"
android:singleLine="true"
android:ellipsize="end"
android:textSize="11sp" />
<FrameLayout
android:id="@+id/last_container"
android:layout_width="87dp"
android:layout_height="wrap_content"
android:layout_margin="1dp"
android:layout_toLeftOf="@+id/net_change_container" >
<TextView
android:id="@+id/last_back"
style="@style/TextView.ListsTextView"
android:layout_width="87dp"
android:layout_height="wrap_content"
android:padding="3dp" />
<TextView
android:id="@+id/last"
style="@style/TextView.ListsTextView"
android:layout_width="87dp"
android:textSize="12sp"
android:layout_height="wrap_content" />
</FrameLayout>
<FrameLayout
android:id="@+id/net_change_container"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_margin="1dp"
android:layout_toLeftOf="@+id/percent_change_container" >
<TextView
android:id="@+id/net_change_back"
style="@style/TextView.ListsTextView"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:padding="3dp" />
<TextView
android:id="@+id/net_change"
style="@style/TextView.ListsTextView"
android:layout_width="80dp"
android:textSize="12sp"
android:layout_height="wrap_content" />
</FrameLayout>
<FrameLayout
android:id="@+id/percent_change_container"
android:layout_width="65dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_margin="1dp" >
<TextView
android:id="@+id/percent_change_back"
style="@style/TextView.ListsTextView"
android:layout_width="65dp"
android:textSize="14sp"
foo:customFont="Roboto-Regular.ttf"
android:layout_height="wrap_content"
android:padding="3dp" />
<TextView
android:id="@+id/percent_change"
style="@style/TextView.ListsTextView"
android:layout_width="65dp"
android:textSize="12sp"
android:layout_height="wrap_content"/>
</FrameLayout>
</RelativeLayout>
```
Also,@jboi with with your fix the screen that I get is:
 | 2013/10/03 | [
"https://Stackoverflow.com/questions/19166342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | From the suggestions given by you all I got answer and works for me
```
function extractText(){
var anchText = "<a href=www.google.com>Google</a>";
var str1 = document.createElement('str1');
str1.innerHTML = anchText;
alert("hi "+str1.innerText);
return anc;
}
```
Thanks everyone for the support | Just going to take an initial stab at this, I can update this is you add more tests cases or details to your question:
```
\w+="<.*>(.*)</.*>"
```
This matches your provided example, in addition it doesn't matter if:
* the variable name is different
* the tag or contents of the tag wrapping the text are different
What will break this, specifically, is if there are angle brackets inside your html tag, which is possible.
**Note:** It is a much better idea to do this using html as other answers have attempted, I only answered this with a regex because that was what OP asked for. To OP, if you can do this without a regex, do that instead. You should not attempt to parse HTML with javascript when possible, and this regex is not comparable to a full html parser. |
19,166,342 | I am using a list view in which I have an xml referencing drawable/list as follows:
```
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
//For the borders
<item>
<shape android:shape="rectangle">
<solid android:color="@color/white" />
<corners android:radius="0dp" />
</shape>
</item>
//For the background color of cells
<item android:top="1px"
android:left="0dp"
android:right="0dp"
android:bottom="1px">
<shape android:shape="rectangle">
<solid android:color="#262626" />
<corners android:radius="0dp" />
</shape>
</item>
</layer-list>
```
The above code is basically used to define the borders and the background color of cells. However, I want to be able to use line for the borders instead of rectangle so that the bottom border of one rectangle doesnt leave a 1 dp gap between the top border of another rectangle below it.
Please refer the image below:

As you can see from the image, the rectangular bottom border below BOK.L is a little off showing a gap between the top rectangular border of GOOG.OQ Is there a way to fix this such that both the borders either overlap on top of each other and no such double line gap appears or is there a way I can define a line shape such that it is defined above and below all the cells in the pic without a gap?
Any clue?
Thanks!
Justin
The xml file referencing the same (drawable/list) is as follows :
```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/list"
android:padding="4dp"
>
<TextView
android:id="@+id/symbol"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="2dp"
android:paddingLeft="8dp"
android:textColor="@color/search_autosuggest_header_text"
foo:customFont="Roboto-Bold.ttf"
android:singleLine="true"
android:layout_toLeftOf="@+id/last_container"
android:ellipsize="end"
android:gravity="left"
android:textSize="14sp"/>
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="8dp"
foo:customFont="Roboto-Regular.ttf"
android:layout_alignParentLeft="true"
android:layout_below="@id/symbol"
android:layout_toLeftOf="@+id/last_container"
android:paddingBottom="4dp"
android:textColor="@color/search_autosuggest_item_subtitle"
android:singleLine="true"
android:ellipsize="end"
android:textSize="11sp" />
<FrameLayout
android:id="@+id/last_container"
android:layout_width="87dp"
android:layout_height="wrap_content"
android:layout_margin="1dp"
android:layout_toLeftOf="@+id/net_change_container" >
<TextView
android:id="@+id/last_back"
style="@style/TextView.ListsTextView"
android:layout_width="87dp"
android:layout_height="wrap_content"
android:padding="3dp" />
<TextView
android:id="@+id/last"
style="@style/TextView.ListsTextView"
android:layout_width="87dp"
android:textSize="12sp"
android:layout_height="wrap_content" />
</FrameLayout>
<FrameLayout
android:id="@+id/net_change_container"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_margin="1dp"
android:layout_toLeftOf="@+id/percent_change_container" >
<TextView
android:id="@+id/net_change_back"
style="@style/TextView.ListsTextView"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:padding="3dp" />
<TextView
android:id="@+id/net_change"
style="@style/TextView.ListsTextView"
android:layout_width="80dp"
android:textSize="12sp"
android:layout_height="wrap_content" />
</FrameLayout>
<FrameLayout
android:id="@+id/percent_change_container"
android:layout_width="65dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_margin="1dp" >
<TextView
android:id="@+id/percent_change_back"
style="@style/TextView.ListsTextView"
android:layout_width="65dp"
android:textSize="14sp"
foo:customFont="Roboto-Regular.ttf"
android:layout_height="wrap_content"
android:padding="3dp" />
<TextView
android:id="@+id/percent_change"
style="@style/TextView.ListsTextView"
android:layout_width="65dp"
android:textSize="12sp"
android:layout_height="wrap_content"/>
</FrameLayout>
</RelativeLayout>
```
Also,@jboi with with your fix the screen that I get is:
 | 2013/10/03 | [
"https://Stackoverflow.com/questions/19166342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I dont think you would like to use Regex for this. You may try simply like this:-
```
<a id="myLink" href="http://www.google.com">Google</a>
var anchor = document.getElementById("myLink");
alert(anchor.getAttribute("href")); // Extract link
alert(anchor.innerHTML); // Extract Text
```
[Sample DEMO](http://jsfiddle.net/Ms7bc/3/)
**EDIT:-**(As rightly commented by Patrick Evans)
```
var str = "<a href=www.google.com>Google</a>";
var str1 = document.createElement('str1');
str1.innerHTML = str;
alert(str1.textContent);
alert( str1.innerText);
```
[Sample DEMO](http://jsfiddle.net/ScacH/3/) | Well, if you're using JQuery this should be an easy task.
I would just create an invisible div and render this anchor () on it. Afterwards you could simply select the anchor and get it's inner text.
```
$('body').append('<div id="invisibleDiv" style="display:none;"></div>'); //create a new invisible div
$('#invisibleDiv').html(str); //Include yours "str" content on the invisible DIV
console.log($('a', '#invisibleDiv').html()); //And this should output the text of any anchor inside that invisible DIV.
```
Remember, to do this way you must have JQuery loaded on your page.
EDIT: Use only if you've already have JQuery on your project, since as stated below, something simple as this should not be a reason for the inclusion of this entire library. |
19,166,342 | I am using a list view in which I have an xml referencing drawable/list as follows:
```
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
//For the borders
<item>
<shape android:shape="rectangle">
<solid android:color="@color/white" />
<corners android:radius="0dp" />
</shape>
</item>
//For the background color of cells
<item android:top="1px"
android:left="0dp"
android:right="0dp"
android:bottom="1px">
<shape android:shape="rectangle">
<solid android:color="#262626" />
<corners android:radius="0dp" />
</shape>
</item>
</layer-list>
```
The above code is basically used to define the borders and the background color of cells. However, I want to be able to use line for the borders instead of rectangle so that the bottom border of one rectangle doesnt leave a 1 dp gap between the top border of another rectangle below it.
Please refer the image below:

As you can see from the image, the rectangular bottom border below BOK.L is a little off showing a gap between the top rectangular border of GOOG.OQ Is there a way to fix this such that both the borders either overlap on top of each other and no such double line gap appears or is there a way I can define a line shape such that it is defined above and below all the cells in the pic without a gap?
Any clue?
Thanks!
Justin
The xml file referencing the same (drawable/list) is as follows :
```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/list"
android:padding="4dp"
>
<TextView
android:id="@+id/symbol"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="2dp"
android:paddingLeft="8dp"
android:textColor="@color/search_autosuggest_header_text"
foo:customFont="Roboto-Bold.ttf"
android:singleLine="true"
android:layout_toLeftOf="@+id/last_container"
android:ellipsize="end"
android:gravity="left"
android:textSize="14sp"/>
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="8dp"
foo:customFont="Roboto-Regular.ttf"
android:layout_alignParentLeft="true"
android:layout_below="@id/symbol"
android:layout_toLeftOf="@+id/last_container"
android:paddingBottom="4dp"
android:textColor="@color/search_autosuggest_item_subtitle"
android:singleLine="true"
android:ellipsize="end"
android:textSize="11sp" />
<FrameLayout
android:id="@+id/last_container"
android:layout_width="87dp"
android:layout_height="wrap_content"
android:layout_margin="1dp"
android:layout_toLeftOf="@+id/net_change_container" >
<TextView
android:id="@+id/last_back"
style="@style/TextView.ListsTextView"
android:layout_width="87dp"
android:layout_height="wrap_content"
android:padding="3dp" />
<TextView
android:id="@+id/last"
style="@style/TextView.ListsTextView"
android:layout_width="87dp"
android:textSize="12sp"
android:layout_height="wrap_content" />
</FrameLayout>
<FrameLayout
android:id="@+id/net_change_container"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_margin="1dp"
android:layout_toLeftOf="@+id/percent_change_container" >
<TextView
android:id="@+id/net_change_back"
style="@style/TextView.ListsTextView"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:padding="3dp" />
<TextView
android:id="@+id/net_change"
style="@style/TextView.ListsTextView"
android:layout_width="80dp"
android:textSize="12sp"
android:layout_height="wrap_content" />
</FrameLayout>
<FrameLayout
android:id="@+id/percent_change_container"
android:layout_width="65dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_margin="1dp" >
<TextView
android:id="@+id/percent_change_back"
style="@style/TextView.ListsTextView"
android:layout_width="65dp"
android:textSize="14sp"
foo:customFont="Roboto-Regular.ttf"
android:layout_height="wrap_content"
android:padding="3dp" />
<TextView
android:id="@+id/percent_change"
style="@style/TextView.ListsTextView"
android:layout_width="65dp"
android:textSize="12sp"
android:layout_height="wrap_content"/>
</FrameLayout>
</RelativeLayout>
```
Also,@jboi with with your fix the screen that I get is:
 | 2013/10/03 | [
"https://Stackoverflow.com/questions/19166342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | No need for a regex, just parse the string with [DOMParser](https://developer.mozilla.org/en-US/docs/Web/API/DOMParser) and get the element and then use the DOM object methods/attributes
```
var parser = new DOMParser();
var str='<a href='www.google.com'>Google</a>";
var dom = parser.parseFromString(str,"text/xml");
//From there use dom like you would use document
var atags = dom.getElementsByTagName("a");
console.log( atags[0].textContent );
//Or
var atag = dom.querySelector("a");
console.log( atag.textContent );
//Or
var atag = dom.childNodes[0];
console.log( atag.textContent );
```
Only catch is DOMParser is not supported in IE lower than 9. | Well, if you're using JQuery this should be an easy task.
I would just create an invisible div and render this anchor () on it. Afterwards you could simply select the anchor and get it's inner text.
```
$('body').append('<div id="invisibleDiv" style="display:none;"></div>'); //create a new invisible div
$('#invisibleDiv').html(str); //Include yours "str" content on the invisible DIV
console.log($('a', '#invisibleDiv').html()); //And this should output the text of any anchor inside that invisible DIV.
```
Remember, to do this way you must have JQuery loaded on your page.
EDIT: Use only if you've already have JQuery on your project, since as stated below, something simple as this should not be a reason for the inclusion of this entire library. |
31,355 | In my world human(oid)s are not born anymore, they are grown in pods which mirror the conditions of a natural womb.
Children are educated before birth and are "born" as fully mature adults with a standard education ready to join society.
How long would this process take? I assume that artificial growth could be much quicker than a natural 18-20 year period. Could a human be grown in a year? A decade? | 2015/12/12 | [
"https://worldbuilding.stackexchange.com/questions/31355",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/18/"
] | A year? No. Babies already require 9 months in the womb to get to where they get. You're limited because many processes in growth require chemical processes that simply take time. Humans simply aren't cars to be manufactured.
A decade? Now its getting interesting. It is reasonable to assume that a human could grow faster in a "perfect" environment with genes to leverage that perfect environment. Its entierly possible we could reach "fully grown" in a decade. However, the womb would probably have to be adjusted. Many thing a human body needs require things that challenge their motion (so they can learn which muscles are doing what). The humans would be gloriously clumsy unless they got Physical Education as part of their standard education in the womb.
A standard education in the womb you say? That education process might be very daunting indeed. You may be able to physically produce a human in a decade, but you may find it hard to properly educate them that fast. | Certainly not in a year, no. Growth is limited by multiple things, for example:
* bone ossification - bones need to both grow laterally and also get ossified. There's a few values for bone growth in children [in this paper](http://www.boneandjoint.org.uk/content/jbjsbr/44-B/1/42.full.pdf) - basically, a few centimeters a year.
* skin needs to grow. And the larger a person gets, the greater their surface gets. Think about how long wound healing can sometimes take.
* neurons in the brain need to grow - your education alone will need several years, and will often have to wait for the growing brain to catch up
You can estimate a lower limit from two scenarios:
* there's people who never stopped producing human growth hormone, which is one of the factors in determining when children grow. [Robert Wadlow](https://en.wikipedia.org/wiki/Robert_Wadlow)'s body never stopped growing until he died at age 22 and roughly 270 centimeters. If he was born at around 50 centimeters, that's roughly 10 centimeters a year.
* the "peak growth velocity" in teenagers, who grow the fastest, is also [around 9 centimeters a year](http://pediatrics.aappublications.org/content/102/Supplement_3/507)
So basically, 10 centimeters a year would be a believable growth rate, meaning from 50 to 180 centimeters, you'd need about 13 years. Under optimal conditions, with great nutrition etc., a decade sounds believable.
However, you might want to keep in mind that this is only lateral growth. [The human brain isn't considered fully mature until the mid-20s.](http://hrweb.mit.edu/worklife/youngadult/brain.html) |
31,355 | In my world human(oid)s are not born anymore, they are grown in pods which mirror the conditions of a natural womb.
Children are educated before birth and are "born" as fully mature adults with a standard education ready to join society.
How long would this process take? I assume that artificial growth could be much quicker than a natural 18-20 year period. Could a human be grown in a year? A decade? | 2015/12/12 | [
"https://worldbuilding.stackexchange.com/questions/31355",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/18/"
] | A year? No. Babies already require 9 months in the womb to get to where they get. You're limited because many processes in growth require chemical processes that simply take time. Humans simply aren't cars to be manufactured.
A decade? Now its getting interesting. It is reasonable to assume that a human could grow faster in a "perfect" environment with genes to leverage that perfect environment. Its entierly possible we could reach "fully grown" in a decade. However, the womb would probably have to be adjusted. Many thing a human body needs require things that challenge their motion (so they can learn which muscles are doing what). The humans would be gloriously clumsy unless they got Physical Education as part of their standard education in the womb.
A standard education in the womb you say? That education process might be very daunting indeed. You may be able to physically produce a human in a decade, but you may find it hard to properly educate them that fast. | **18 weeks to 6 or 8 years, but it does not matter**
9 months to produce an infant is a long time compared to the initial growth rate of the embryo. At 4 weeks, the embryo is the size of a poppy seed (2 mm long), at 8 weeks, the size of a kidney bean (16 mm head to bottom). During that period, the human increased by at least a factor of 8. This is a growth rate of about 68% per week. At this rate, you are large newborn at 15 week and a full sized adult in under 18 weeks.
So, we have a reasonable lower bound of about 18 weeks and an upper bound of about 18 years. But can we find a better upper bound? Yes we can, [Robert Wadlow](https://en.wikipedia.org/wiki/Robert_Wadlow) was the tallest modern man that can be reliably documented. At age 6, he 5'7" and was already taller than his father at age 8. So 6-8 years seems like a better upper bound since people can grow that fast with too much human growth hormone.
Robert Wadlow had health problems and in fact died of medical complications of an autoimmune disease (possibly related to his HGH levels) at age 22. He was reportedly in good health until the final year of his life. His brain was certainly not mature at age 6 or 8, but lets assume that it could be close enough to be considered adult if he had a magical efficient training systems and nanotech to re-arrange brain structures as needed.
So 18 weeks to 6 years. Hypothetically speaking, after all of the needed advances in technology, including nano-tech what could we do?
The answer is simply unknown since we don't have the medical knowledge of the complications of accelerated growth in an artificial womb. Perhaps with nano-technology we could control physical growth, perform the necessary muscle and bone training, deal with the psychological and sociological training. Training the interactions between the brain and eyes, ears, hands, etc. Perhaps it is also possible to teach language, reading, writing, arithmetic, etc. in the womb.
There is a huge gulf between our current state of knowledge and that needed to perform all development in the womb. And there is very little incentive to acquire it.
Parents want to watch their children grow up, play, learn from their environment, etc. I can't image any parent I know desiring to replace this process with an artificial one. |
31,355 | In my world human(oid)s are not born anymore, they are grown in pods which mirror the conditions of a natural womb.
Children are educated before birth and are "born" as fully mature adults with a standard education ready to join society.
How long would this process take? I assume that artificial growth could be much quicker than a natural 18-20 year period. Could a human be grown in a year? A decade? | 2015/12/12 | [
"https://worldbuilding.stackexchange.com/questions/31355",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/18/"
] | A year? No. Babies already require 9 months in the womb to get to where they get. You're limited because many processes in growth require chemical processes that simply take time. Humans simply aren't cars to be manufactured.
A decade? Now its getting interesting. It is reasonable to assume that a human could grow faster in a "perfect" environment with genes to leverage that perfect environment. Its entierly possible we could reach "fully grown" in a decade. However, the womb would probably have to be adjusted. Many thing a human body needs require things that challenge their motion (so they can learn which muscles are doing what). The humans would be gloriously clumsy unless they got Physical Education as part of their standard education in the womb.
A standard education in the womb you say? That education process might be very daunting indeed. You may be able to physically produce a human in a decade, but you may find it hard to properly educate them that fast. | It **REALLY** depends on what level of technology we're talking about here.
After all, given sufficiently advanced technology, we could "build" a person, atom by atom, to have all the same properties, education, mental and motor functions etc. as if they had developed the normal way over many years.
---
Let's assume a level of technology that allows us to "develop" the brain in any way we like (including but not limited to: memories, knowledge, motor functions) as the body is growing, but which requires all the normal physical/chemical processes to take place. Albeit in an environment designed to optimise the speed/efficiency of that development.
**My guess: 2-7 years**
This is based on the fact that the environment you describe (No external interruptions, wholly optimised for and focused on development) sounds *very* similar to what we call "sleep".
Now, sleep also involves lots of other functions relating to ongoing maintenance/learning/repair which we may be able to eliminate the need for in our growth environment.
But then again, we have almost no idea of \*why\* humans need to sleep in the first place. So, I would suggest, for every day of "normal" growth, you will need a significant fraction of the time we spend sleeping, 2-8 hours or so, of "Test Tube Development Time". This yields 9%-33% of "Normal Development Time", so 2-7 years for a 20-year-old equivalent. |
31,355 | In my world human(oid)s are not born anymore, they are grown in pods which mirror the conditions of a natural womb.
Children are educated before birth and are "born" as fully mature adults with a standard education ready to join society.
How long would this process take? I assume that artificial growth could be much quicker than a natural 18-20 year period. Could a human be grown in a year? A decade? | 2015/12/12 | [
"https://worldbuilding.stackexchange.com/questions/31355",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/18/"
] | A year? No. Babies already require 9 months in the womb to get to where they get. You're limited because many processes in growth require chemical processes that simply take time. Humans simply aren't cars to be manufactured.
A decade? Now its getting interesting. It is reasonable to assume that a human could grow faster in a "perfect" environment with genes to leverage that perfect environment. Its entierly possible we could reach "fully grown" in a decade. However, the womb would probably have to be adjusted. Many thing a human body needs require things that challenge their motion (so they can learn which muscles are doing what). The humans would be gloriously clumsy unless they got Physical Education as part of their standard education in the womb.
A standard education in the womb you say? That education process might be very daunting indeed. You may be able to physically produce a human in a decade, but you may find it hard to properly educate them that fast. | Human growth is subject to many limiting factors, including the ability of the mother to supply the required nutrients to the foetus, and after birth, the ability of the child to acquire the full range of expected social skills.
A young human is physically small in order to convey the impression of youth to other humans. Since learning to be an adult human takes around eighteen to twenty-five years, that is how long it takes for the human body to mature fully. Size and other physical traits conveys an impression of age to others.
Now, if humans could grow to maturity and be born with all necessary knowledge to be fully functioning adults, as well as be free of the limitations of maternal nutrition, growing such a human in-vitro could occur in a relative short period of time.
In larger mammalian - and dinosaur - species where achieving an adult body-size (of several hundred kilograms to many tons) as quickly as possible is of paramount importance, very high growth rates can be achieved, with newborns achieving maturity within a handful of years, certainly within 5 years or less.
We could therefore expect that with genetic engineering - or some clever artificial stimulation - to remove the limits on pre-maturity growth-rate, a fully mature human could be produced within three years.
I should point out that if humans were genetically engineered to grow that quickly, it would effectively sterilize the population and make them dependent on artificial reproduction. Should a modified human mother become pregnant, her body would not be able to supply the huge metabolic needs that such a foetus impose on her, and a significant or even fatal loss of body mass would likely occur. Should the foetus survive, it would be no better educated than any normal human newborn.
On the other hand, if humans were grown rapidly and educated in-vitro through medical trickery rather than genetic engineering, a natural pregnancy would most likely be possible, with a normal-sized infant being born after the usual period of gestation. It is up to you if the mother would have been educated sufficiently to have the knowledge to handle a naturally-born child. |
31,355 | In my world human(oid)s are not born anymore, they are grown in pods which mirror the conditions of a natural womb.
Children are educated before birth and are "born" as fully mature adults with a standard education ready to join society.
How long would this process take? I assume that artificial growth could be much quicker than a natural 18-20 year period. Could a human be grown in a year? A decade? | 2015/12/12 | [
"https://worldbuilding.stackexchange.com/questions/31355",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/18/"
] | Certainly not in a year, no. Growth is limited by multiple things, for example:
* bone ossification - bones need to both grow laterally and also get ossified. There's a few values for bone growth in children [in this paper](http://www.boneandjoint.org.uk/content/jbjsbr/44-B/1/42.full.pdf) - basically, a few centimeters a year.
* skin needs to grow. And the larger a person gets, the greater their surface gets. Think about how long wound healing can sometimes take.
* neurons in the brain need to grow - your education alone will need several years, and will often have to wait for the growing brain to catch up
You can estimate a lower limit from two scenarios:
* there's people who never stopped producing human growth hormone, which is one of the factors in determining when children grow. [Robert Wadlow](https://en.wikipedia.org/wiki/Robert_Wadlow)'s body never stopped growing until he died at age 22 and roughly 270 centimeters. If he was born at around 50 centimeters, that's roughly 10 centimeters a year.
* the "peak growth velocity" in teenagers, who grow the fastest, is also [around 9 centimeters a year](http://pediatrics.aappublications.org/content/102/Supplement_3/507)
So basically, 10 centimeters a year would be a believable growth rate, meaning from 50 to 180 centimeters, you'd need about 13 years. Under optimal conditions, with great nutrition etc., a decade sounds believable.
However, you might want to keep in mind that this is only lateral growth. [The human brain isn't considered fully mature until the mid-20s.](http://hrweb.mit.edu/worklife/youngadult/brain.html) | **18 weeks to 6 or 8 years, but it does not matter**
9 months to produce an infant is a long time compared to the initial growth rate of the embryo. At 4 weeks, the embryo is the size of a poppy seed (2 mm long), at 8 weeks, the size of a kidney bean (16 mm head to bottom). During that period, the human increased by at least a factor of 8. This is a growth rate of about 68% per week. At this rate, you are large newborn at 15 week and a full sized adult in under 18 weeks.
So, we have a reasonable lower bound of about 18 weeks and an upper bound of about 18 years. But can we find a better upper bound? Yes we can, [Robert Wadlow](https://en.wikipedia.org/wiki/Robert_Wadlow) was the tallest modern man that can be reliably documented. At age 6, he 5'7" and was already taller than his father at age 8. So 6-8 years seems like a better upper bound since people can grow that fast with too much human growth hormone.
Robert Wadlow had health problems and in fact died of medical complications of an autoimmune disease (possibly related to his HGH levels) at age 22. He was reportedly in good health until the final year of his life. His brain was certainly not mature at age 6 or 8, but lets assume that it could be close enough to be considered adult if he had a magical efficient training systems and nanotech to re-arrange brain structures as needed.
So 18 weeks to 6 years. Hypothetically speaking, after all of the needed advances in technology, including nano-tech what could we do?
The answer is simply unknown since we don't have the medical knowledge of the complications of accelerated growth in an artificial womb. Perhaps with nano-technology we could control physical growth, perform the necessary muscle and bone training, deal with the psychological and sociological training. Training the interactions between the brain and eyes, ears, hands, etc. Perhaps it is also possible to teach language, reading, writing, arithmetic, etc. in the womb.
There is a huge gulf between our current state of knowledge and that needed to perform all development in the womb. And there is very little incentive to acquire it.
Parents want to watch their children grow up, play, learn from their environment, etc. I can't image any parent I know desiring to replace this process with an artificial one. |
31,355 | In my world human(oid)s are not born anymore, they are grown in pods which mirror the conditions of a natural womb.
Children are educated before birth and are "born" as fully mature adults with a standard education ready to join society.
How long would this process take? I assume that artificial growth could be much quicker than a natural 18-20 year period. Could a human be grown in a year? A decade? | 2015/12/12 | [
"https://worldbuilding.stackexchange.com/questions/31355",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/18/"
] | Certainly not in a year, no. Growth is limited by multiple things, for example:
* bone ossification - bones need to both grow laterally and also get ossified. There's a few values for bone growth in children [in this paper](http://www.boneandjoint.org.uk/content/jbjsbr/44-B/1/42.full.pdf) - basically, a few centimeters a year.
* skin needs to grow. And the larger a person gets, the greater their surface gets. Think about how long wound healing can sometimes take.
* neurons in the brain need to grow - your education alone will need several years, and will often have to wait for the growing brain to catch up
You can estimate a lower limit from two scenarios:
* there's people who never stopped producing human growth hormone, which is one of the factors in determining when children grow. [Robert Wadlow](https://en.wikipedia.org/wiki/Robert_Wadlow)'s body never stopped growing until he died at age 22 and roughly 270 centimeters. If he was born at around 50 centimeters, that's roughly 10 centimeters a year.
* the "peak growth velocity" in teenagers, who grow the fastest, is also [around 9 centimeters a year](http://pediatrics.aappublications.org/content/102/Supplement_3/507)
So basically, 10 centimeters a year would be a believable growth rate, meaning from 50 to 180 centimeters, you'd need about 13 years. Under optimal conditions, with great nutrition etc., a decade sounds believable.
However, you might want to keep in mind that this is only lateral growth. [The human brain isn't considered fully mature until the mid-20s.](http://hrweb.mit.edu/worklife/youngadult/brain.html) | Human growth is subject to many limiting factors, including the ability of the mother to supply the required nutrients to the foetus, and after birth, the ability of the child to acquire the full range of expected social skills.
A young human is physically small in order to convey the impression of youth to other humans. Since learning to be an adult human takes around eighteen to twenty-five years, that is how long it takes for the human body to mature fully. Size and other physical traits conveys an impression of age to others.
Now, if humans could grow to maturity and be born with all necessary knowledge to be fully functioning adults, as well as be free of the limitations of maternal nutrition, growing such a human in-vitro could occur in a relative short period of time.
In larger mammalian - and dinosaur - species where achieving an adult body-size (of several hundred kilograms to many tons) as quickly as possible is of paramount importance, very high growth rates can be achieved, with newborns achieving maturity within a handful of years, certainly within 5 years or less.
We could therefore expect that with genetic engineering - or some clever artificial stimulation - to remove the limits on pre-maturity growth-rate, a fully mature human could be produced within three years.
I should point out that if humans were genetically engineered to grow that quickly, it would effectively sterilize the population and make them dependent on artificial reproduction. Should a modified human mother become pregnant, her body would not be able to supply the huge metabolic needs that such a foetus impose on her, and a significant or even fatal loss of body mass would likely occur. Should the foetus survive, it would be no better educated than any normal human newborn.
On the other hand, if humans were grown rapidly and educated in-vitro through medical trickery rather than genetic engineering, a natural pregnancy would most likely be possible, with a normal-sized infant being born after the usual period of gestation. It is up to you if the mother would have been educated sufficiently to have the knowledge to handle a naturally-born child. |
31,355 | In my world human(oid)s are not born anymore, they are grown in pods which mirror the conditions of a natural womb.
Children are educated before birth and are "born" as fully mature adults with a standard education ready to join society.
How long would this process take? I assume that artificial growth could be much quicker than a natural 18-20 year period. Could a human be grown in a year? A decade? | 2015/12/12 | [
"https://worldbuilding.stackexchange.com/questions/31355",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/18/"
] | It **REALLY** depends on what level of technology we're talking about here.
After all, given sufficiently advanced technology, we could "build" a person, atom by atom, to have all the same properties, education, mental and motor functions etc. as if they had developed the normal way over many years.
---
Let's assume a level of technology that allows us to "develop" the brain in any way we like (including but not limited to: memories, knowledge, motor functions) as the body is growing, but which requires all the normal physical/chemical processes to take place. Albeit in an environment designed to optimise the speed/efficiency of that development.
**My guess: 2-7 years**
This is based on the fact that the environment you describe (No external interruptions, wholly optimised for and focused on development) sounds *very* similar to what we call "sleep".
Now, sleep also involves lots of other functions relating to ongoing maintenance/learning/repair which we may be able to eliminate the need for in our growth environment.
But then again, we have almost no idea of \*why\* humans need to sleep in the first place. So, I would suggest, for every day of "normal" growth, you will need a significant fraction of the time we spend sleeping, 2-8 hours or so, of "Test Tube Development Time". This yields 9%-33% of "Normal Development Time", so 2-7 years for a 20-year-old equivalent. | **18 weeks to 6 or 8 years, but it does not matter**
9 months to produce an infant is a long time compared to the initial growth rate of the embryo. At 4 weeks, the embryo is the size of a poppy seed (2 mm long), at 8 weeks, the size of a kidney bean (16 mm head to bottom). During that period, the human increased by at least a factor of 8. This is a growth rate of about 68% per week. At this rate, you are large newborn at 15 week and a full sized adult in under 18 weeks.
So, we have a reasonable lower bound of about 18 weeks and an upper bound of about 18 years. But can we find a better upper bound? Yes we can, [Robert Wadlow](https://en.wikipedia.org/wiki/Robert_Wadlow) was the tallest modern man that can be reliably documented. At age 6, he 5'7" and was already taller than his father at age 8. So 6-8 years seems like a better upper bound since people can grow that fast with too much human growth hormone.
Robert Wadlow had health problems and in fact died of medical complications of an autoimmune disease (possibly related to his HGH levels) at age 22. He was reportedly in good health until the final year of his life. His brain was certainly not mature at age 6 or 8, but lets assume that it could be close enough to be considered adult if he had a magical efficient training systems and nanotech to re-arrange brain structures as needed.
So 18 weeks to 6 years. Hypothetically speaking, after all of the needed advances in technology, including nano-tech what could we do?
The answer is simply unknown since we don't have the medical knowledge of the complications of accelerated growth in an artificial womb. Perhaps with nano-technology we could control physical growth, perform the necessary muscle and bone training, deal with the psychological and sociological training. Training the interactions between the brain and eyes, ears, hands, etc. Perhaps it is also possible to teach language, reading, writing, arithmetic, etc. in the womb.
There is a huge gulf between our current state of knowledge and that needed to perform all development in the womb. And there is very little incentive to acquire it.
Parents want to watch their children grow up, play, learn from their environment, etc. I can't image any parent I know desiring to replace this process with an artificial one. |
31,355 | In my world human(oid)s are not born anymore, they are grown in pods which mirror the conditions of a natural womb.
Children are educated before birth and are "born" as fully mature adults with a standard education ready to join society.
How long would this process take? I assume that artificial growth could be much quicker than a natural 18-20 year period. Could a human be grown in a year? A decade? | 2015/12/12 | [
"https://worldbuilding.stackexchange.com/questions/31355",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/18/"
] | **18 weeks to 6 or 8 years, but it does not matter**
9 months to produce an infant is a long time compared to the initial growth rate of the embryo. At 4 weeks, the embryo is the size of a poppy seed (2 mm long), at 8 weeks, the size of a kidney bean (16 mm head to bottom). During that period, the human increased by at least a factor of 8. This is a growth rate of about 68% per week. At this rate, you are large newborn at 15 week and a full sized adult in under 18 weeks.
So, we have a reasonable lower bound of about 18 weeks and an upper bound of about 18 years. But can we find a better upper bound? Yes we can, [Robert Wadlow](https://en.wikipedia.org/wiki/Robert_Wadlow) was the tallest modern man that can be reliably documented. At age 6, he 5'7" and was already taller than his father at age 8. So 6-8 years seems like a better upper bound since people can grow that fast with too much human growth hormone.
Robert Wadlow had health problems and in fact died of medical complications of an autoimmune disease (possibly related to his HGH levels) at age 22. He was reportedly in good health until the final year of his life. His brain was certainly not mature at age 6 or 8, but lets assume that it could be close enough to be considered adult if he had a magical efficient training systems and nanotech to re-arrange brain structures as needed.
So 18 weeks to 6 years. Hypothetically speaking, after all of the needed advances in technology, including nano-tech what could we do?
The answer is simply unknown since we don't have the medical knowledge of the complications of accelerated growth in an artificial womb. Perhaps with nano-technology we could control physical growth, perform the necessary muscle and bone training, deal with the psychological and sociological training. Training the interactions between the brain and eyes, ears, hands, etc. Perhaps it is also possible to teach language, reading, writing, arithmetic, etc. in the womb.
There is a huge gulf between our current state of knowledge and that needed to perform all development in the womb. And there is very little incentive to acquire it.
Parents want to watch their children grow up, play, learn from their environment, etc. I can't image any parent I know desiring to replace this process with an artificial one. | Human growth is subject to many limiting factors, including the ability of the mother to supply the required nutrients to the foetus, and after birth, the ability of the child to acquire the full range of expected social skills.
A young human is physically small in order to convey the impression of youth to other humans. Since learning to be an adult human takes around eighteen to twenty-five years, that is how long it takes for the human body to mature fully. Size and other physical traits conveys an impression of age to others.
Now, if humans could grow to maturity and be born with all necessary knowledge to be fully functioning adults, as well as be free of the limitations of maternal nutrition, growing such a human in-vitro could occur in a relative short period of time.
In larger mammalian - and dinosaur - species where achieving an adult body-size (of several hundred kilograms to many tons) as quickly as possible is of paramount importance, very high growth rates can be achieved, with newborns achieving maturity within a handful of years, certainly within 5 years or less.
We could therefore expect that with genetic engineering - or some clever artificial stimulation - to remove the limits on pre-maturity growth-rate, a fully mature human could be produced within three years.
I should point out that if humans were genetically engineered to grow that quickly, it would effectively sterilize the population and make them dependent on artificial reproduction. Should a modified human mother become pregnant, her body would not be able to supply the huge metabolic needs that such a foetus impose on her, and a significant or even fatal loss of body mass would likely occur. Should the foetus survive, it would be no better educated than any normal human newborn.
On the other hand, if humans were grown rapidly and educated in-vitro through medical trickery rather than genetic engineering, a natural pregnancy would most likely be possible, with a normal-sized infant being born after the usual period of gestation. It is up to you if the mother would have been educated sufficiently to have the knowledge to handle a naturally-born child. |
31,355 | In my world human(oid)s are not born anymore, they are grown in pods which mirror the conditions of a natural womb.
Children are educated before birth and are "born" as fully mature adults with a standard education ready to join society.
How long would this process take? I assume that artificial growth could be much quicker than a natural 18-20 year period. Could a human be grown in a year? A decade? | 2015/12/12 | [
"https://worldbuilding.stackexchange.com/questions/31355",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/18/"
] | It **REALLY** depends on what level of technology we're talking about here.
After all, given sufficiently advanced technology, we could "build" a person, atom by atom, to have all the same properties, education, mental and motor functions etc. as if they had developed the normal way over many years.
---
Let's assume a level of technology that allows us to "develop" the brain in any way we like (including but not limited to: memories, knowledge, motor functions) as the body is growing, but which requires all the normal physical/chemical processes to take place. Albeit in an environment designed to optimise the speed/efficiency of that development.
**My guess: 2-7 years**
This is based on the fact that the environment you describe (No external interruptions, wholly optimised for and focused on development) sounds *very* similar to what we call "sleep".
Now, sleep also involves lots of other functions relating to ongoing maintenance/learning/repair which we may be able to eliminate the need for in our growth environment.
But then again, we have almost no idea of \*why\* humans need to sleep in the first place. So, I would suggest, for every day of "normal" growth, you will need a significant fraction of the time we spend sleeping, 2-8 hours or so, of "Test Tube Development Time". This yields 9%-33% of "Normal Development Time", so 2-7 years for a 20-year-old equivalent. | Human growth is subject to many limiting factors, including the ability of the mother to supply the required nutrients to the foetus, and after birth, the ability of the child to acquire the full range of expected social skills.
A young human is physically small in order to convey the impression of youth to other humans. Since learning to be an adult human takes around eighteen to twenty-five years, that is how long it takes for the human body to mature fully. Size and other physical traits conveys an impression of age to others.
Now, if humans could grow to maturity and be born with all necessary knowledge to be fully functioning adults, as well as be free of the limitations of maternal nutrition, growing such a human in-vitro could occur in a relative short period of time.
In larger mammalian - and dinosaur - species where achieving an adult body-size (of several hundred kilograms to many tons) as quickly as possible is of paramount importance, very high growth rates can be achieved, with newborns achieving maturity within a handful of years, certainly within 5 years or less.
We could therefore expect that with genetic engineering - or some clever artificial stimulation - to remove the limits on pre-maturity growth-rate, a fully mature human could be produced within three years.
I should point out that if humans were genetically engineered to grow that quickly, it would effectively sterilize the population and make them dependent on artificial reproduction. Should a modified human mother become pregnant, her body would not be able to supply the huge metabolic needs that such a foetus impose on her, and a significant or even fatal loss of body mass would likely occur. Should the foetus survive, it would be no better educated than any normal human newborn.
On the other hand, if humans were grown rapidly and educated in-vitro through medical trickery rather than genetic engineering, a natural pregnancy would most likely be possible, with a normal-sized infant being born after the usual period of gestation. It is up to you if the mother would have been educated sufficiently to have the knowledge to handle a naturally-born child. |
23,775,272 | I'm new to Modals, I have a Form and when the user clicks submit, It will show a Modal confirming if the user wants to submit, the modal also contains the user input from the form fields. I searched all over the internet but can't find the right one on my needs. And all I see is that they tag the click event to open modal on a a link. i have a input type submit. Can you give examples or ideas? Thanks! Here's my sample form.
```
<form role="form" id="formfield" action="inc/Controller/OperatorController.php" method="post" enctype="multipart/form-data" onsubmit="return validateForm();">
<input type="hidden" name="action" value="add_form" />
<div class="form-group">
<label>Last Name</label><span class="label label-danger">*required</span>
<input class="form-control" placeholder="Enter Last Name" name="lastname" id="lastname">
</div>
<div class="form-group">
<label>First Name</label><span class="label label-danger">*required</span>
<input class="form-control" placeholder="Enter First Name" name="firstname" id="firstname">
</div>
<input type="submit" name="btn" value="Submit" id="submitBtn" class="btn btn-default" data-confirm="Are you sure you want to delete?"/>
<input type="button" name="btn" value="Reset" onclick="window.location='fillup.php'" class="btn btn-default" data-modal-type="confirm"/>
</form>
``` | 2014/05/21 | [
"https://Stackoverflow.com/questions/23775272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3651491/"
] | So if I get it right, on click of a button, you want to open up a modal that lists the values entered by the users followed by submitting it.
For this, you first change your `input type="submit"` to `input type="button"` and add `data-toggle="modal" data-target="#confirm-submit"` so that the modal gets triggered when you click on it:
```
<input type="button" name="btn" value="Submit" id="submitBtn" data-toggle="modal" data-target="#confirm-submit" class="btn btn-default" />
```
Next, the modal dialog:
```
<div class="modal fade" id="confirm-submit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
Confirm Submit
</div>
<div class="modal-body">
Are you sure you want to submit the following details?
<!-- We display the details entered by the user here -->
<table class="table">
<tr>
<th>Last Name</th>
<td id="lname"></td>
</tr>
<tr>
<th>First Name</th>
<td id="fname"></td>
</tr>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<a href="#" id="submit" class="btn btn-success success">Submit</a>
</div>
</div>
</div>
</div>
```
Lastly, a little bit of jQuery:
```
$('#submitBtn').click(function() {
/* when the button in the form, display the entered values in the modal */
$('#lname').text($('#lastname').val());
$('#fname').text($('#firstname').val());
});
$('#submit').click(function(){
/* when the submit button in the modal is clicked, submit the form */
alert('submitting');
$('#formfield').submit();
});
```
You haven't specified what the function `validateForm()` does, but based on this you should restrict your form from being submitted. Or you can run that function on the form's button `#submitBtn` click and then load the modal after the validations have been checked.
**[DEMO](http://jsfiddle.net/0gct8qd8/)** | ```
$('form button[type="submit"]').on('click', function () {
$(this).parents('form').submit();
});
``` |
23,775,272 | I'm new to Modals, I have a Form and when the user clicks submit, It will show a Modal confirming if the user wants to submit, the modal also contains the user input from the form fields. I searched all over the internet but can't find the right one on my needs. And all I see is that they tag the click event to open modal on a a link. i have a input type submit. Can you give examples or ideas? Thanks! Here's my sample form.
```
<form role="form" id="formfield" action="inc/Controller/OperatorController.php" method="post" enctype="multipart/form-data" onsubmit="return validateForm();">
<input type="hidden" name="action" value="add_form" />
<div class="form-group">
<label>Last Name</label><span class="label label-danger">*required</span>
<input class="form-control" placeholder="Enter Last Name" name="lastname" id="lastname">
</div>
<div class="form-group">
<label>First Name</label><span class="label label-danger">*required</span>
<input class="form-control" placeholder="Enter First Name" name="firstname" id="firstname">
</div>
<input type="submit" name="btn" value="Submit" id="submitBtn" class="btn btn-default" data-confirm="Are you sure you want to delete?"/>
<input type="button" name="btn" value="Reset" onclick="window.location='fillup.php'" class="btn btn-default" data-modal-type="confirm"/>
</form>
``` | 2014/05/21 | [
"https://Stackoverflow.com/questions/23775272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3651491/"
] | So if I get it right, on click of a button, you want to open up a modal that lists the values entered by the users followed by submitting it.
For this, you first change your `input type="submit"` to `input type="button"` and add `data-toggle="modal" data-target="#confirm-submit"` so that the modal gets triggered when you click on it:
```
<input type="button" name="btn" value="Submit" id="submitBtn" data-toggle="modal" data-target="#confirm-submit" class="btn btn-default" />
```
Next, the modal dialog:
```
<div class="modal fade" id="confirm-submit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
Confirm Submit
</div>
<div class="modal-body">
Are you sure you want to submit the following details?
<!-- We display the details entered by the user here -->
<table class="table">
<tr>
<th>Last Name</th>
<td id="lname"></td>
</tr>
<tr>
<th>First Name</th>
<td id="fname"></td>
</tr>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<a href="#" id="submit" class="btn btn-success success">Submit</a>
</div>
</div>
</div>
</div>
```
Lastly, a little bit of jQuery:
```
$('#submitBtn').click(function() {
/* when the button in the form, display the entered values in the modal */
$('#lname').text($('#lastname').val());
$('#fname').text($('#firstname').val());
});
$('#submit').click(function(){
/* when the submit button in the modal is clicked, submit the form */
alert('submitting');
$('#formfield').submit();
});
```
You haven't specified what the function `validateForm()` does, but based on this you should restrict your form from being submitted. Or you can run that function on the form's button `#submitBtn` click and then load the modal after the validations have been checked.
**[DEMO](http://jsfiddle.net/0gct8qd8/)** | It is easy to solve, only create an hidden submit:
```
<button id="submitCadastro" type="button">ENVIAR</button>
<input type="submit" id="submitCadastroHidden" style="display: none;" >
```
with jQuery you click the submit:
```
$("#submitCadastro").click(function(){
if($("#checkDocumentos").prop("checked") == false){
//alert("Aceite os termos e condições primeiro!.");
$("#modalERROR").modal("show");
}else{
//$("#formCadastro").submit();
$("#submitCadastroHidden").click();
}
});
``` |
23,775,272 | I'm new to Modals, I have a Form and when the user clicks submit, It will show a Modal confirming if the user wants to submit, the modal also contains the user input from the form fields. I searched all over the internet but can't find the right one on my needs. And all I see is that they tag the click event to open modal on a a link. i have a input type submit. Can you give examples or ideas? Thanks! Here's my sample form.
```
<form role="form" id="formfield" action="inc/Controller/OperatorController.php" method="post" enctype="multipart/form-data" onsubmit="return validateForm();">
<input type="hidden" name="action" value="add_form" />
<div class="form-group">
<label>Last Name</label><span class="label label-danger">*required</span>
<input class="form-control" placeholder="Enter Last Name" name="lastname" id="lastname">
</div>
<div class="form-group">
<label>First Name</label><span class="label label-danger">*required</span>
<input class="form-control" placeholder="Enter First Name" name="firstname" id="firstname">
</div>
<input type="submit" name="btn" value="Submit" id="submitBtn" class="btn btn-default" data-confirm="Are you sure you want to delete?"/>
<input type="button" name="btn" value="Reset" onclick="window.location='fillup.php'" class="btn btn-default" data-modal-type="confirm"/>
</form>
``` | 2014/05/21 | [
"https://Stackoverflow.com/questions/23775272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3651491/"
] | So if I get it right, on click of a button, you want to open up a modal that lists the values entered by the users followed by submitting it.
For this, you first change your `input type="submit"` to `input type="button"` and add `data-toggle="modal" data-target="#confirm-submit"` so that the modal gets triggered when you click on it:
```
<input type="button" name="btn" value="Submit" id="submitBtn" data-toggle="modal" data-target="#confirm-submit" class="btn btn-default" />
```
Next, the modal dialog:
```
<div class="modal fade" id="confirm-submit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
Confirm Submit
</div>
<div class="modal-body">
Are you sure you want to submit the following details?
<!-- We display the details entered by the user here -->
<table class="table">
<tr>
<th>Last Name</th>
<td id="lname"></td>
</tr>
<tr>
<th>First Name</th>
<td id="fname"></td>
</tr>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<a href="#" id="submit" class="btn btn-success success">Submit</a>
</div>
</div>
</div>
</div>
```
Lastly, a little bit of jQuery:
```
$('#submitBtn').click(function() {
/* when the button in the form, display the entered values in the modal */
$('#lname').text($('#lastname').val());
$('#fname').text($('#firstname').val());
});
$('#submit').click(function(){
/* when the submit button in the modal is clicked, submit the form */
alert('submitting');
$('#formfield').submit();
});
```
You haven't specified what the function `validateForm()` does, but based on this you should restrict your form from being submitted. Or you can run that function on the form's button `#submitBtn` click and then load the modal after the validations have been checked.
**[DEMO](http://jsfiddle.net/0gct8qd8/)** | I noticed some of the answers were not triggering the HTML5 `required` attribute (as stuff was being executed on the action of *clicking* rather than the action of *form send*, causing to bypass it when the inputs were empty):
1. Have a `<form id='xform'></form>` with some inputs with the required attribute and place a `<input type='submit'>` at the end.
2. A confirmation input where typing "ok" is expected `<input type='text' name='xconf' value='' required>`
3. Add a **modal\_1\_confirm** to your html (to confirm the form of sending).
4. (on modal\_1\_confirm) add the **id** `modal_1_accept` to the accept button.
5. Add a second **modal\_2\_errMsg** to your html (to display form validation errors).
6. (on modal\_2\_errMsg) add the **id** `modal_2_accept` to the accept button.
7. (on modal\_2\_errMsg) add the **id** `m2_Txt` to the displayed text holder.
8. The JS to intercept before the form is sent:
```
$("#xform").submit(function(e){
var msg, conf, preventSend;
if($("#xform").attr("data-send")!=="ready"){
msg="Error."; //default error msg
preventSend=false;
conf=$("[name='xconf']").val().toLowerCase().replace(/^"|"$/g, "");
if(conf===""){
msg="The field is empty.";
preventSend=true;
}else if(conf!=="ok"){
msg="You didn't write \"ok\" correctly.";
preventSend=true;
}
if(preventSend){ //validation failed, show the error
$("#m2_Txt").html(msg); //displayed text on modal_2_errMsg
$("#modal_2_errMsg").modal("show");
}else{ //validation passed, now let's confirm the action
$("#modal_1_confirm").modal("show");
}
e.preventDefault();
return false;
}
});
```
`9. Also some stuff when clicking the Buttons from the modals:
```
$("#modal_1_accept").click(function(){
$("#modal_1_confirm").modal("hide");
$("#xform").attr("data-send", "ready").submit();
});
$("#modal_2_accept").click(function(){
$("#modal_2_errMsg").modal("hide");
});
```
**Important Note:** So just be careful if you add an extra way to show the modal, as simply clicking the accept button `$("#modal_1_accept")` will assume the validation passed and it will add the `"ready"` attribute:
* The reasoning for this is that `$("#modal_1_confirm").modal("show");` is shown *only* when it passed
the validation, so clicking `$("#modal_1_accept")` should be
unreachable without first getting the form validated. |
23,775,272 | I'm new to Modals, I have a Form and when the user clicks submit, It will show a Modal confirming if the user wants to submit, the modal also contains the user input from the form fields. I searched all over the internet but can't find the right one on my needs. And all I see is that they tag the click event to open modal on a a link. i have a input type submit. Can you give examples or ideas? Thanks! Here's my sample form.
```
<form role="form" id="formfield" action="inc/Controller/OperatorController.php" method="post" enctype="multipart/form-data" onsubmit="return validateForm();">
<input type="hidden" name="action" value="add_form" />
<div class="form-group">
<label>Last Name</label><span class="label label-danger">*required</span>
<input class="form-control" placeholder="Enter Last Name" name="lastname" id="lastname">
</div>
<div class="form-group">
<label>First Name</label><span class="label label-danger">*required</span>
<input class="form-control" placeholder="Enter First Name" name="firstname" id="firstname">
</div>
<input type="submit" name="btn" value="Submit" id="submitBtn" class="btn btn-default" data-confirm="Are you sure you want to delete?"/>
<input type="button" name="btn" value="Reset" onclick="window.location='fillup.php'" class="btn btn-default" data-modal-type="confirm"/>
</form>
``` | 2014/05/21 | [
"https://Stackoverflow.com/questions/23775272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3651491/"
] | So if I get it right, on click of a button, you want to open up a modal that lists the values entered by the users followed by submitting it.
For this, you first change your `input type="submit"` to `input type="button"` and add `data-toggle="modal" data-target="#confirm-submit"` so that the modal gets triggered when you click on it:
```
<input type="button" name="btn" value="Submit" id="submitBtn" data-toggle="modal" data-target="#confirm-submit" class="btn btn-default" />
```
Next, the modal dialog:
```
<div class="modal fade" id="confirm-submit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
Confirm Submit
</div>
<div class="modal-body">
Are you sure you want to submit the following details?
<!-- We display the details entered by the user here -->
<table class="table">
<tr>
<th>Last Name</th>
<td id="lname"></td>
</tr>
<tr>
<th>First Name</th>
<td id="fname"></td>
</tr>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<a href="#" id="submit" class="btn btn-success success">Submit</a>
</div>
</div>
</div>
</div>
```
Lastly, a little bit of jQuery:
```
$('#submitBtn').click(function() {
/* when the button in the form, display the entered values in the modal */
$('#lname').text($('#lastname').val());
$('#fname').text($('#firstname').val());
});
$('#submit').click(function(){
/* when the submit button in the modal is clicked, submit the form */
alert('submitting');
$('#formfield').submit();
});
```
You haven't specified what the function `validateForm()` does, but based on this you should restrict your form from being submitted. Or you can run that function on the form's button `#submitBtn` click and then load the modal after the validations have been checked.
**[DEMO](http://jsfiddle.net/0gct8qd8/)** | You can use browser default prompt window.
Instead of basic `<input type="submit" (...) >` try:
```
<button onClick="if(confirm(\'are you sure ?\')){ this.form.submit() }">Save</button>
``` |
23,775,272 | I'm new to Modals, I have a Form and when the user clicks submit, It will show a Modal confirming if the user wants to submit, the modal also contains the user input from the form fields. I searched all over the internet but can't find the right one on my needs. And all I see is that they tag the click event to open modal on a a link. i have a input type submit. Can you give examples or ideas? Thanks! Here's my sample form.
```
<form role="form" id="formfield" action="inc/Controller/OperatorController.php" method="post" enctype="multipart/form-data" onsubmit="return validateForm();">
<input type="hidden" name="action" value="add_form" />
<div class="form-group">
<label>Last Name</label><span class="label label-danger">*required</span>
<input class="form-control" placeholder="Enter Last Name" name="lastname" id="lastname">
</div>
<div class="form-group">
<label>First Name</label><span class="label label-danger">*required</span>
<input class="form-control" placeholder="Enter First Name" name="firstname" id="firstname">
</div>
<input type="submit" name="btn" value="Submit" id="submitBtn" class="btn btn-default" data-confirm="Are you sure you want to delete?"/>
<input type="button" name="btn" value="Reset" onclick="window.location='fillup.php'" class="btn btn-default" data-modal-type="confirm"/>
</form>
``` | 2014/05/21 | [
"https://Stackoverflow.com/questions/23775272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3651491/"
] | You can use browser default prompt window.
Instead of basic `<input type="submit" (...) >` try:
```
<button onClick="if(confirm(\'are you sure ?\')){ this.form.submit() }">Save</button>
``` | ```
$('form button[type="submit"]').on('click', function () {
$(this).parents('form').submit();
});
``` |
23,775,272 | I'm new to Modals, I have a Form and when the user clicks submit, It will show a Modal confirming if the user wants to submit, the modal also contains the user input from the form fields. I searched all over the internet but can't find the right one on my needs. And all I see is that they tag the click event to open modal on a a link. i have a input type submit. Can you give examples or ideas? Thanks! Here's my sample form.
```
<form role="form" id="formfield" action="inc/Controller/OperatorController.php" method="post" enctype="multipart/form-data" onsubmit="return validateForm();">
<input type="hidden" name="action" value="add_form" />
<div class="form-group">
<label>Last Name</label><span class="label label-danger">*required</span>
<input class="form-control" placeholder="Enter Last Name" name="lastname" id="lastname">
</div>
<div class="form-group">
<label>First Name</label><span class="label label-danger">*required</span>
<input class="form-control" placeholder="Enter First Name" name="firstname" id="firstname">
</div>
<input type="submit" name="btn" value="Submit" id="submitBtn" class="btn btn-default" data-confirm="Are you sure you want to delete?"/>
<input type="button" name="btn" value="Reset" onclick="window.location='fillup.php'" class="btn btn-default" data-modal-type="confirm"/>
</form>
``` | 2014/05/21 | [
"https://Stackoverflow.com/questions/23775272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3651491/"
] | You can use browser default prompt window.
Instead of basic `<input type="submit" (...) >` try:
```
<button onClick="if(confirm(\'are you sure ?\')){ this.form.submit() }">Save</button>
``` | It is easy to solve, only create an hidden submit:
```
<button id="submitCadastro" type="button">ENVIAR</button>
<input type="submit" id="submitCadastroHidden" style="display: none;" >
```
with jQuery you click the submit:
```
$("#submitCadastro").click(function(){
if($("#checkDocumentos").prop("checked") == false){
//alert("Aceite os termos e condições primeiro!.");
$("#modalERROR").modal("show");
}else{
//$("#formCadastro").submit();
$("#submitCadastroHidden").click();
}
});
``` |
23,775,272 | I'm new to Modals, I have a Form and when the user clicks submit, It will show a Modal confirming if the user wants to submit, the modal also contains the user input from the form fields. I searched all over the internet but can't find the right one on my needs. And all I see is that they tag the click event to open modal on a a link. i have a input type submit. Can you give examples or ideas? Thanks! Here's my sample form.
```
<form role="form" id="formfield" action="inc/Controller/OperatorController.php" method="post" enctype="multipart/form-data" onsubmit="return validateForm();">
<input type="hidden" name="action" value="add_form" />
<div class="form-group">
<label>Last Name</label><span class="label label-danger">*required</span>
<input class="form-control" placeholder="Enter Last Name" name="lastname" id="lastname">
</div>
<div class="form-group">
<label>First Name</label><span class="label label-danger">*required</span>
<input class="form-control" placeholder="Enter First Name" name="firstname" id="firstname">
</div>
<input type="submit" name="btn" value="Submit" id="submitBtn" class="btn btn-default" data-confirm="Are you sure you want to delete?"/>
<input type="button" name="btn" value="Reset" onclick="window.location='fillup.php'" class="btn btn-default" data-modal-type="confirm"/>
</form>
``` | 2014/05/21 | [
"https://Stackoverflow.com/questions/23775272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3651491/"
] | You can use browser default prompt window.
Instead of basic `<input type="submit" (...) >` try:
```
<button onClick="if(confirm(\'are you sure ?\')){ this.form.submit() }">Save</button>
``` | I noticed some of the answers were not triggering the HTML5 `required` attribute (as stuff was being executed on the action of *clicking* rather than the action of *form send*, causing to bypass it when the inputs were empty):
1. Have a `<form id='xform'></form>` with some inputs with the required attribute and place a `<input type='submit'>` at the end.
2. A confirmation input where typing "ok" is expected `<input type='text' name='xconf' value='' required>`
3. Add a **modal\_1\_confirm** to your html (to confirm the form of sending).
4. (on modal\_1\_confirm) add the **id** `modal_1_accept` to the accept button.
5. Add a second **modal\_2\_errMsg** to your html (to display form validation errors).
6. (on modal\_2\_errMsg) add the **id** `modal_2_accept` to the accept button.
7. (on modal\_2\_errMsg) add the **id** `m2_Txt` to the displayed text holder.
8. The JS to intercept before the form is sent:
```
$("#xform").submit(function(e){
var msg, conf, preventSend;
if($("#xform").attr("data-send")!=="ready"){
msg="Error."; //default error msg
preventSend=false;
conf=$("[name='xconf']").val().toLowerCase().replace(/^"|"$/g, "");
if(conf===""){
msg="The field is empty.";
preventSend=true;
}else if(conf!=="ok"){
msg="You didn't write \"ok\" correctly.";
preventSend=true;
}
if(preventSend){ //validation failed, show the error
$("#m2_Txt").html(msg); //displayed text on modal_2_errMsg
$("#modal_2_errMsg").modal("show");
}else{ //validation passed, now let's confirm the action
$("#modal_1_confirm").modal("show");
}
e.preventDefault();
return false;
}
});
```
`9. Also some stuff when clicking the Buttons from the modals:
```
$("#modal_1_accept").click(function(){
$("#modal_1_confirm").modal("hide");
$("#xform").attr("data-send", "ready").submit();
});
$("#modal_2_accept").click(function(){
$("#modal_2_errMsg").modal("hide");
});
```
**Important Note:** So just be careful if you add an extra way to show the modal, as simply clicking the accept button `$("#modal_1_accept")` will assume the validation passed and it will add the `"ready"` attribute:
* The reasoning for this is that `$("#modal_1_confirm").modal("show");` is shown *only* when it passed
the validation, so clicking `$("#modal_1_accept")` should be
unreachable without first getting the form validated. |
22,168,437 | We have a Java project that we wish to distribute to users. It does not use any Java features beyond Java 1.5, so we wish it to run on Java 1.5 and above.
At this point, you might rightfully note that Java 1.6 is the oldest available currently, so why target Java 1.5? However, that does not change the generic nature of the question of cross-compiling for older versions.
So, the way one usually starts cross-compilation attempts is by specifying `-source 1.5` and `-target 1.5` options to `javac`, at which point one gets a famous warning about `-bootclasspath` not being set:
```
$ javac -source 1.5 -target 1.5 Test.java
warning: [options] bootstrap class path not set in conjunction with -source 1.5
1 warning
```
Now, according to [Oracle blog post](https://blogs.oracle.com/darcy/entry/bootclasspath_older_source), as well as [official documentation](http://docs.oracle.com/javase/7/docs/technotes/tools/solaris/javac.html#crosscomp-example), the correct practice for cross-compilation is to:
>
> To use javac from JDK N to cross-compiler to an older platform version, the correct practice is to:
>
>
> * Use the older -source setting.
> * Set the bootclasspath to compile against the rt.jar (or equivalent) for the older platform.
>
>
> If the second step is not taken, javac will dutifully use the old language rules combined with new libraries, which can result in class files that do not work on the older platform since references to non-existent methods can get included.
>
>
>
For instance, quoting official documentation:
```
% javac -source 1.6 -target 1.6 -bootclasspath jdk1.6.0/lib/rt.jar \
-extdirs "" OldCode.java
```
This is great and has been answered many times before both on Stack Overflow and the rest of the Internet.
However, none of the resources we have found seem to indicate where to actually find the `rt.jar` for older versions of Java. As an example, JDK 1.7 does not ship with `rt.jar` except its own:
```
$ find jdk-1.7.0_45 -name rt.jar
jdk-1.7.0_45/jre/lib/rt.jar
```
That makes one think that in order to obtain `rt.jar` for Java 1.6, for instance, one needs to download JDK 1.6. But then two questions arise:
1. if we download JDK 1.6, we might as well use that for compilation instead of JDK 1.7;
2. if we wish to cross-compile for Java 1.5, then JDK 1.5 is no longer available for download.
So, how do we actually specify `-bootclasspath` option to use this cross-compilation feature? | 2014/03/04 | [
"https://Stackoverflow.com/questions/22168437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1307749/"
] | The rt.jar is included with the JRE. You will be able to perform the cross compilation if you have, say, JDK 1.6 and JRE 1.5.
Using your JDK 1.6:
```
$ javac -source 1.5 -target 1.5 -bootclasspath jre1.5.0/lib/rt.jar Test.java
```
The advantage here is that the JRE can be as little as 1/3 the size of a full JDK. You can often remove old JDK versions without removing old JRE versions.
If you need to get hold of an old JRE, they can be found following links on the Java Archive page <http://www.oracle.com/technetwork/java/javase/archive-139210.html> | This type of compilation is primarily motivated by needing to target a JRE that is already in production or an otherwise existing install, IME. In that case, pulling the JRE bootclasspath files from the existing install and making them available from the build system(s) would be the first task. The bootclasspath value you specify will depend on where you put the JRE bootclasspath files during that step.
FYI, you may need quite a few more files than just rt.jar. E.g., when targeting IBM Java 6. |
38,470,462 | I have the following:
```
public class Car{
public Car()
{//some stuff
}
private Car [] carmodels ;
public Car [] getCarModel() {
return this.carmodels;
}
public void setcarModel(Car [] carmodels ) {
this.carmodels = carmodels;
}
```
Now on my test class, I have something like this
```
public void main (String [] args)
{
Car car1= new Car();
car.setcarModel(new Car[5]);//here i create an array of Car
for(int i =0;i<5;i++)
{
// how can i created 5 cars and set them based on index i
// car.setCarModel[new Car()]????
}
}
```
How can do that? I could use a temp array of type Car which I can pass to my Setter just after the loop. But is there a better way? | 2016/07/20 | [
"https://Stackoverflow.com/questions/38470462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3841581/"
] | If you insist on not using a temp value in the for loop you could use an [ArrayList](https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html) instead of an array for the carmodels.
than add a method
```
public void addCar(Car toadd)
{
carmodels.add(toadd);
}
```
than in your foor loop just call
```
for(int i =0;i<5;i++)
{
car.addCar(new Car());
}
```
Im assuming the size can vary and that a fixed size array is not sufficient. | ```
for(int i =0;i<5;i++)
{
car.getCarModel()[i] =new Car();
}
```
or
Write another overloaded setter by passing index.
```
public void setCarModel(int index, Car c)
{
carmodels[index] = c;
}
for(int i =0;i<5;i++)
{
car.setCarModel(i, new Car());
}
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.