qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
36,406,041 | I got a small piece of code from here <https://github.com/shellphish/how2heap/blob/master/fastbin_dup.c>
```
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("This file demonstrates a simple double-free attack with fastbins.\n");
printf("Allocating 3 buffers.\n");
int *a = malloc(8);
int *b = malloc(8);
int *c = malloc(8);
printf("1st malloc(8): %p\n", a);
printf("2nd malloc(8): %p\n", b);
printf("3rd malloc(8): %p\n", c);
printf("Freeing the first one...\n");
free(a);
printf("If we free %p again, things will crash because %p is at the top of the free list.\n", a, a);
// free(a);
printf("So, instead, we'll free %p.\n", b);
free(b);
printf("Now, we can free %p again, since it's not the head of the free list.\n", a);
free(a);
printf("Now the free list has [ %p, %p, %p ]. If we malloc 3 times, we'll get %p twice!\n", a, b, a, a);
printf("1st malloc(8): %p\n", malloc(8));
printf("2nd malloc(8): %p\n", malloc(8));
printf("3rd malloc(8): %p\n", malloc(8));
}
```
1. Why can I not free A twice in a row?
2. Why can I free A again after freeing B?
3. Why get I back the same chunk twice if I malloc again?
Thanks! | 2016/04/04 | [
"https://Stackoverflow.com/questions/36406041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2600312/"
] | This is a compiler specific "exploit". First, let's call out the elephant in the room:
1. You're intentionally using undefined behavior (UB), so from that point forward, all bets are off.
2. You're not using any static code analysis tools like [`cppcheck`](http://cppcheck.sourceforge.net/) or lint, nor any debugging tools like [valgrind](http://valgrind.org/) to catch this. In production systems, you would use such tools to at least attempt to catch these bugs.
3. You can always pull the latest [glibc source](https://ftp.gnu.org/gnu/glibc/) and discover this for your yourself :)
Now, to the question. First, this exploit only really works on GCC with "fastbins" enabled. If you just add the following to your code:
```
#include <malloc.h>
// ...
mallopt(M_MXFAST, 0);
```
Then it will crash much sooner:
```
This file demonstrates a simple double-free attack with fastbins.
Allocating 3 buffers.
1st malloc(8): 0x556f373b1010
2nd malloc(8): 0x556f373b1030
3rd malloc(8): 0x556f373b1050
Freeing the first one...
If we free 0x556f373b1010 again, things will crash because 0x556f373b1010 is at the top of the free list.
So, instead, we'll free 0x556f373b1030.
Now, we can free 0x556f373b1010 again, since it's not the head of the free list.
*** Error in `./a.out': double free or corruption (!prev): 0x0000556f373b1010 ***
Aborted (core dumped)
```
This is due to how the "fastbins" work:
>
> M\_MXFAST (since glibc 2.3)
> Set the upper limit for memory allocation requests that are
> satisfied using "fastbins". (The measurement unit for this
> parameter is bytes.) Fastbins are storage areas that hold
> deallocated blocks of memory of the same size without merging
> adjacent free blocks. Subsequent reallocation of blocks of
> the same size can be handled very quickly by allocating from
> the fastbin, although memory fragmentation and the overall
> memory footprint of the program can increase. The default
> value for this parameter is 64\*sizeof(size\_t)/4 (i.e., 64 on
> 32-bit architectures). The range for this parameter is 0 to
> 80\*sizeof(size\_t)/4. Setting M\_MXFAST to 0 disables the use
> of fastbins.
>
>
>
The free call doesn't immediately release the memory, and just marks it as being available for future `malloc()` calls. If you immediately try to issue the `free()` call against the same chunk of memory twice in a row, an internal pointer check will catch it, but the damage has already been done (UB invoked), yet the same check won't handle the example case you presented.
As for the final 3 `malloc()` calls generating the same address twice: UB has been invoked, and has corrupted the free list. | As recommended by DevNull, static code analysis can assist you be detecting potential coding issues. Here is the output of cppcheck when your code is scanned:
```
$ cppcheck --enable=all test.cpp
Checking test.cpp...
[test.cpp:27]: (error) Memory pointed to by 'a' is freed twice.
[test.cpp:33]: (error) Memory leak: c
[test.cpp:30]: (error) Allocation with malloc, printf doesn't release it.
[test.cpp:27]: (error) Deallocating a deallocated pointer: a
``` |
36,406,041 | I got a small piece of code from here <https://github.com/shellphish/how2heap/blob/master/fastbin_dup.c>
```
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("This file demonstrates a simple double-free attack with fastbins.\n");
printf("Allocating 3 buffers.\n");
int *a = malloc(8);
int *b = malloc(8);
int *c = malloc(8);
printf("1st malloc(8): %p\n", a);
printf("2nd malloc(8): %p\n", b);
printf("3rd malloc(8): %p\n", c);
printf("Freeing the first one...\n");
free(a);
printf("If we free %p again, things will crash because %p is at the top of the free list.\n", a, a);
// free(a);
printf("So, instead, we'll free %p.\n", b);
free(b);
printf("Now, we can free %p again, since it's not the head of the free list.\n", a);
free(a);
printf("Now the free list has [ %p, %p, %p ]. If we malloc 3 times, we'll get %p twice!\n", a, b, a, a);
printf("1st malloc(8): %p\n", malloc(8));
printf("2nd malloc(8): %p\n", malloc(8));
printf("3rd malloc(8): %p\n", malloc(8));
}
```
1. Why can I not free A twice in a row?
2. Why can I free A again after freeing B?
3. Why get I back the same chunk twice if I malloc again?
Thanks! | 2016/04/04 | [
"https://Stackoverflow.com/questions/36406041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2600312/"
] | This is a compiler specific "exploit". First, let's call out the elephant in the room:
1. You're intentionally using undefined behavior (UB), so from that point forward, all bets are off.
2. You're not using any static code analysis tools like [`cppcheck`](http://cppcheck.sourceforge.net/) or lint, nor any debugging tools like [valgrind](http://valgrind.org/) to catch this. In production systems, you would use such tools to at least attempt to catch these bugs.
3. You can always pull the latest [glibc source](https://ftp.gnu.org/gnu/glibc/) and discover this for your yourself :)
Now, to the question. First, this exploit only really works on GCC with "fastbins" enabled. If you just add the following to your code:
```
#include <malloc.h>
// ...
mallopt(M_MXFAST, 0);
```
Then it will crash much sooner:
```
This file demonstrates a simple double-free attack with fastbins.
Allocating 3 buffers.
1st malloc(8): 0x556f373b1010
2nd malloc(8): 0x556f373b1030
3rd malloc(8): 0x556f373b1050
Freeing the first one...
If we free 0x556f373b1010 again, things will crash because 0x556f373b1010 is at the top of the free list.
So, instead, we'll free 0x556f373b1030.
Now, we can free 0x556f373b1010 again, since it's not the head of the free list.
*** Error in `./a.out': double free or corruption (!prev): 0x0000556f373b1010 ***
Aborted (core dumped)
```
This is due to how the "fastbins" work:
>
> M\_MXFAST (since glibc 2.3)
> Set the upper limit for memory allocation requests that are
> satisfied using "fastbins". (The measurement unit for this
> parameter is bytes.) Fastbins are storage areas that hold
> deallocated blocks of memory of the same size without merging
> adjacent free blocks. Subsequent reallocation of blocks of
> the same size can be handled very quickly by allocating from
> the fastbin, although memory fragmentation and the overall
> memory footprint of the program can increase. The default
> value for this parameter is 64\*sizeof(size\_t)/4 (i.e., 64 on
> 32-bit architectures). The range for this parameter is 0 to
> 80\*sizeof(size\_t)/4. Setting M\_MXFAST to 0 disables the use
> of fastbins.
>
>
>
The free call doesn't immediately release the memory, and just marks it as being available for future `malloc()` calls. If you immediately try to issue the `free()` call against the same chunk of memory twice in a row, an internal pointer check will catch it, but the damage has already been done (UB invoked), yet the same check won't handle the example case you presented.
As for the final 3 `malloc()` calls generating the same address twice: UB has been invoked, and has corrupted the free list. | The previous answers don't actually explain. Here:
**Why can I not free A twice in a row?**
Because the glibc implementation contains basic checks to make sure that when a chunk is added to the freelist, it's not already on that list (you end up with a self-referential pointer). It's not a security defense as such, but more a fortunate protection against an obvious bug
**Why can I free A again after freeing B?**
because A won't be adjacent to A on the freelist. The freelist will look like:
```
-->A-->B-->A
```
So there won't be any self-referential pointers
**Why get I back the same chunk twice if I malloc again?**
When you request the first chunk, you get A, then B, then A. It's simply "popping" the next item from the freelist. |
36,406,041 | I got a small piece of code from here <https://github.com/shellphish/how2heap/blob/master/fastbin_dup.c>
```
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("This file demonstrates a simple double-free attack with fastbins.\n");
printf("Allocating 3 buffers.\n");
int *a = malloc(8);
int *b = malloc(8);
int *c = malloc(8);
printf("1st malloc(8): %p\n", a);
printf("2nd malloc(8): %p\n", b);
printf("3rd malloc(8): %p\n", c);
printf("Freeing the first one...\n");
free(a);
printf("If we free %p again, things will crash because %p is at the top of the free list.\n", a, a);
// free(a);
printf("So, instead, we'll free %p.\n", b);
free(b);
printf("Now, we can free %p again, since it's not the head of the free list.\n", a);
free(a);
printf("Now the free list has [ %p, %p, %p ]. If we malloc 3 times, we'll get %p twice!\n", a, b, a, a);
printf("1st malloc(8): %p\n", malloc(8));
printf("2nd malloc(8): %p\n", malloc(8));
printf("3rd malloc(8): %p\n", malloc(8));
}
```
1. Why can I not free A twice in a row?
2. Why can I free A again after freeing B?
3. Why get I back the same chunk twice if I malloc again?
Thanks! | 2016/04/04 | [
"https://Stackoverflow.com/questions/36406041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2600312/"
] | The previous answers don't actually explain. Here:
**Why can I not free A twice in a row?**
Because the glibc implementation contains basic checks to make sure that when a chunk is added to the freelist, it's not already on that list (you end up with a self-referential pointer). It's not a security defense as such, but more a fortunate protection against an obvious bug
**Why can I free A again after freeing B?**
because A won't be adjacent to A on the freelist. The freelist will look like:
```
-->A-->B-->A
```
So there won't be any self-referential pointers
**Why get I back the same chunk twice if I malloc again?**
When you request the first chunk, you get A, then B, then A. It's simply "popping" the next item from the freelist. | As recommended by DevNull, static code analysis can assist you be detecting potential coding issues. Here is the output of cppcheck when your code is scanned:
```
$ cppcheck --enable=all test.cpp
Checking test.cpp...
[test.cpp:27]: (error) Memory pointed to by 'a' is freed twice.
[test.cpp:33]: (error) Memory leak: c
[test.cpp:30]: (error) Allocation with malloc, printf doesn't release it.
[test.cpp:27]: (error) Deallocating a deallocated pointer: a
``` |
26,514,021 | My question is, given i have the following php code to compare two strings:
```
$cadena1='JUAN LÓPEZ YÁÑEZ';
$cadena2='JUAN LOPEZ YÁÑEZ';
if($cadena1===$cadena2){
echo '<p style="color: green;">The strings match!</p>';
}else{
echo '<p style="color: red;">The strings do not match. Accent sensitive?</p>';
}
```
I notice for example that if I compare *LOPEZ* and *LÓPEZ* then the comparison turns to false.
Is there a way or a function already there to compare these strings regardless of the Spanish accents? | 2014/10/22 | [
"https://Stackoverflow.com/questions/26514021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1883256/"
] | I would replace all accents in your strings before comparing them. You can do that using the following code:
```
$replacements = array('Ó'=>'O', 'Á'=>'A', 'Ñ' => 'N'); //Add the remaining Spanish accents.
$output = strtr("JUAN LÓPEZ YÁÑEZ",$replacements);
```
`output` will now be equal to `cadena2`. | Try this function from <http://sourcecookbook.com/en/recipes/8/function-to-slugify-strings-in-php>. It will replace non-ASCII characters with ASCII characters in string.
```
$cadena1='JUAN LÓPEZ YÁÑEZ';
$cadena2='JUAN LOPEZ YÁÑEZ';
function slugify( $text ) {
// replace non letter or digits by -
$text = preg_replace('~[^\\pL\d]+~u', '-', $text);
$text = trim($text, '-');
/**
* //IGNORE//TRANSLIT to avoid errors on non translatable characters and still translate other characters
* //TRANSLIT to out_charset transliteration is activated
* //IGNORE, characters that cannot be represented in the target charset are silently discarded
*/
$text = iconv('utf-8', 'ASCII//IGNORE//TRANSLIT', $text);
$text = strtolower(trim($text));
// remove unwanted characters
$text = preg_replace('~[^-\w]+~', '', $text);
return empty($text) ? '' : $text;
}
var_dump( slugify( $cadena1 ) ); // string(16) "juan-lopez-yanez"
var_dump( slugify( $cadena2 ) ); // string(16) "juan-lopez-yanez"
``` |
26,514,021 | My question is, given i have the following php code to compare two strings:
```
$cadena1='JUAN LÓPEZ YÁÑEZ';
$cadena2='JUAN LOPEZ YÁÑEZ';
if($cadena1===$cadena2){
echo '<p style="color: green;">The strings match!</p>';
}else{
echo '<p style="color: red;">The strings do not match. Accent sensitive?</p>';
}
```
I notice for example that if I compare *LOPEZ* and *LÓPEZ* then the comparison turns to false.
Is there a way or a function already there to compare these strings regardless of the Spanish accents? | 2014/10/22 | [
"https://Stackoverflow.com/questions/26514021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1883256/"
] | Why not just use collations from intl extension, Collator class?
* with a primary level to ignore accents **and** case
* with a primary level and set Collator::CASE\_LEVEL attribute to On to ignore accents but not case
(and so on - see ICU or PHP documentation for details)
```
$cadena1 = 'JUAN LÓPEZ YÁÑEZ';
$cadena2 = 'JUAN LOPEZ YÁÑEZ';
$coll = new Collator('es_ES');
$coll->setStrength(Collator::PRIMARY);
//$coll->setAttribute(Collator::CASE_LEVEL, Collator::ON);
var_dump($coll->compare($cadena1, $cadena2)); // 0 = equals
```
(of course, the strings have to be UTF-8 encoded) | Try this function from <http://sourcecookbook.com/en/recipes/8/function-to-slugify-strings-in-php>. It will replace non-ASCII characters with ASCII characters in string.
```
$cadena1='JUAN LÓPEZ YÁÑEZ';
$cadena2='JUAN LOPEZ YÁÑEZ';
function slugify( $text ) {
// replace non letter or digits by -
$text = preg_replace('~[^\\pL\d]+~u', '-', $text);
$text = trim($text, '-');
/**
* //IGNORE//TRANSLIT to avoid errors on non translatable characters and still translate other characters
* //TRANSLIT to out_charset transliteration is activated
* //IGNORE, characters that cannot be represented in the target charset are silently discarded
*/
$text = iconv('utf-8', 'ASCII//IGNORE//TRANSLIT', $text);
$text = strtolower(trim($text));
// remove unwanted characters
$text = preg_replace('~[^-\w]+~', '', $text);
return empty($text) ? '' : $text;
}
var_dump( slugify( $cadena1 ) ); // string(16) "juan-lopez-yanez"
var_dump( slugify( $cadena2 ) ); // string(16) "juan-lopez-yanez"
``` |
26,514,021 | My question is, given i have the following php code to compare two strings:
```
$cadena1='JUAN LÓPEZ YÁÑEZ';
$cadena2='JUAN LOPEZ YÁÑEZ';
if($cadena1===$cadena2){
echo '<p style="color: green;">The strings match!</p>';
}else{
echo '<p style="color: red;">The strings do not match. Accent sensitive?</p>';
}
```
I notice for example that if I compare *LOPEZ* and *LÓPEZ* then the comparison turns to false.
Is there a way or a function already there to compare these strings regardless of the Spanish accents? | 2014/10/22 | [
"https://Stackoverflow.com/questions/26514021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1883256/"
] | I would replace all accents in your strings before comparing them. You can do that using the following code:
```
$replacements = array('Ó'=>'O', 'Á'=>'A', 'Ñ' => 'N'); //Add the remaining Spanish accents.
$output = strtr("JUAN LÓPEZ YÁÑEZ",$replacements);
```
`output` will now be equal to `cadena2`. | I had the same issue:
the following messages are compared as no-equal.
```
$var1= "Utilizar preferentemente la vacuna Td (toxoides tetánico y diftérico) o, si no está disponible, la vacuna TT (toxoide tetánico).";
$var2 = "Utilizar preferentemente la vacuna Td (toxoides tetánico y diftérico) o, si no está disponible, la vacuna TT (toxoide tetánico).";
if(strcmp($var1, $var2) == 0 ) {
echo "they are Equal!";
}else {
echo "they are NOT Equal!";
}
```
the result is "they are NOT Equal!".
I tried the mentioned solution with intl but unfortunately didn't work. but the following solution helped me.
```
$var1 = iconv('UTF-8','ASCII//TRANSLIT',$var1);
$var2 = iconv('UTF-8','ASCII//TRANSLIT',$var2);
if(strcmp($var1, $var2) == 0 ) {
echo "they are Equal!";
}else {
echo "they are NOT Equal!";
}
```
This time they are equal! |
26,514,021 | My question is, given i have the following php code to compare two strings:
```
$cadena1='JUAN LÓPEZ YÁÑEZ';
$cadena2='JUAN LOPEZ YÁÑEZ';
if($cadena1===$cadena2){
echo '<p style="color: green;">The strings match!</p>';
}else{
echo '<p style="color: red;">The strings do not match. Accent sensitive?</p>';
}
```
I notice for example that if I compare *LOPEZ* and *LÓPEZ* then the comparison turns to false.
Is there a way or a function already there to compare these strings regardless of the Spanish accents? | 2014/10/22 | [
"https://Stackoverflow.com/questions/26514021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1883256/"
] | The two strings compare to false because they are actually different sequence of bytes. To compare them, you need to normalize them in any way.
The best way to do that is to use the Transliterator class, part of the `intl` extension on PHP 5.4+.
A test code:
```
<?php
$transliterator = Transliterator::createFromRules(':: NFD; :: [:Nonspacing Mark:] Remove; :: NFC;', Transliterator::FORWARD);
$test = ['abcd', 'èe', '€', 'àòùìéëü', 'àòùìéëü', 'tiësto'];
foreach($test as $e) {
$normalized = $transliterator->transliterate($e);
echo $e. ' --> '.$normalized."\n";
}
?>
```
Result:
```
abcd --> abcd
èe --> ee
€ --> €
àòùìéëü --> aouieeu
àòùìéëü --> aouieeu
tiësto --> tiesto
```
(taken from my answer here: [mySQL - matching latin (english) form input to utf8 (non-English) data](https://stackoverflow.com/questions/26185163/mysql-matching-latin-english-form-input-to-utf8-non-english-data/26186456#26186456) )
This replaces characters according to the tables of the ICU library, which are extremely complete and well-tested. Before transliterating, this normalizes the string, so it matches any possible way to represent characters like ñ (ñ, for example, can be represented with 1 multibyte character or as the combination of the two characters ˜ and n).
Unlike using soundex(), which is also very resource-intense, this does not compare sounds, so it's more accurate. | Why not just use collations from intl extension, Collator class?
* with a primary level to ignore accents **and** case
* with a primary level and set Collator::CASE\_LEVEL attribute to On to ignore accents but not case
(and so on - see ICU or PHP documentation for details)
```
$cadena1 = 'JUAN LÓPEZ YÁÑEZ';
$cadena2 = 'JUAN LOPEZ YÁÑEZ';
$coll = new Collator('es_ES');
$coll->setStrength(Collator::PRIMARY);
//$coll->setAttribute(Collator::CASE_LEVEL, Collator::ON);
var_dump($coll->compare($cadena1, $cadena2)); // 0 = equals
```
(of course, the strings have to be UTF-8 encoded) |
26,514,021 | My question is, given i have the following php code to compare two strings:
```
$cadena1='JUAN LÓPEZ YÁÑEZ';
$cadena2='JUAN LOPEZ YÁÑEZ';
if($cadena1===$cadena2){
echo '<p style="color: green;">The strings match!</p>';
}else{
echo '<p style="color: red;">The strings do not match. Accent sensitive?</p>';
}
```
I notice for example that if I compare *LOPEZ* and *LÓPEZ* then the comparison turns to false.
Is there a way or a function already there to compare these strings regardless of the Spanish accents? | 2014/10/22 | [
"https://Stackoverflow.com/questions/26514021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1883256/"
] | Why not just use collations from intl extension, Collator class?
* with a primary level to ignore accents **and** case
* with a primary level and set Collator::CASE\_LEVEL attribute to On to ignore accents but not case
(and so on - see ICU or PHP documentation for details)
```
$cadena1 = 'JUAN LÓPEZ YÁÑEZ';
$cadena2 = 'JUAN LOPEZ YÁÑEZ';
$coll = new Collator('es_ES');
$coll->setStrength(Collator::PRIMARY);
//$coll->setAttribute(Collator::CASE_LEVEL, Collator::ON);
var_dump($coll->compare($cadena1, $cadena2)); // 0 = equals
```
(of course, the strings have to be UTF-8 encoded) | You could try the [`soundex()`](http://php.net/manual/en/function.soundex.php) function, that works at least for your example:
```
var_dump(soundex('LOPEZ'));
// string(4) "L120"
var_dump(soundex('LÓPEZ'));
// string(4) "L120"
```
You would have to test that for different words and if the results are not good enough, you could try [`similar_text()`](http://php.net/manual/en/function.similar-text.php).
See an [example with your code](http://codepad.viper-7.com/LvnVhh). |
26,514,021 | My question is, given i have the following php code to compare two strings:
```
$cadena1='JUAN LÓPEZ YÁÑEZ';
$cadena2='JUAN LOPEZ YÁÑEZ';
if($cadena1===$cadena2){
echo '<p style="color: green;">The strings match!</p>';
}else{
echo '<p style="color: red;">The strings do not match. Accent sensitive?</p>';
}
```
I notice for example that if I compare *LOPEZ* and *LÓPEZ* then the comparison turns to false.
Is there a way or a function already there to compare these strings regardless of the Spanish accents? | 2014/10/22 | [
"https://Stackoverflow.com/questions/26514021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1883256/"
] | The two strings compare to false because they are actually different sequence of bytes. To compare them, you need to normalize them in any way.
The best way to do that is to use the Transliterator class, part of the `intl` extension on PHP 5.4+.
A test code:
```
<?php
$transliterator = Transliterator::createFromRules(':: NFD; :: [:Nonspacing Mark:] Remove; :: NFC;', Transliterator::FORWARD);
$test = ['abcd', 'èe', '€', 'àòùìéëü', 'àòùìéëü', 'tiësto'];
foreach($test as $e) {
$normalized = $transliterator->transliterate($e);
echo $e. ' --> '.$normalized."\n";
}
?>
```
Result:
```
abcd --> abcd
èe --> ee
€ --> €
àòùìéëü --> aouieeu
àòùìéëü --> aouieeu
tiësto --> tiesto
```
(taken from my answer here: [mySQL - matching latin (english) form input to utf8 (non-English) data](https://stackoverflow.com/questions/26185163/mysql-matching-latin-english-form-input-to-utf8-non-english-data/26186456#26186456) )
This replaces characters according to the tables of the ICU library, which are extremely complete and well-tested. Before transliterating, this normalizes the string, so it matches any possible way to represent characters like ñ (ñ, for example, can be represented with 1 multibyte character or as the combination of the two characters ˜ and n).
Unlike using soundex(), which is also very resource-intense, this does not compare sounds, so it's more accurate. | You could try the [`soundex()`](http://php.net/manual/en/function.soundex.php) function, that works at least for your example:
```
var_dump(soundex('LOPEZ'));
// string(4) "L120"
var_dump(soundex('LÓPEZ'));
// string(4) "L120"
```
You would have to test that for different words and if the results are not good enough, you could try [`similar_text()`](http://php.net/manual/en/function.similar-text.php).
See an [example with your code](http://codepad.viper-7.com/LvnVhh). |
26,514,021 | My question is, given i have the following php code to compare two strings:
```
$cadena1='JUAN LÓPEZ YÁÑEZ';
$cadena2='JUAN LOPEZ YÁÑEZ';
if($cadena1===$cadena2){
echo '<p style="color: green;">The strings match!</p>';
}else{
echo '<p style="color: red;">The strings do not match. Accent sensitive?</p>';
}
```
I notice for example that if I compare *LOPEZ* and *LÓPEZ* then the comparison turns to false.
Is there a way or a function already there to compare these strings regardless of the Spanish accents? | 2014/10/22 | [
"https://Stackoverflow.com/questions/26514021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1883256/"
] | I would replace all accents in your strings before comparing them. You can do that using the following code:
```
$replacements = array('Ó'=>'O', 'Á'=>'A', 'Ñ' => 'N'); //Add the remaining Spanish accents.
$output = strtr("JUAN LÓPEZ YÁÑEZ",$replacements);
```
`output` will now be equal to `cadena2`. | Why not just use collations from intl extension, Collator class?
* with a primary level to ignore accents **and** case
* with a primary level and set Collator::CASE\_LEVEL attribute to On to ignore accents but not case
(and so on - see ICU or PHP documentation for details)
```
$cadena1 = 'JUAN LÓPEZ YÁÑEZ';
$cadena2 = 'JUAN LOPEZ YÁÑEZ';
$coll = new Collator('es_ES');
$coll->setStrength(Collator::PRIMARY);
//$coll->setAttribute(Collator::CASE_LEVEL, Collator::ON);
var_dump($coll->compare($cadena1, $cadena2)); // 0 = equals
```
(of course, the strings have to be UTF-8 encoded) |
26,514,021 | My question is, given i have the following php code to compare two strings:
```
$cadena1='JUAN LÓPEZ YÁÑEZ';
$cadena2='JUAN LOPEZ YÁÑEZ';
if($cadena1===$cadena2){
echo '<p style="color: green;">The strings match!</p>';
}else{
echo '<p style="color: red;">The strings do not match. Accent sensitive?</p>';
}
```
I notice for example that if I compare *LOPEZ* and *LÓPEZ* then the comparison turns to false.
Is there a way or a function already there to compare these strings regardless of the Spanish accents? | 2014/10/22 | [
"https://Stackoverflow.com/questions/26514021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1883256/"
] | The two strings compare to false because they are actually different sequence of bytes. To compare them, you need to normalize them in any way.
The best way to do that is to use the Transliterator class, part of the `intl` extension on PHP 5.4+.
A test code:
```
<?php
$transliterator = Transliterator::createFromRules(':: NFD; :: [:Nonspacing Mark:] Remove; :: NFC;', Transliterator::FORWARD);
$test = ['abcd', 'èe', '€', 'àòùìéëü', 'àòùìéëü', 'tiësto'];
foreach($test as $e) {
$normalized = $transliterator->transliterate($e);
echo $e. ' --> '.$normalized."\n";
}
?>
```
Result:
```
abcd --> abcd
èe --> ee
€ --> €
àòùìéëü --> aouieeu
àòùìéëü --> aouieeu
tiësto --> tiesto
```
(taken from my answer here: [mySQL - matching latin (english) form input to utf8 (non-English) data](https://stackoverflow.com/questions/26185163/mysql-matching-latin-english-form-input-to-utf8-non-english-data/26186456#26186456) )
This replaces characters according to the tables of the ICU library, which are extremely complete and well-tested. Before transliterating, this normalizes the string, so it matches any possible way to represent characters like ñ (ñ, for example, can be represented with 1 multibyte character or as the combination of the two characters ˜ and n).
Unlike using soundex(), which is also very resource-intense, this does not compare sounds, so it's more accurate. | Try this function from <http://sourcecookbook.com/en/recipes/8/function-to-slugify-strings-in-php>. It will replace non-ASCII characters with ASCII characters in string.
```
$cadena1='JUAN LÓPEZ YÁÑEZ';
$cadena2='JUAN LOPEZ YÁÑEZ';
function slugify( $text ) {
// replace non letter or digits by -
$text = preg_replace('~[^\\pL\d]+~u', '-', $text);
$text = trim($text, '-');
/**
* //IGNORE//TRANSLIT to avoid errors on non translatable characters and still translate other characters
* //TRANSLIT to out_charset transliteration is activated
* //IGNORE, characters that cannot be represented in the target charset are silently discarded
*/
$text = iconv('utf-8', 'ASCII//IGNORE//TRANSLIT', $text);
$text = strtolower(trim($text));
// remove unwanted characters
$text = preg_replace('~[^-\w]+~', '', $text);
return empty($text) ? '' : $text;
}
var_dump( slugify( $cadena1 ) ); // string(16) "juan-lopez-yanez"
var_dump( slugify( $cadena2 ) ); // string(16) "juan-lopez-yanez"
``` |
26,514,021 | My question is, given i have the following php code to compare two strings:
```
$cadena1='JUAN LÓPEZ YÁÑEZ';
$cadena2='JUAN LOPEZ YÁÑEZ';
if($cadena1===$cadena2){
echo '<p style="color: green;">The strings match!</p>';
}else{
echo '<p style="color: red;">The strings do not match. Accent sensitive?</p>';
}
```
I notice for example that if I compare *LOPEZ* and *LÓPEZ* then the comparison turns to false.
Is there a way or a function already there to compare these strings regardless of the Spanish accents? | 2014/10/22 | [
"https://Stackoverflow.com/questions/26514021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1883256/"
] | I would replace all accents in your strings before comparing them. You can do that using the following code:
```
$replacements = array('Ó'=>'O', 'Á'=>'A', 'Ñ' => 'N'); //Add the remaining Spanish accents.
$output = strtr("JUAN LÓPEZ YÁÑEZ",$replacements);
```
`output` will now be equal to `cadena2`. | You could try the [`soundex()`](http://php.net/manual/en/function.soundex.php) function, that works at least for your example:
```
var_dump(soundex('LOPEZ'));
// string(4) "L120"
var_dump(soundex('LÓPEZ'));
// string(4) "L120"
```
You would have to test that for different words and if the results are not good enough, you could try [`similar_text()`](http://php.net/manual/en/function.similar-text.php).
See an [example with your code](http://codepad.viper-7.com/LvnVhh). |
26,514,021 | My question is, given i have the following php code to compare two strings:
```
$cadena1='JUAN LÓPEZ YÁÑEZ';
$cadena2='JUAN LOPEZ YÁÑEZ';
if($cadena1===$cadena2){
echo '<p style="color: green;">The strings match!</p>';
}else{
echo '<p style="color: red;">The strings do not match. Accent sensitive?</p>';
}
```
I notice for example that if I compare *LOPEZ* and *LÓPEZ* then the comparison turns to false.
Is there a way or a function already there to compare these strings regardless of the Spanish accents? | 2014/10/22 | [
"https://Stackoverflow.com/questions/26514021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1883256/"
] | Why not just use collations from intl extension, Collator class?
* with a primary level to ignore accents **and** case
* with a primary level and set Collator::CASE\_LEVEL attribute to On to ignore accents but not case
(and so on - see ICU or PHP documentation for details)
```
$cadena1 = 'JUAN LÓPEZ YÁÑEZ';
$cadena2 = 'JUAN LOPEZ YÁÑEZ';
$coll = new Collator('es_ES');
$coll->setStrength(Collator::PRIMARY);
//$coll->setAttribute(Collator::CASE_LEVEL, Collator::ON);
var_dump($coll->compare($cadena1, $cadena2)); // 0 = equals
```
(of course, the strings have to be UTF-8 encoded) | I had the same issue:
the following messages are compared as no-equal.
```
$var1= "Utilizar preferentemente la vacuna Td (toxoides tetánico y diftérico) o, si no está disponible, la vacuna TT (toxoide tetánico).";
$var2 = "Utilizar preferentemente la vacuna Td (toxoides tetánico y diftérico) o, si no está disponible, la vacuna TT (toxoide tetánico).";
if(strcmp($var1, $var2) == 0 ) {
echo "they are Equal!";
}else {
echo "they are NOT Equal!";
}
```
the result is "they are NOT Equal!".
I tried the mentioned solution with intl but unfortunately didn't work. but the following solution helped me.
```
$var1 = iconv('UTF-8','ASCII//TRANSLIT',$var1);
$var2 = iconv('UTF-8','ASCII//TRANSLIT',$var2);
if(strcmp($var1, $var2) == 0 ) {
echo "they are Equal!";
}else {
echo "they are NOT Equal!";
}
```
This time they are equal! |
108,146 | I'm Chinese and currently waiting for my residence permit here in France. I'm not sure if my residence permit will be released before my scheduled trip in Europe. I'm planning to go to Belgium, Amsterdam, Switzerland, Germany and Italy. There is a chance that I will only have my temporary residence permit during my Europe trip. I will travel only by bus and by train. Do they usually check the passport and residence permit in buses/trains? By the way, the visa in my passport is already expired. | 2018/01/11 | [
"https://travel.stackexchange.com/questions/108146",
"https://travel.stackexchange.com",
"https://travel.stackexchange.com/users/72478/"
] | There will be occasional checks at least when entering Switzerland, or Germany from Austria/Switzerland, or France from Germany/Switzerland/Italy. However, it's less common on trains than buses.
When entering Switzerland by bus, checks are very common, though not systematic.
I would **not** recommend you to do this trip if you don't receive your residence permit in time. | There are random checks on both buses and trains. I've had my passport checked when traveling by train from Germany to France and when traveling by bus from Austria to Germany. I also had my passport checked almost every time when traveling to Switzerland, but the last time I went there was 8 years ago.
These checks are seemingly random, and (other than Switzerland) they happened to me less than 5% of the times I traveled across borders within the EU. I suspect checks are more common on trains and buses that are suspected of carrying passengers coming from eastern Europe, but I don't know that for sure.
If you have a temporary residence permit that is valid the entire time you are traveling, then that should be good enough. It shows that you have permission to be there. |
8,056,842 | My question is not about GPGPU. I understand GPGPU pretty decently and that is not what I am looking for. Intel's Sand Bridge has supposedly some features that allow you to directly perform computations on the GPU.
Is that really true?
The code I am planning to write is going to be in inline assembly (in C). Are there assembly instructions that instead of executing on the CPU push stuff out to the GPU?
Some related documentation :
* <http://intellinuxgraphics.org/documentation.html>
* <http://intellinuxgraphics.org/documentation/SNB/IHD_OS_Vol4_Part2.pdf>
The PDF has the instruction set. | 2011/11/08 | [
"https://Stackoverflow.com/questions/8056842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Answering your first question: No it is not true.
Let me quote from the resources you have linked:
>
> The Graphics Processing Unit is controlled by the CPU through a direct interface of memory-mapped IO
> registers, and indirectly by parsing commands that the CPU has placed in memory. (Chapter 2.2 from the SB GPU manual)
>
>
>
So no direct execution of GPU code in the cpu context.
For your second question: "Pushing stuff out to the GPU" is done with the mov instruction. Target is a mem-mapped IO register, source the stuff you want to write. You might need to insert some "sfence" or similar instructions to make sure no weak memory reordering does happen. | I don't believe that the instruction set detailed in the PDF you linked can be directly used from "user space". It's what the GPU driver on your OS may\* use to implement higher-level interfaces like OpenGL and DirectX.
For what it's worth, the Sandy Bridge GPU is pretty weak. It doesn't support OpenCL\*\*, which is a standard GPGPU library which is supported by ATI / nVidia. I'd recommend that you program to that library (on hardware that supports it), as it's far more portable (and easier to use!) than trying to program to the bare-metal interface that you're looking at.
---
\*: It's possible, although unlikely, that there's a different interface than what's described in that PDF which is used in Intel's closed-source drivers.
\*\*: Not the same as OpenGL, although it was designed by the same group. |
18,889,056 | I'm trying to figure out a way of identifying a "run" of results (successive rows, in order) that meet some condition. Currently, I'm ordering a result set, and scanning by eye for particular patterns. Here's an example:
```
SELECT the_date, name
FROM orders
WHERE
the_date BETWEEN
to_date('2013-09-18',..) AND
to_date('2013-09-22', ..)
ORDER BY the_date
--------------------------------------
the_date | name
--------------------------------------
2013-09-18 00:00:01 | John
--------------------------------------
2013-09-19 00:00:01 | James
--------------------------------------
2013-09-20 00:00:01 | John
--------------------------------------
2013-09-20 00:00:02 | John
--------------------------------------
2013-09-20 00:00:03 | John
--------------------------------------
2013-09-20 00:00:04 | John
--------------------------------------
2013-09-21 16:00:01 | Jennifer
--------------------------------------
```
What I want to extract from this result set is all the rows attributed to `John` on `2013-09-20`. Generally what I'm looking for is a run of results from the same `name`, in a row, >= 3. I'm using Oracle 11, but I'm interested to know if this can be achieved with strict SQL, or if some kind of analytical function must be used. | 2013/09/19 | [
"https://Stackoverflow.com/questions/18889056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10583/"
] | You need multiple nested window functions:
```
SELECT *
FROM
(
SELECT the_date, name, grp,
COUNT(*) OVER (PARTITION BY grp) AS cnt
FROM
(
SELECT the_date, name,
SUM(flag) OVER (ORDER BY the_date) AS grp
FROM
(
SELECT the_date, name,
CASE WHEN LAG(name) OVER (ORDER BY the_date) = name THEN 0 ELSE 1 END AS flag
FROM orders
WHERE
the_date BETWEEN
TO_DATE('2013-09-18',..) AND
TO_DATE('2013-09-22', ..)
) dt
) dt
) dt
WHERE cnt >= 3
ORDER BY the_date
``` | Try this
```
WITH ORDERS
AS (SELECT
TO_DATE ( '2013-09-18 00:00:01',
'YYYY-MM-DD HH24:MI:SS' )
AS THE_DATE,
'John' AS NAME
FROM
DUAL
UNION ALL
SELECT
TO_DATE ( '2013-09-19 00:00:01',
'YYYY-MM-DD HH24:MI:SS' )
AS THE_DATE,
'James' AS NAME
FROM
DUAL
UNION ALL
SELECT
TO_DATE ( '2013-09-20 00:00:01',
'YYYY-MM-DD HH24:MI:SS' )
AS THE_DATE,
'John' AS NAME
FROM
DUAL
UNION ALL
SELECT
TO_DATE ( '2013-09-20 00:00:02',
'YYYY-MM-DD HH24:MI:SS' )
AS THE_DATE,
'John' AS NAME
FROM
DUAL
UNION ALL
SELECT
TO_DATE ( '2013-09-20 00:00:03',
'YYYY-MM-DD HH24:MI:SS' )
AS THE_DATE,
'John' AS NAME
FROM
DUAL
UNION ALL
SELECT
TO_DATE ( '2013-09-20 00:00:04',
'YYYY-MM-DD HH24:MI:SS' )
AS THE_DATE,
'John' AS NAME
FROM
DUAL
UNION ALL
SELECT
TO_DATE ( '2013-09-21 16:00:01',
'YYYY-MM-DD HH24:MI:SS' )
AS THE_DATE,
'Jennifer' AS NAME
FROM
DUAL)
SELECT
B.*
FROM
(SELECT
TRUNC ( THE_DATE ) THE_DATE,
NAME,
COUNT ( * )
FROM
ORDERS
WHERE
THE_DATE BETWEEN TRUNC ( TO_DATE ( '2013-09-18',
'YYYY-MM-DD' ) )
AND TRUNC ( TO_DATE ( '2013-09-22',
'YYYY-MM-DD' ) )
GROUP BY
TRUNC ( THE_DATE ),
NAME
HAVING
COUNT ( * ) >= 3) A,
ORDERS B
WHERE
A.NAME = B.NAME
AND TRUNC ( A.THE_DATE ) = TRUNC ( B.THE_DATE );
```
OUTPUT
```
9/20/2013 12:00:01 AM John
9/20/2013 12:00:02 AM John
9/20/2013 12:00:03 AM John
9/20/2013 12:00:04 AM John
``` |
16,568 | So company earnings can fluctuate quite a bit, based on the market conditions, seasonal conditions, whether there was a big spend in the last year etc.
Therefore, even the last years earnings could differ quite a lot from this year.
So I was wondering like when we work out the P/E ratio, which set of earnings is used? Is it the real annual earnings from last year? Or is it the latest estimates of what the earnings will be? And who makes these estimates? Is it the market commentators or the company saying "we'd expected to make this much"?
One example I can think of is with BHP. I've been looking at their P/E ratio and it has been around 8 for the past few months.
Yesterday, they announced that profit fell `35%` following the news of [**'BHP Mothballs Expansion' smh.com.au**](http://www.smh.com.au/business/mining-and-resources/bhp-mothballs-olympic-dam-expansion-20120822-24m4i.html)
As suggested in the linked article, this news was not a surprise and even beat "*Market Consensus*" (which is what?) by a little bit.
So I guess in this example, as the P/E ratio did not just jump `35%` on that news so that suggests to me that the p/e had already taken this news into account even before it was announced. If so, where are these numbers coming from? | 2012/08/23 | [
"https://money.stackexchange.com/questions/16568",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/1508/"
] | This is a note from my broker, CMC Markets, who use Morningstar:
>
> Morningstar calculate the P/E Ratio using a weighted average of the most recent earnings and the projected earnings for the next year. This may result in a different P/E Ratio to those based solely on past earnings as reported on some sites and other publications.
>
>
>
They show the P/E as being 9.93.
So obviously past earnings would usually be used but you would need to check with your source which numbers they are using. Also, as BHP's results just came out yesterday it may take a while for the most recent financial details to be updated. | @jlowin's answer has a very good discussion of the types of PE ratio so I will just answer a very specific question from within your question:
>
> And who makes these estimates? Is it the market commentators or the company saying "we'd expected to make this much"?
>
>
>
Future earnings estimates are made by professional analysts and analytical teams in the market based on a number of factors. If these analysts are within an investment company the investment company will use a frequently updated value of this estimate as the basis for their PE ratio. Some of these numbers for large or liquid firms may essentially be generated every time they want to look at the PE ratio, possibly many times a day. In my experience they take little notice of what the company says they expect to make as those are numbers that the board wants the market to see. Instead analysts use a mixture of economic data and forecasting, surveys of sentiment towards the company and its industry, and various related current events to build up an ongoing model of the company's finances. How sophisticated the model is is dependent upon how big the analytics team is and how much time resource they can devote to the company. For bigger firms with good investor relations teams and high liquidity or small, fast growing firms this can be a huge undertaking as they can see large rewards in putting the extra work in. The
At least one analytics team at a large investment bank that I worked closely with even went as far as sending analysts out onto the streets some days to "get a feeling for" some companies' and industries' growth potential.
Each analytics team or analyst only seems to make public its estimates a few times a year in spite of their being calculated internally as an ongoing process. The reason why they do this is simple; this analysis is worth a lot to their trading teams, asset managers and paying clients than the PR of releasing the data. Although these projections are "good at time of release" their value diminishes as time goes on, particularly if the firm launches new initiatives etc.. This is why weighting analyst forecasts based on this time variable makes for a better average.
Most private individual investors use an average or time weighted average (on time since release) of these analyst estimates as the basis for their forward PE. |
16,568 | So company earnings can fluctuate quite a bit, based on the market conditions, seasonal conditions, whether there was a big spend in the last year etc.
Therefore, even the last years earnings could differ quite a lot from this year.
So I was wondering like when we work out the P/E ratio, which set of earnings is used? Is it the real annual earnings from last year? Or is it the latest estimates of what the earnings will be? And who makes these estimates? Is it the market commentators or the company saying "we'd expected to make this much"?
One example I can think of is with BHP. I've been looking at their P/E ratio and it has been around 8 for the past few months.
Yesterday, they announced that profit fell `35%` following the news of [**'BHP Mothballs Expansion' smh.com.au**](http://www.smh.com.au/business/mining-and-resources/bhp-mothballs-olympic-dam-expansion-20120822-24m4i.html)
As suggested in the linked article, this news was not a surprise and even beat "*Market Consensus*" (which is what?) by a little bit.
So I guess in this example, as the P/E ratio did not just jump `35%` on that news so that suggests to me that the p/e had already taken this news into account even before it was announced. If so, where are these numbers coming from? | 2012/08/23 | [
"https://money.stackexchange.com/questions/16568",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/1508/"
] | There are two common types of P/E ratio calculations: "trailing" and "forward" (and then there are various mixes of the two).
Trailing P/E ratios are calculated as [current price] / [trailing 12-month EPS]. An alternative is the Forward P/E ratio, which is based on an estimate of earnings in the coming 12 months. The estimate used is usually called "consensus" and, to answer your question, is the average estimate of analysts who cover the stock. Any reputable organization will disclose how they calculate their financials. For example, Reuters uses a trailing ratio (indicated by "TTM") on [their page for BHP](http://www.reuters.com/finance/stocks/overview?symbol=BHP.AX).
So, the first reason a PE ratio might not jump on an announcement is it might be forward looking and therefore not very sensitive to the realized earnings.
The second reason is that if it is a trailing ratio, some of the annual EPS change is known prior to the annual announcement. For example, on 12/31 a company might report a large drop in annual earnings, but if the bulk of that loss was reported in a previous quarterly report, then the trailing EPS would account partially for it prior to the annual announcement.
In this case, I think the first reason is the culprit. The Reuters P/E of nearly 12 is a trailing ratio, so if you see 8 I'd think it must be based on a forward-looking estimate. | @jlowin's answer has a very good discussion of the types of PE ratio so I will just answer a very specific question from within your question:
>
> And who makes these estimates? Is it the market commentators or the company saying "we'd expected to make this much"?
>
>
>
Future earnings estimates are made by professional analysts and analytical teams in the market based on a number of factors. If these analysts are within an investment company the investment company will use a frequently updated value of this estimate as the basis for their PE ratio. Some of these numbers for large or liquid firms may essentially be generated every time they want to look at the PE ratio, possibly many times a day. In my experience they take little notice of what the company says they expect to make as those are numbers that the board wants the market to see. Instead analysts use a mixture of economic data and forecasting, surveys of sentiment towards the company and its industry, and various related current events to build up an ongoing model of the company's finances. How sophisticated the model is is dependent upon how big the analytics team is and how much time resource they can devote to the company. For bigger firms with good investor relations teams and high liquidity or small, fast growing firms this can be a huge undertaking as they can see large rewards in putting the extra work in. The
At least one analytics team at a large investment bank that I worked closely with even went as far as sending analysts out onto the streets some days to "get a feeling for" some companies' and industries' growth potential.
Each analytics team or analyst only seems to make public its estimates a few times a year in spite of their being calculated internally as an ongoing process. The reason why they do this is simple; this analysis is worth a lot to their trading teams, asset managers and paying clients than the PR of releasing the data. Although these projections are "good at time of release" their value diminishes as time goes on, particularly if the firm launches new initiatives etc.. This is why weighting analyst forecasts based on this time variable makes for a better average.
Most private individual investors use an average or time weighted average (on time since release) of these analyst estimates as the basis for their forward PE. |
48,881,108 | When I turn on the UISwitch I try to make it hide the background Image but I get the error: Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value.
What am I doing wrong? when it was on the main storyboard it worked fine, but when on the settings storyboard it doesn't.
Code:
```
@IBAction func switchBackground(_ sender: UISwitch) {
if (sender.isOn == true) {
Background!.isHidden = false
amountDue.textColor = UIColor.white
amountMoney.textColor = UIColor.white
amountPeople.textColor = UIColor.white
}else {
Background!.isHidden = true
amountDue.textColor = UIColor.black
amountMoney.textColor = UIColor.black
amountPeople.textColor = UIColor.black
amountDueText.textColor = UIColor.black
amountPeopleText.textColor = UIColor.black
amountMoneyText.textColor = UIColor.black
}
}
``` | 2018/02/20 | [
"https://Stackoverflow.com/questions/48881108",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9384661/"
] | ```
You can use a filter to remove the read-more link from content. I have updated your filter. Please try it, It's working fine.
function disable_more_link( $link ) {
$link = preg_replace( '|#more-[0-9]+|', '', '' );
return $link;
}
add_filter( 'the_content_more_link', 'disable_more_link', 10, 2 );
``` | [More info](https://codex.wordpress.org/Customizing_the_Read_More)
```
function new_excerpt_more($more) {
return '...';
}
add_filter('excerpt_more', 'new_excerpt_more');
``` |
3,225,512 | I have a jQuery function that allows a user to create a list of links. By clicking on an "add row" link they create as many of these blocks (shown below) as they like which they can type the information into.
```
<div class="links_row">
<input type="text" name="link_name[]">
<input type="text" name="link_url[]">
</div>
```
I am posting this data to a PHP function to insert into a database which looks like this:
```
+---------------+
|id |
+---------------+
|name |
+---------------+
|url |
+---------------+
```
I need to work out how to combine the two input arrays link\_name[] and link\_url[] and loop through the resulting single array, inserting each as a row in the database. | 2010/07/12 | [
"https://Stackoverflow.com/questions/3225512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/339876/"
] | Combine. You mean like `array_merge()` combine?
If so, use that.
EDIT:
On second thought, you might want `array_combine()`. It takes two arrays and returns one where one of the input arrays provides the keys and the other provides the values. | No, youre better off with an array map because the numbers would correlate. Check out:
>
> <http://php.net/manual/en/function.array-map.php>
>
>
> |
3,225,512 | I have a jQuery function that allows a user to create a list of links. By clicking on an "add row" link they create as many of these blocks (shown below) as they like which they can type the information into.
```
<div class="links_row">
<input type="text" name="link_name[]">
<input type="text" name="link_url[]">
</div>
```
I am posting this data to a PHP function to insert into a database which looks like this:
```
+---------------+
|id |
+---------------+
|name |
+---------------+
|url |
+---------------+
```
I need to work out how to combine the two input arrays link\_name[] and link\_url[] and loop through the resulting single array, inserting each as a row in the database. | 2010/07/12 | [
"https://Stackoverflow.com/questions/3225512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/339876/"
] | Probably not the cleanest way of doing this, but a quick loop should do it.
I'm assuming you've validated and sanitized the form data and made sure the arrays are the same size.
```
$rows = array();
$num_results = count($_POST['link_name']);
for($i = 0; $i < $num_results; $i++) {
$rows[$i]['url'] = $_POST['link_url'][$i];
$rows[$i]['name'] = $_POST['link_name'][$i];
}
``` | Combine. You mean like `array_merge()` combine?
If so, use that.
EDIT:
On second thought, you might want `array_combine()`. It takes two arrays and returns one where one of the input arrays provides the keys and the other provides the values. |
3,225,512 | I have a jQuery function that allows a user to create a list of links. By clicking on an "add row" link they create as many of these blocks (shown below) as they like which they can type the information into.
```
<div class="links_row">
<input type="text" name="link_name[]">
<input type="text" name="link_url[]">
</div>
```
I am posting this data to a PHP function to insert into a database which looks like this:
```
+---------------+
|id |
+---------------+
|name |
+---------------+
|url |
+---------------+
```
I need to work out how to combine the two input arrays link\_name[] and link\_url[] and loop through the resulting single array, inserting each as a row in the database. | 2010/07/12 | [
"https://Stackoverflow.com/questions/3225512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/339876/"
] | Probably not the cleanest way of doing this, but a quick loop should do it.
I'm assuming you've validated and sanitized the form data and made sure the arrays are the same size.
```
$rows = array();
$num_results = count($_POST['link_name']);
for($i = 0; $i < $num_results; $i++) {
$rows[$i]['url'] = $_POST['link_url'][$i];
$rows[$i]['name'] = $_POST['link_name'][$i];
}
``` | No, youre better off with an array map because the numbers would correlate. Check out:
>
> <http://php.net/manual/en/function.array-map.php>
>
>
> |
4,737,701 | I trying to write a a crash report feature that when you launch the app after a crash, it will offer to send the crash report to the server. I can't find how to get the crash log within the app. I saw there is a framework that doing so ([PLCrashReporter](http://code.google.com/p/plcrashreporter/)), however this framework is large and I don't need most of it's features.
Does anyone knows how to simply access the log?
Thanks,
Guy. | 2011/01/19 | [
"https://Stackoverflow.com/questions/4737701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/248037/"
] | I had this similar issue and the PLCrashReported seemed too complicated for what I wanted to do.
Note that you can't access the crash report generated by Apple, the PLCrashReport generates it's own reports and store them in the user's cache folder.
Eventually, I used the following example:
<http://cocoawithlove.com/2010/05/handling-unhandled-exceptions-and.html>
it's very simple and easy to use, just register exception and signal handlers using:
```
NSSetUncaughtExceptionHandler(&HandleException);
signal(SIGABRT, SignalHandler);
signal(SIGILL, SignalHandler);
signal(SIGSEGV, SignalHandler);
signal(SIGFPE, SignalHandler);
signal(SIGBUS, SignalHandler);
signal(SIGPIPE, SignalHandler);
```
and get the stack trace using the `backtrace` method in `UncaughtExceptionHandler` class. | Maybe a better solution will be to use a fully specialized end-2-end solution/service? Such as <http://apphance.com>. It is currently in closed beta testing phase, but you can ask for participation and we'll get back to you pretty quickly. The only thing you need to do is to register for an API key and embed a small framework library into your app (or .jar file in android). Then you have remote access not only to crashlogs but also to a debug logs generated by the application - which makes it much more useful. It is for now targeted to be used during testing, but there will soon be a lite version that you will be able to embed into app-store-released application.
Inside the framework we are doing all the magic of plugging-into the apple's framework and getting the crashlog information, decoding stack traces, even handling out-of-memory cases. All the comments by @nupark hold very much true: We spend countless hours on making it works seamlessly - thread-safeness, making sure that we can do the job of saving everything within the time required by Apple's framework before your app get finally killed, getting stack trace from out-of-memory case (that one was really difficult). The same for android - we've done some clever tricks there to make sure it's really working fine.
Disclaimer: I am CTO of Polidea, company which is behind apphance and co-creator of the solution. |
4,737,701 | I trying to write a a crash report feature that when you launch the app after a crash, it will offer to send the crash report to the server. I can't find how to get the crash log within the app. I saw there is a framework that doing so ([PLCrashReporter](http://code.google.com/p/plcrashreporter/)), however this framework is large and I don't need most of it's features.
Does anyone knows how to simply access the log?
Thanks,
Guy. | 2011/01/19 | [
"https://Stackoverflow.com/questions/4737701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/248037/"
] | I had this similar issue and the PLCrashReported seemed too complicated for what I wanted to do.
Note that you can't access the crash report generated by Apple, the PLCrashReport generates it's own reports and store them in the user's cache folder.
Eventually, I used the following example:
<http://cocoawithlove.com/2010/05/handling-unhandled-exceptions-and.html>
it's very simple and easy to use, just register exception and signal handlers using:
```
NSSetUncaughtExceptionHandler(&HandleException);
signal(SIGABRT, SignalHandler);
signal(SIGILL, SignalHandler);
signal(SIGSEGV, SignalHandler);
signal(SIGFPE, SignalHandler);
signal(SIGBUS, SignalHandler);
signal(SIGPIPE, SignalHandler);
```
and get the stack trace using the `backtrace` method in `UncaughtExceptionHandler` class. | There are a bunch of (SAAS) E2E solutions that you may be very happy to know.
Very very simple to integrate into your application
Have Fun...
1. [**crashlytics**](http://www.crashlytics.com) (Free and my preferred)
2. [hockeyapp](http://hockeyapp.net/)
3. [bugSense](http://www.bugsense.com)
4. [Crittercism](https://www.crittercism.com)
In our days you may use the built-in crash reports (iOS & Android)
1. [iOS (Itunes connect) - Viewing Crash Reports](http://developer.apple.com/library/ios/#documentation/LanguagesUtilities/Conceptual/iTunesConnect_Guide/10_ManagingYourApplications/ManagingYourApplications.html#//apple_ref/doc/uid/TP40011225-CH3-SW1)
2. [Understanding Crash Reports
on iPhone OS](http://adcdownload.apple.com//wwdc_2010/wwdc_2010_video_assets__pdfs/317__understanding_crash_reports_on_iphone_os.pdf)
3. [Reading Android Market Crash Reports](http://mobile.tutsplus.com/tutorials/android/android-app-publishing-reading-android-market-crash-reports/) |
4,737,701 | I trying to write a a crash report feature that when you launch the app after a crash, it will offer to send the crash report to the server. I can't find how to get the crash log within the app. I saw there is a framework that doing so ([PLCrashReporter](http://code.google.com/p/plcrashreporter/)), however this framework is large and I don't need most of it's features.
Does anyone knows how to simply access the log?
Thanks,
Guy. | 2011/01/19 | [
"https://Stackoverflow.com/questions/4737701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/248037/"
] | I guess I don't have the karma to add a comment to Nimrod Gat's answer, so I have to provide my follow-up here. I'll try to make it worthy of a standalone answer.
It's very, very difficult to write a safe, correct, and *reliable* crash reporter, especially one that runs directly in-process. The code referenced in Nimrod Gat's answer is not correct and honestly, that blog post should be retracted. Signal handlers must only run async-safe code, and that code isn't async-safe:
<http://www.cocoadev.com/index.pl?SignalSafety>
Crash handling is even more complicated than normal signal handling, because that you can't expect the process to continue to run successfully after your signal handler returns.
It's tempting to think you can just hack together a simpler solution, and it will work some of the time, but there's a good reason people like Google's engineers have thousands of LoC dedicated to reliable crash reporting:
<http://code.google.com/p/google-breakpad/>
On iOS, you should just use PLCrashReporter. On other platforms (such as Mac OS X) you should use Google Breakpad. There's no point in re-inventing this wheel unless you're going to do it not only correctly, but better than what already exists. | Maybe a better solution will be to use a fully specialized end-2-end solution/service? Such as <http://apphance.com>. It is currently in closed beta testing phase, but you can ask for participation and we'll get back to you pretty quickly. The only thing you need to do is to register for an API key and embed a small framework library into your app (or .jar file in android). Then you have remote access not only to crashlogs but also to a debug logs generated by the application - which makes it much more useful. It is for now targeted to be used during testing, but there will soon be a lite version that you will be able to embed into app-store-released application.
Inside the framework we are doing all the magic of plugging-into the apple's framework and getting the crashlog information, decoding stack traces, even handling out-of-memory cases. All the comments by @nupark hold very much true: We spend countless hours on making it works seamlessly - thread-safeness, making sure that we can do the job of saving everything within the time required by Apple's framework before your app get finally killed, getting stack trace from out-of-memory case (that one was really difficult). The same for android - we've done some clever tricks there to make sure it's really working fine.
Disclaimer: I am CTO of Polidea, company which is behind apphance and co-creator of the solution. |
4,737,701 | I trying to write a a crash report feature that when you launch the app after a crash, it will offer to send the crash report to the server. I can't find how to get the crash log within the app. I saw there is a framework that doing so ([PLCrashReporter](http://code.google.com/p/plcrashreporter/)), however this framework is large and I don't need most of it's features.
Does anyone knows how to simply access the log?
Thanks,
Guy. | 2011/01/19 | [
"https://Stackoverflow.com/questions/4737701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/248037/"
] | I guess I don't have the karma to add a comment to Nimrod Gat's answer, so I have to provide my follow-up here. I'll try to make it worthy of a standalone answer.
It's very, very difficult to write a safe, correct, and *reliable* crash reporter, especially one that runs directly in-process. The code referenced in Nimrod Gat's answer is not correct and honestly, that blog post should be retracted. Signal handlers must only run async-safe code, and that code isn't async-safe:
<http://www.cocoadev.com/index.pl?SignalSafety>
Crash handling is even more complicated than normal signal handling, because that you can't expect the process to continue to run successfully after your signal handler returns.
It's tempting to think you can just hack together a simpler solution, and it will work some of the time, but there's a good reason people like Google's engineers have thousands of LoC dedicated to reliable crash reporting:
<http://code.google.com/p/google-breakpad/>
On iOS, you should just use PLCrashReporter. On other platforms (such as Mac OS X) you should use Google Breakpad. There's no point in re-inventing this wheel unless you're going to do it not only correctly, but better than what already exists. | There are a bunch of (SAAS) E2E solutions that you may be very happy to know.
Very very simple to integrate into your application
Have Fun...
1. [**crashlytics**](http://www.crashlytics.com) (Free and my preferred)
2. [hockeyapp](http://hockeyapp.net/)
3. [bugSense](http://www.bugsense.com)
4. [Crittercism](https://www.crittercism.com)
In our days you may use the built-in crash reports (iOS & Android)
1. [iOS (Itunes connect) - Viewing Crash Reports](http://developer.apple.com/library/ios/#documentation/LanguagesUtilities/Conceptual/iTunesConnect_Guide/10_ManagingYourApplications/ManagingYourApplications.html#//apple_ref/doc/uid/TP40011225-CH3-SW1)
2. [Understanding Crash Reports
on iPhone OS](http://adcdownload.apple.com//wwdc_2010/wwdc_2010_video_assets__pdfs/317__understanding_crash_reports_on_iphone_os.pdf)
3. [Reading Android Market Crash Reports](http://mobile.tutsplus.com/tutorials/android/android-app-publishing-reading-android-market-crash-reports/) |
4,737,701 | I trying to write a a crash report feature that when you launch the app after a crash, it will offer to send the crash report to the server. I can't find how to get the crash log within the app. I saw there is a framework that doing so ([PLCrashReporter](http://code.google.com/p/plcrashreporter/)), however this framework is large and I don't need most of it's features.
Does anyone knows how to simply access the log?
Thanks,
Guy. | 2011/01/19 | [
"https://Stackoverflow.com/questions/4737701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/248037/"
] | Maybe a better solution will be to use a fully specialized end-2-end solution/service? Such as <http://apphance.com>. It is currently in closed beta testing phase, but you can ask for participation and we'll get back to you pretty quickly. The only thing you need to do is to register for an API key and embed a small framework library into your app (or .jar file in android). Then you have remote access not only to crashlogs but also to a debug logs generated by the application - which makes it much more useful. It is for now targeted to be used during testing, but there will soon be a lite version that you will be able to embed into app-store-released application.
Inside the framework we are doing all the magic of plugging-into the apple's framework and getting the crashlog information, decoding stack traces, even handling out-of-memory cases. All the comments by @nupark hold very much true: We spend countless hours on making it works seamlessly - thread-safeness, making sure that we can do the job of saving everything within the time required by Apple's framework before your app get finally killed, getting stack trace from out-of-memory case (that one was really difficult). The same for android - we've done some clever tricks there to make sure it's really working fine.
Disclaimer: I am CTO of Polidea, company which is behind apphance and co-creator of the solution. | There are a bunch of (SAAS) E2E solutions that you may be very happy to know.
Very very simple to integrate into your application
Have Fun...
1. [**crashlytics**](http://www.crashlytics.com) (Free and my preferred)
2. [hockeyapp](http://hockeyapp.net/)
3. [bugSense](http://www.bugsense.com)
4. [Crittercism](https://www.crittercism.com)
In our days you may use the built-in crash reports (iOS & Android)
1. [iOS (Itunes connect) - Viewing Crash Reports](http://developer.apple.com/library/ios/#documentation/LanguagesUtilities/Conceptual/iTunesConnect_Guide/10_ManagingYourApplications/ManagingYourApplications.html#//apple_ref/doc/uid/TP40011225-CH3-SW1)
2. [Understanding Crash Reports
on iPhone OS](http://adcdownload.apple.com//wwdc_2010/wwdc_2010_video_assets__pdfs/317__understanding_crash_reports_on_iphone_os.pdf)
3. [Reading Android Market Crash Reports](http://mobile.tutsplus.com/tutorials/android/android-app-publishing-reading-android-market-crash-reports/) |
71,386,061 | Our instruction manual is in markdown format. We improve the manual daily or weekly and then we would like to translate to other languages. Until now, this process is manual and we use TRADOS (a assisted translation software)
We are studying to improve the process. What we want to do is to translate it using Microsoft translator and then a human reviewer do the fine tune. The problem is how we can reuse the corrected document in Microsoft Translator for the next translation.
Many times we only change 2 or 3 words of a topic and then the translator would create a complete new translation, doing the reviewer work very tedious if the translation is not accurate.
I know that we can train the model, but I think that there is not a 100% of probabilities that the translator uses the review. Also, it seems very time consuming to maintain the distortionary after reviewing the document.
I was wondering if somebody has solved this kind a problem. | 2022/03/07 | [
"https://Stackoverflow.com/questions/71386061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5185236/"
] | First of all, an expression like `writeDir.concat("/").concat("metadata.txt")` is reducing readability *and* performance. A straight-forward `writeDir + "/" + "metadata.txt"` will provide better performance. But since you’re constructing a string merely for constructing a `Path`, it’s even more straight-forward not to do the `Path`’s job in your code but rather use `Paths.get(writeDir, "metadata.txt")`.
You can not rewind a `BufferedWriter` but you can rewind a `FileChannel`. Therefore, to keep the channel open and rewind it when needed, you have to construct a new writer after rewinding:
```java
public static void writeMetaData(FileChannel ch, JSONObject jsonObj) throws IOException {
ch.position(0);
if(ch.size() > 0) ch.truncate(0);
Writer w = Channels.newWriter(ch, StandardCharsets.UTF_8.newEncoder(), 8192);
w.write(jsonObj.toString());
w.flush();
}
```
```java
try(FileChannel ch = FileChannel.open(Paths.get(writeDir, "metadata.txt"),
StandardOpenOption.WRITE, StandardOpenOption.CREATE)) {
for(int i = 0; i < 100000; i++) {
// do Something;
if(i % 100 == 0) {
writeMetaData(ch, jsonObject);
}
}
}
```
It’s important that the use of the `Writer` ends with `flush()` to force the write of all buffered data, but not `close()` as that would also close the underlying channel. Note that this code does not wrap the writer into a `BufferedWriter`; encoding text as UTF-8 is already a buffered operation and by requesting a larger buffer for the encoder, matching `BufferedWriter`’s default buffer size, we get the same effect of buffering without the copying overhead.
Since writing is not an end in itself, there’s a question left regarding your reading side. If the reader is trying to read the data in some intervals, there’s the risk of overlapping with the write, getting incomplete data.
You could use
```java
public static void writeMetaData(FileChannel ch, JSONObject jsonObj) throws IOException {
try(FileLock lock = ch.lock()) {
ch.position(0);
if(ch.size() > 0) ch.truncate(0);
Writer w = Channels.newWriter(ch, StandardCharsets.UTF_8.newEncoder(), 8192);
w.write(jsonObj.toString());
w.flush();
}
}
```
to lock the file during the write. But depending on the system, file locking might not be mandatory but only affect readers also trying to get a read lock.
---
When you use JDK 11 or newer, you may consider using
```java
for(int i = 0; i < 100000; i++) {
// do Something;
if(i % 100 == 0) {
Files.writeString(Paths.get(writeDir, "metadata.txt"), jsonObject.toString());
}
}
```
which clearly wins on simplicity (yes, that’s the complete code, no additional method required). The default options do already include the desired `StandardCharsets.UTF_8` and `StandardOpenOption.TRUNCATE_EXISTING`.
While it does open and close the file internally, it has some other performance tweaks which may compensate. Especially in the likely case that the string consists of ASCII characters only, as the implementation will simply write the string’s internal array directly to the file then. | A Stream does not allow to go back and rewrite content. A way to achieve what you want is using a [`RandomAccessFile`](https://docs.oracle.com/javase/8/docs/api/java/io/RandomAccessFile.html).
Its [`setLength()`](https://docs.oracle.com/javase/8/docs/api/java/io/RandomAccessFile.html#setLength-long-) method will truncate the file if you pass `0`.
Here is a simple example:
```
import java.io.*;
public class Test
{
public static void updateFile(RandomAccessFile raf, String content) throws IOException
{
raf.setLength(0);
raf.write(content.getBytes("UTF-8"));
}
public static void main(String[] args) throws IOException
{
try(RandomAccessFile raf = new RandomAccessFile("metadata.txt", "rw"))
{
updateFile(raf, "progress: 100");
updateFile(raf, "progress: 200");
}
}
}
``` |
71,386,061 | Our instruction manual is in markdown format. We improve the manual daily or weekly and then we would like to translate to other languages. Until now, this process is manual and we use TRADOS (a assisted translation software)
We are studying to improve the process. What we want to do is to translate it using Microsoft translator and then a human reviewer do the fine tune. The problem is how we can reuse the corrected document in Microsoft Translator for the next translation.
Many times we only change 2 or 3 words of a topic and then the translator would create a complete new translation, doing the reviewer work very tedious if the translation is not accurate.
I know that we can train the model, but I think that there is not a 100% of probabilities that the translator uses the review. Also, it seems very time consuming to maintain the distortionary after reviewing the document.
I was wondering if somebody has solved this kind a problem. | 2022/03/07 | [
"https://Stackoverflow.com/questions/71386061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5185236/"
] | A Stream does not allow to go back and rewrite content. A way to achieve what you want is using a [`RandomAccessFile`](https://docs.oracle.com/javase/8/docs/api/java/io/RandomAccessFile.html).
Its [`setLength()`](https://docs.oracle.com/javase/8/docs/api/java/io/RandomAccessFile.html#setLength-long-) method will truncate the file if you pass `0`.
Here is a simple example:
```
import java.io.*;
public class Test
{
public static void updateFile(RandomAccessFile raf, String content) throws IOException
{
raf.setLength(0);
raf.write(content.getBytes("UTF-8"));
}
public static void main(String[] args) throws IOException
{
try(RandomAccessFile raf = new RandomAccessFile("metadata.txt", "rw"))
{
updateFile(raf, "progress: 100");
updateFile(raf, "progress: 200");
}
}
}
``` | File operations are typically buffered by the underlying kernel, and so you're unlikely to see much of a performance benefit by keeping an open file descriptor for this kind of low throughput application.
Keeping your code as a single operation that gets to leave no state after it finishes, rather than designing it as a continuous rewindable stream, makes for an elegant, simple, and unless you've specifically requested synchronous IO, then also sufficiently performant implementation that gets to benefit from the optimizations of all of the layers that sit beneath it.
When you do get measurable impedance to performance by this, which I suspect you never will, you could use the `RandomAccessFile` API, or go unnecessarily lower level by using `FileChannel` as others already specified.
I think you shouldn't compromise the simplicity/elegance of your design for this kind of micro-optimization, which in the grand scheme of things, is guaranteed to be insignificant (one tiny write operation per 100 jobs processed). |
71,386,061 | Our instruction manual is in markdown format. We improve the manual daily or weekly and then we would like to translate to other languages. Until now, this process is manual and we use TRADOS (a assisted translation software)
We are studying to improve the process. What we want to do is to translate it using Microsoft translator and then a human reviewer do the fine tune. The problem is how we can reuse the corrected document in Microsoft Translator for the next translation.
Many times we only change 2 or 3 words of a topic and then the translator would create a complete new translation, doing the reviewer work very tedious if the translation is not accurate.
I know that we can train the model, but I think that there is not a 100% of probabilities that the translator uses the review. Also, it seems very time consuming to maintain the distortionary after reviewing the document.
I was wondering if somebody has solved this kind a problem. | 2022/03/07 | [
"https://Stackoverflow.com/questions/71386061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5185236/"
] | First of all, an expression like `writeDir.concat("/").concat("metadata.txt")` is reducing readability *and* performance. A straight-forward `writeDir + "/" + "metadata.txt"` will provide better performance. But since you’re constructing a string merely for constructing a `Path`, it’s even more straight-forward not to do the `Path`’s job in your code but rather use `Paths.get(writeDir, "metadata.txt")`.
You can not rewind a `BufferedWriter` but you can rewind a `FileChannel`. Therefore, to keep the channel open and rewind it when needed, you have to construct a new writer after rewinding:
```java
public static void writeMetaData(FileChannel ch, JSONObject jsonObj) throws IOException {
ch.position(0);
if(ch.size() > 0) ch.truncate(0);
Writer w = Channels.newWriter(ch, StandardCharsets.UTF_8.newEncoder(), 8192);
w.write(jsonObj.toString());
w.flush();
}
```
```java
try(FileChannel ch = FileChannel.open(Paths.get(writeDir, "metadata.txt"),
StandardOpenOption.WRITE, StandardOpenOption.CREATE)) {
for(int i = 0; i < 100000; i++) {
// do Something;
if(i % 100 == 0) {
writeMetaData(ch, jsonObject);
}
}
}
```
It’s important that the use of the `Writer` ends with `flush()` to force the write of all buffered data, but not `close()` as that would also close the underlying channel. Note that this code does not wrap the writer into a `BufferedWriter`; encoding text as UTF-8 is already a buffered operation and by requesting a larger buffer for the encoder, matching `BufferedWriter`’s default buffer size, we get the same effect of buffering without the copying overhead.
Since writing is not an end in itself, there’s a question left regarding your reading side. If the reader is trying to read the data in some intervals, there’s the risk of overlapping with the write, getting incomplete data.
You could use
```java
public static void writeMetaData(FileChannel ch, JSONObject jsonObj) throws IOException {
try(FileLock lock = ch.lock()) {
ch.position(0);
if(ch.size() > 0) ch.truncate(0);
Writer w = Channels.newWriter(ch, StandardCharsets.UTF_8.newEncoder(), 8192);
w.write(jsonObj.toString());
w.flush();
}
}
```
to lock the file during the write. But depending on the system, file locking might not be mandatory but only affect readers also trying to get a read lock.
---
When you use JDK 11 or newer, you may consider using
```java
for(int i = 0; i < 100000; i++) {
// do Something;
if(i % 100 == 0) {
Files.writeString(Paths.get(writeDir, "metadata.txt"), jsonObject.toString());
}
}
```
which clearly wins on simplicity (yes, that’s the complete code, no additional method required). The default options do already include the desired `StandardCharsets.UTF_8` and `StandardOpenOption.TRUNCATE_EXISTING`.
While it does open and close the file internally, it has some other performance tweaks which may compensate. Especially in the likely case that the string consists of ASCII characters only, as the implementation will simply write the string’s internal array directly to the file then. | File operations are typically buffered by the underlying kernel, and so you're unlikely to see much of a performance benefit by keeping an open file descriptor for this kind of low throughput application.
Keeping your code as a single operation that gets to leave no state after it finishes, rather than designing it as a continuous rewindable stream, makes for an elegant, simple, and unless you've specifically requested synchronous IO, then also sufficiently performant implementation that gets to benefit from the optimizations of all of the layers that sit beneath it.
When you do get measurable impedance to performance by this, which I suspect you never will, you could use the `RandomAccessFile` API, or go unnecessarily lower level by using `FileChannel` as others already specified.
I think you shouldn't compromise the simplicity/elegance of your design for this kind of micro-optimization, which in the grand scheme of things, is guaranteed to be insignificant (one tiny write operation per 100 jobs processed). |
162,524 | I have recently received peer review on a systematic review after six months, with revisions requested. This is on a dynamic subject with significant literature published since. I re-screened the papers and was able to include a further 5 from those published in the past 6 months.
Is it acceptable to update the review at revision with this additional data, as it will be undergoing peer review again regardless? I think it improves the review substantially to include more data, which is more recent, but I'm not sure if this is acceptable?
Thank you in advance! | 2021/02/11 | [
"https://academia.stackexchange.com/questions/162524",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/-1/"
] | Since it is undergoing peer review again, in general, you should be able to include the new papers. If you do this, though, highlight both the new papers and the changes to your conclusions in your author response / revision note, so that the reviewers know to pay particular attention to them and give them proper review - if you don't, they might not notice, and skip over important things because they think they already reviewed it.
It's common for reviewers to ask for new analyses or even experiments in revision, so this seems like a relatively normal kind of update in a revision cycle.
If in doubt, e-mail the managing editor. One way to do that productively is to make a specific proposal - e.g. include the new papers and highlight in the author response letter - and ask if that is an appropriate way to handle the situation for their journal.
A note that doesn't seem applicable to your specific situation, but may help others finding this answer: the exception to this is when you get what many journals call a "Minor Revision" decision, where only the editor will see the revisions - it won't go back out to reviewers. In such a situation, I would contact the managing editor and notify them of the situation. They may be able to handle the revision as a "Major Revision" and get reviews for it. | It is essential to update the systematic review in the revision, identifying new studies, incorporating them into the results, and reconsidering the conclusions. An overarching goal of systematic review is to present a synthesis of the existing literature as close in time to publication as possible. If there are known new studies and they have not been included in the systematic review, the review is obsolete when published.
The conclusions should be modified to reflect the new information even if the conclusions are different from those in the original submission.
It is likely that one reason for re-submitting for peer review is to assure that the systematic review has been updated and the manuscript revised as appropriate. If the systematic review has been updated and the manuscript revised appropriately to reflect any new information, the revision will likely be accepted quickly.
You will need to move fast in a rapidly changing field. |
42,534,593 | I'm looking to copy the custom classes added to the initial < option > over to the jQuery selectmenu UI generated list. I've tried using 'transferClasses: true' but that just transfers the main class across.
The select menu markup before jQuery UI is:
```
<select>
<option>Option 1</option>
<option>Option 2</option>
<option class="child-option">Sub Option 1</option>
<option class="child-option">Sub Option 2</option>
<option>Option 3</option>
...
</select>
```
---
EDIT: What jQuery UI outputs at the moment:
```
<div class="ui-selectmenu-menu">
<ul>
<li class="ui-menu-item"><div>Option 1</div></li>
<li class="ui-menu-item"><div>Option 2</div></li>
<li class="ui-menu-item"><div>Sub Option 1</div></li>
<li class="ui-menu-item"><div>Sub Option 2</div></li>
<li class="ui-menu-item"><div>Option 3</div></li>
</ul>
</div>
```
---
What I'd like jQuery UI to output:
```
<div class="ui-selectmenu-menu">
<ul>
<li class="ui-menu-item"><div>Option 1</div></li>
<li class="ui-menu-item"><div>Option 2</div></li>
<li class="ui-menu-item child-option"><div>Sub Option 1</div></li>
<li class="ui-menu-item child-option"><div>Sub Option 2</div></li>
<li class="ui-menu-item"><div>Option 3</div></li>
</ul>
</div>
```
I've tried the solutions in similar request threads [here](https://stackoverflow.com/questions/27348549/transfer-data-attributes-from-option-tags-to-ui-selectmenu-items) and [here](https://stackoverflow.com/questions/41570175/how-set-individual-styles-css-for-option-in-selectmenu-jquery-ui-selectmenu) but with no success.
---
EDIT 2:
The jQuery I'm using to generate the `ul` is:
```
$( "select" ).selectmenu({
transferClasses: true,
});
```
---
Any help would be great!
Thanks | 2017/03/01 | [
"https://Stackoverflow.com/questions/42534593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7641837/"
] | I was able to do it by looping over the newly created select menu using the open event. Apparently the actual items don't exist until the first time the open method is called.
```js
$('select').selectmenu({
open: function() {
$('div.ui-selectmenu-menu li.ui-menu-item').each(function(idx){
$(this).addClass( $('select option').eq(idx).attr('class') )
})
}
})
```
```css
.child-option {
background:red;
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<select>
<option>Option 1</option>
<option>Option 2</option>
<option class="child-option">Sub Option 1</option>
<option class="child-option">Sub Option 2</option>
<option>Option 3</option>
</select>
``` | It seems there no way you can instruct selectmenu to preserve classes or other attributes.
But you can create your own selectmenu extension via widget factory.
```js
//classyMenu widget extends/overrides selectmenu
$.widget("custom.classyMenu", $.ui.selectmenu, {
_renderItem: function(ul, item) {
var li = $("<li>" ,{
class: item.element.attr("class") //access the original item's class
}),
wrapper = $("<div>", {
text: item.label
});
if ( item.disabled ) {
li.addClass("ui-state-disabled");
}
return li.append( wrapper ).appendTo(ul);
}
});
$("select").classyMenu(); //use classyMenu instad of selectmenu()
$("#open").click(function(){
$("select").classyMenu("open");
});
$("#close").click(function(){
$("select").classyMenu("close");
});
```
```css
.bronze{color: #D1A684;}
.silver{color: silver;}
.gold{color: gold;}
ui-selectmenu-button{font-weight: bold}
```
```html
<link href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script
src="http://code.jquery.com/ui/1.12.1/jquery-ui.min.js"
integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU="
crossorigin="anonymous"></script>
<button id="open">Open</button>
<button id="close">Close</button>
<br />
<select>
<option value=""></option>
<option value="1" class="bronze">1</option>
<option value="2" class="silver">2</option>
<option value="3" class="gold">3</option>
</select>
``` |
42,534,593 | I'm looking to copy the custom classes added to the initial < option > over to the jQuery selectmenu UI generated list. I've tried using 'transferClasses: true' but that just transfers the main class across.
The select menu markup before jQuery UI is:
```
<select>
<option>Option 1</option>
<option>Option 2</option>
<option class="child-option">Sub Option 1</option>
<option class="child-option">Sub Option 2</option>
<option>Option 3</option>
...
</select>
```
---
EDIT: What jQuery UI outputs at the moment:
```
<div class="ui-selectmenu-menu">
<ul>
<li class="ui-menu-item"><div>Option 1</div></li>
<li class="ui-menu-item"><div>Option 2</div></li>
<li class="ui-menu-item"><div>Sub Option 1</div></li>
<li class="ui-menu-item"><div>Sub Option 2</div></li>
<li class="ui-menu-item"><div>Option 3</div></li>
</ul>
</div>
```
---
What I'd like jQuery UI to output:
```
<div class="ui-selectmenu-menu">
<ul>
<li class="ui-menu-item"><div>Option 1</div></li>
<li class="ui-menu-item"><div>Option 2</div></li>
<li class="ui-menu-item child-option"><div>Sub Option 1</div></li>
<li class="ui-menu-item child-option"><div>Sub Option 2</div></li>
<li class="ui-menu-item"><div>Option 3</div></li>
</ul>
</div>
```
I've tried the solutions in similar request threads [here](https://stackoverflow.com/questions/27348549/transfer-data-attributes-from-option-tags-to-ui-selectmenu-items) and [here](https://stackoverflow.com/questions/41570175/how-set-individual-styles-css-for-option-in-selectmenu-jquery-ui-selectmenu) but with no success.
---
EDIT 2:
The jQuery I'm using to generate the `ul` is:
```
$( "select" ).selectmenu({
transferClasses: true,
});
```
---
Any help would be great!
Thanks | 2017/03/01 | [
"https://Stackoverflow.com/questions/42534593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7641837/"
] | I was able to do it by looping over the newly created select menu using the open event. Apparently the actual items don't exist until the first time the open method is called.
```js
$('select').selectmenu({
open: function() {
$('div.ui-selectmenu-menu li.ui-menu-item').each(function(idx){
$(this).addClass( $('select option').eq(idx).attr('class') )
})
}
})
```
```css
.child-option {
background:red;
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<select>
<option>Option 1</option>
<option>Option 2</option>
<option class="child-option">Sub Option 1</option>
<option class="child-option">Sub Option 2</option>
<option>Option 3</option>
</select>
``` | There is a simple and direct way to add custom class to any jQuery UI widget - it's [classes option](http://learn.jquery.com/jquery-ui/widget-factory/classes-option/).
Let's take a simple case with [selectmenu](https://jqueryui.com/selectmenu/#default) jQuery widget.
HTML part is strict:
```
<select name="speed" id="speed" class="my-happy-decorated-class">
<option>Slower</option>
<option>Slow</option>
<option selected="selected">Medium</option>
<option>Fast</option>
<option>Faster</option>
</select>
```
As usual, in order to decorate this ugly default stuff with cute jQuery UI just afterwards the document has been loaded we apply appropriate for the widget jQuery UI-function **selectmenu()**:
```
<script>
$(function() {
$("#speed").selectmenu();
} );
</script>
```
As a result we get something like this:
```
<select name="speed" id="speed" style="display: none;" class="my-happy-decorated-class">
<option>Slower</option>
<option>Slow</option>
<option selected="selected">Medium</option>
<option>Fast</option>
<option>Faster</option>
</select>
<span tabindex="0" id="speed-button" role="combobox" aria-expanded="false" aria-autocomplete="list" aria-owns="speed-menu" aria-haspopup="true" class="ui-selectmenu-button ui-button ui-widget ui-selectmenu-button-closed ui-corner-all" aria-activedescendant="ui-id-3" aria-labelledby="ui-id-3" aria-disabled="false"><span class="ui-selectmenu-icon ui-icon ui-icon-triangle-1-s"></span><span class="ui-selectmenu-text">Medium</span></span>
<span class="ui-selectmenu-icon ui-icon ui-icon-triangle-1-s"></span>
<span class="ui-selectmenu-text">Medium</span>
<span tabindex="0" id="speed-button" role="combobox" aria-expanded="false" aria-autocomplete="list" aria-owns="speed-menu" aria-haspopup="true" class="ui-selectmenu-button ui-button ui-widget ui-selectmenu-button-closed ui-corner-all" aria-activedescendant="ui-id-3" aria-labelledby="ui-id-3" aria-disabled="false"><span class="ui-selectmenu-icon ui-icon ui-icon-triangle-1-s"></span><span class="ui-selectmenu-text">Medium</span></span>
```
As you can see the initial tag `<select ... class="my-happy-decorated-class">` got hidden and applying any style to class **"my-happy-decorated-class"** is useless.
This is the point where jQuery UI-option `classes` comes to help! Just apply the option to the widget by using the same **selectmenu()** command and you'll get the class in certain place in the result code:
```
<script>
$(function() {
$("#speed").selectmenu();
$("#speed").selectmenu({
classes: {
"ui-selectmenu-button-closed": "my-happy-decorated-class"
}
});
});
</script>
```
**NOTE, that "ui-selectmenu-button-closed" is the default class**, that jQuery UI sets to resulting HTML-tag used for displaying the widget! Names of default classes of different parts of any widget you can see with F12 in your browser.
Resulting HTML-code will be:
```
<select name="speed" id="speed" style="display: none;" class="my-happy-decorated-class">
<option>Slower</option>
<option>Slow</option>
<option selected="selected">Medium</option>
<option>Fast</option>
<option>Faster</option>
</select>
<span tabindex="0" id="speed-button" role="combobox" aria-expanded="false" aria-autocomplete="list" aria-owns="speed-menu" aria-haspopup="true" class="ui-selectmenu-button ui-button ui-widget
ui-selectmenu-button-closed my-happy-decorated-class
ui-corner-all" aria-activedescendant="ui-id-3" aria-labelledby="ui-id-3" aria-disabled="false"><span class="ui-selectmenu-icon ui-icon ui-icon-triangle-1-s"></span><span class="ui-selectmenu-text">Medium</span></span>
<span class="ui-selectmenu-icon ui-icon ui-icon-triangle-1-s"></span>
<span class="ui-selectmenu-text">Medium</span>
<span tabindex="0" id="speed-button" role="combobox" aria-expanded="false" aria-autocomplete="list" aria-owns="speed-menu" aria-haspopup="true" class="ui-selectmenu-button ui-button ui-widget ui-selectmenu-button-closed ui-corner-all" aria-activedescendant="ui-id-3" aria-labelledby="ui-id-3" aria-disabled="false"><span class="ui-selectmenu-icon ui-icon ui-icon-triangle-1-s"></span><span class="ui-selectmenu-text">Medium</span></span>
```
As you can see your class `my-happy-decorated-class`was added to the main visual resulting `span` of the widget and you are able to apply your styles to it. |
42,534,593 | I'm looking to copy the custom classes added to the initial < option > over to the jQuery selectmenu UI generated list. I've tried using 'transferClasses: true' but that just transfers the main class across.
The select menu markup before jQuery UI is:
```
<select>
<option>Option 1</option>
<option>Option 2</option>
<option class="child-option">Sub Option 1</option>
<option class="child-option">Sub Option 2</option>
<option>Option 3</option>
...
</select>
```
---
EDIT: What jQuery UI outputs at the moment:
```
<div class="ui-selectmenu-menu">
<ul>
<li class="ui-menu-item"><div>Option 1</div></li>
<li class="ui-menu-item"><div>Option 2</div></li>
<li class="ui-menu-item"><div>Sub Option 1</div></li>
<li class="ui-menu-item"><div>Sub Option 2</div></li>
<li class="ui-menu-item"><div>Option 3</div></li>
</ul>
</div>
```
---
What I'd like jQuery UI to output:
```
<div class="ui-selectmenu-menu">
<ul>
<li class="ui-menu-item"><div>Option 1</div></li>
<li class="ui-menu-item"><div>Option 2</div></li>
<li class="ui-menu-item child-option"><div>Sub Option 1</div></li>
<li class="ui-menu-item child-option"><div>Sub Option 2</div></li>
<li class="ui-menu-item"><div>Option 3</div></li>
</ul>
</div>
```
I've tried the solutions in similar request threads [here](https://stackoverflow.com/questions/27348549/transfer-data-attributes-from-option-tags-to-ui-selectmenu-items) and [here](https://stackoverflow.com/questions/41570175/how-set-individual-styles-css-for-option-in-selectmenu-jquery-ui-selectmenu) but with no success.
---
EDIT 2:
The jQuery I'm using to generate the `ul` is:
```
$( "select" ).selectmenu({
transferClasses: true,
});
```
---
Any help would be great!
Thanks | 2017/03/01 | [
"https://Stackoverflow.com/questions/42534593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7641837/"
] | I was able to do it by looping over the newly created select menu using the open event. Apparently the actual items don't exist until the first time the open method is called.
```js
$('select').selectmenu({
open: function() {
$('div.ui-selectmenu-menu li.ui-menu-item').each(function(idx){
$(this).addClass( $('select option').eq(idx).attr('class') )
})
}
})
```
```css
.child-option {
background:red;
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<select>
<option>Option 1</option>
<option>Option 2</option>
<option class="child-option">Sub Option 1</option>
<option class="child-option">Sub Option 2</option>
<option>Option 3</option>
</select>
``` | If you have multiple selects:
```
$("select").each(function(index, select) {
$(select).selectmenu({
create: function( event, ui ) {
$(select).next().addClass($(select).attr('class'));
},
open: function( event, ui ) {
// Maybe remove classes or whatever
}
});
});
``` |
42,534,593 | I'm looking to copy the custom classes added to the initial < option > over to the jQuery selectmenu UI generated list. I've tried using 'transferClasses: true' but that just transfers the main class across.
The select menu markup before jQuery UI is:
```
<select>
<option>Option 1</option>
<option>Option 2</option>
<option class="child-option">Sub Option 1</option>
<option class="child-option">Sub Option 2</option>
<option>Option 3</option>
...
</select>
```
---
EDIT: What jQuery UI outputs at the moment:
```
<div class="ui-selectmenu-menu">
<ul>
<li class="ui-menu-item"><div>Option 1</div></li>
<li class="ui-menu-item"><div>Option 2</div></li>
<li class="ui-menu-item"><div>Sub Option 1</div></li>
<li class="ui-menu-item"><div>Sub Option 2</div></li>
<li class="ui-menu-item"><div>Option 3</div></li>
</ul>
</div>
```
---
What I'd like jQuery UI to output:
```
<div class="ui-selectmenu-menu">
<ul>
<li class="ui-menu-item"><div>Option 1</div></li>
<li class="ui-menu-item"><div>Option 2</div></li>
<li class="ui-menu-item child-option"><div>Sub Option 1</div></li>
<li class="ui-menu-item child-option"><div>Sub Option 2</div></li>
<li class="ui-menu-item"><div>Option 3</div></li>
</ul>
</div>
```
I've tried the solutions in similar request threads [here](https://stackoverflow.com/questions/27348549/transfer-data-attributes-from-option-tags-to-ui-selectmenu-items) and [here](https://stackoverflow.com/questions/41570175/how-set-individual-styles-css-for-option-in-selectmenu-jquery-ui-selectmenu) but with no success.
---
EDIT 2:
The jQuery I'm using to generate the `ul` is:
```
$( "select" ).selectmenu({
transferClasses: true,
});
```
---
Any help would be great!
Thanks | 2017/03/01 | [
"https://Stackoverflow.com/questions/42534593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7641837/"
] | It seems there no way you can instruct selectmenu to preserve classes or other attributes.
But you can create your own selectmenu extension via widget factory.
```js
//classyMenu widget extends/overrides selectmenu
$.widget("custom.classyMenu", $.ui.selectmenu, {
_renderItem: function(ul, item) {
var li = $("<li>" ,{
class: item.element.attr("class") //access the original item's class
}),
wrapper = $("<div>", {
text: item.label
});
if ( item.disabled ) {
li.addClass("ui-state-disabled");
}
return li.append( wrapper ).appendTo(ul);
}
});
$("select").classyMenu(); //use classyMenu instad of selectmenu()
$("#open").click(function(){
$("select").classyMenu("open");
});
$("#close").click(function(){
$("select").classyMenu("close");
});
```
```css
.bronze{color: #D1A684;}
.silver{color: silver;}
.gold{color: gold;}
ui-selectmenu-button{font-weight: bold}
```
```html
<link href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script
src="http://code.jquery.com/ui/1.12.1/jquery-ui.min.js"
integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU="
crossorigin="anonymous"></script>
<button id="open">Open</button>
<button id="close">Close</button>
<br />
<select>
<option value=""></option>
<option value="1" class="bronze">1</option>
<option value="2" class="silver">2</option>
<option value="3" class="gold">3</option>
</select>
``` | There is a simple and direct way to add custom class to any jQuery UI widget - it's [classes option](http://learn.jquery.com/jquery-ui/widget-factory/classes-option/).
Let's take a simple case with [selectmenu](https://jqueryui.com/selectmenu/#default) jQuery widget.
HTML part is strict:
```
<select name="speed" id="speed" class="my-happy-decorated-class">
<option>Slower</option>
<option>Slow</option>
<option selected="selected">Medium</option>
<option>Fast</option>
<option>Faster</option>
</select>
```
As usual, in order to decorate this ugly default stuff with cute jQuery UI just afterwards the document has been loaded we apply appropriate for the widget jQuery UI-function **selectmenu()**:
```
<script>
$(function() {
$("#speed").selectmenu();
} );
</script>
```
As a result we get something like this:
```
<select name="speed" id="speed" style="display: none;" class="my-happy-decorated-class">
<option>Slower</option>
<option>Slow</option>
<option selected="selected">Medium</option>
<option>Fast</option>
<option>Faster</option>
</select>
<span tabindex="0" id="speed-button" role="combobox" aria-expanded="false" aria-autocomplete="list" aria-owns="speed-menu" aria-haspopup="true" class="ui-selectmenu-button ui-button ui-widget ui-selectmenu-button-closed ui-corner-all" aria-activedescendant="ui-id-3" aria-labelledby="ui-id-3" aria-disabled="false"><span class="ui-selectmenu-icon ui-icon ui-icon-triangle-1-s"></span><span class="ui-selectmenu-text">Medium</span></span>
<span class="ui-selectmenu-icon ui-icon ui-icon-triangle-1-s"></span>
<span class="ui-selectmenu-text">Medium</span>
<span tabindex="0" id="speed-button" role="combobox" aria-expanded="false" aria-autocomplete="list" aria-owns="speed-menu" aria-haspopup="true" class="ui-selectmenu-button ui-button ui-widget ui-selectmenu-button-closed ui-corner-all" aria-activedescendant="ui-id-3" aria-labelledby="ui-id-3" aria-disabled="false"><span class="ui-selectmenu-icon ui-icon ui-icon-triangle-1-s"></span><span class="ui-selectmenu-text">Medium</span></span>
```
As you can see the initial tag `<select ... class="my-happy-decorated-class">` got hidden and applying any style to class **"my-happy-decorated-class"** is useless.
This is the point where jQuery UI-option `classes` comes to help! Just apply the option to the widget by using the same **selectmenu()** command and you'll get the class in certain place in the result code:
```
<script>
$(function() {
$("#speed").selectmenu();
$("#speed").selectmenu({
classes: {
"ui-selectmenu-button-closed": "my-happy-decorated-class"
}
});
});
</script>
```
**NOTE, that "ui-selectmenu-button-closed" is the default class**, that jQuery UI sets to resulting HTML-tag used for displaying the widget! Names of default classes of different parts of any widget you can see with F12 in your browser.
Resulting HTML-code will be:
```
<select name="speed" id="speed" style="display: none;" class="my-happy-decorated-class">
<option>Slower</option>
<option>Slow</option>
<option selected="selected">Medium</option>
<option>Fast</option>
<option>Faster</option>
</select>
<span tabindex="0" id="speed-button" role="combobox" aria-expanded="false" aria-autocomplete="list" aria-owns="speed-menu" aria-haspopup="true" class="ui-selectmenu-button ui-button ui-widget
ui-selectmenu-button-closed my-happy-decorated-class
ui-corner-all" aria-activedescendant="ui-id-3" aria-labelledby="ui-id-3" aria-disabled="false"><span class="ui-selectmenu-icon ui-icon ui-icon-triangle-1-s"></span><span class="ui-selectmenu-text">Medium</span></span>
<span class="ui-selectmenu-icon ui-icon ui-icon-triangle-1-s"></span>
<span class="ui-selectmenu-text">Medium</span>
<span tabindex="0" id="speed-button" role="combobox" aria-expanded="false" aria-autocomplete="list" aria-owns="speed-menu" aria-haspopup="true" class="ui-selectmenu-button ui-button ui-widget ui-selectmenu-button-closed ui-corner-all" aria-activedescendant="ui-id-3" aria-labelledby="ui-id-3" aria-disabled="false"><span class="ui-selectmenu-icon ui-icon ui-icon-triangle-1-s"></span><span class="ui-selectmenu-text">Medium</span></span>
```
As you can see your class `my-happy-decorated-class`was added to the main visual resulting `span` of the widget and you are able to apply your styles to it. |
42,534,593 | I'm looking to copy the custom classes added to the initial < option > over to the jQuery selectmenu UI generated list. I've tried using 'transferClasses: true' but that just transfers the main class across.
The select menu markup before jQuery UI is:
```
<select>
<option>Option 1</option>
<option>Option 2</option>
<option class="child-option">Sub Option 1</option>
<option class="child-option">Sub Option 2</option>
<option>Option 3</option>
...
</select>
```
---
EDIT: What jQuery UI outputs at the moment:
```
<div class="ui-selectmenu-menu">
<ul>
<li class="ui-menu-item"><div>Option 1</div></li>
<li class="ui-menu-item"><div>Option 2</div></li>
<li class="ui-menu-item"><div>Sub Option 1</div></li>
<li class="ui-menu-item"><div>Sub Option 2</div></li>
<li class="ui-menu-item"><div>Option 3</div></li>
</ul>
</div>
```
---
What I'd like jQuery UI to output:
```
<div class="ui-selectmenu-menu">
<ul>
<li class="ui-menu-item"><div>Option 1</div></li>
<li class="ui-menu-item"><div>Option 2</div></li>
<li class="ui-menu-item child-option"><div>Sub Option 1</div></li>
<li class="ui-menu-item child-option"><div>Sub Option 2</div></li>
<li class="ui-menu-item"><div>Option 3</div></li>
</ul>
</div>
```
I've tried the solutions in similar request threads [here](https://stackoverflow.com/questions/27348549/transfer-data-attributes-from-option-tags-to-ui-selectmenu-items) and [here](https://stackoverflow.com/questions/41570175/how-set-individual-styles-css-for-option-in-selectmenu-jquery-ui-selectmenu) but with no success.
---
EDIT 2:
The jQuery I'm using to generate the `ul` is:
```
$( "select" ).selectmenu({
transferClasses: true,
});
```
---
Any help would be great!
Thanks | 2017/03/01 | [
"https://Stackoverflow.com/questions/42534593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7641837/"
] | It seems there no way you can instruct selectmenu to preserve classes or other attributes.
But you can create your own selectmenu extension via widget factory.
```js
//classyMenu widget extends/overrides selectmenu
$.widget("custom.classyMenu", $.ui.selectmenu, {
_renderItem: function(ul, item) {
var li = $("<li>" ,{
class: item.element.attr("class") //access the original item's class
}),
wrapper = $("<div>", {
text: item.label
});
if ( item.disabled ) {
li.addClass("ui-state-disabled");
}
return li.append( wrapper ).appendTo(ul);
}
});
$("select").classyMenu(); //use classyMenu instad of selectmenu()
$("#open").click(function(){
$("select").classyMenu("open");
});
$("#close").click(function(){
$("select").classyMenu("close");
});
```
```css
.bronze{color: #D1A684;}
.silver{color: silver;}
.gold{color: gold;}
ui-selectmenu-button{font-weight: bold}
```
```html
<link href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script
src="http://code.jquery.com/ui/1.12.1/jquery-ui.min.js"
integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU="
crossorigin="anonymous"></script>
<button id="open">Open</button>
<button id="close">Close</button>
<br />
<select>
<option value=""></option>
<option value="1" class="bronze">1</option>
<option value="2" class="silver">2</option>
<option value="3" class="gold">3</option>
</select>
``` | If you have multiple selects:
```
$("select").each(function(index, select) {
$(select).selectmenu({
create: function( event, ui ) {
$(select).next().addClass($(select).attr('class'));
},
open: function( event, ui ) {
// Maybe remove classes or whatever
}
});
});
``` |
60,032,119 | Is it possible to catch all thrown exceptions of a particular type, say IllegalArgumentException, throughout the entire Spring Boot application and handle it one place? I want to introduce some additional logging for particular types of exception in application and I am looking for a way to avoid duplicating logic or method calls throughout the application? | 2020/02/03 | [
"https://Stackoverflow.com/questions/60032119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1541964/"
] | Take a look at the annotation [@ExceptionHandler(value=YourException.class)](https://www.tutorialspoint.com/spring_boot/spring_boot_exception_handling.htm) and @ControllerAdvice it allows you to handle custom exceptions. The Controller Advice class can handle the exception globally. We can define any Exception Handler methods in this class file.
```
@ControllerAdvice
public class ProductExceptionController {
@ExceptionHandler(value = ProductNotfoundException.class)
public ResponseEntity<Object> exception(ProductNotfoundException exception) {
return new ResponseEntity<>("Product not found", HttpStatus.NOT_FOUND);
}
}
``` | Spring AOP can be used to address this cross cutting concern.
[@AfterThrowing](https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#aop-advice-after-throwing) advice can be used for this purpose.
>
> The name used in the throwing attribute must correspond to the name of
> a parameter in the advice method. When a method execution exits by
> throwing an exception, the exception is passed to the advice method as
> the corresponding argument value. A throwing clause also restricts
> matching to only those method executions that throw an exception of
> the specified type
>
>
>
Example can be found [here](https://howtodoinjava.com/spring-aop/aspectj-afterthrowing-annotation-example/) |
60,032,119 | Is it possible to catch all thrown exceptions of a particular type, say IllegalArgumentException, throughout the entire Spring Boot application and handle it one place? I want to introduce some additional logging for particular types of exception in application and I am looking for a way to avoid duplicating logic or method calls throughout the application? | 2020/02/03 | [
"https://Stackoverflow.com/questions/60032119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1541964/"
] | Take a look at the annotation [@ExceptionHandler(value=YourException.class)](https://www.tutorialspoint.com/spring_boot/spring_boot_exception_handling.htm) and @ControllerAdvice it allows you to handle custom exceptions. The Controller Advice class can handle the exception globally. We can define any Exception Handler methods in this class file.
```
@ControllerAdvice
public class ProductExceptionController {
@ExceptionHandler(value = ProductNotfoundException.class)
public ResponseEntity<Object> exception(ProductNotfoundException exception) {
return new ResponseEntity<>("Product not found", HttpStatus.NOT_FOUND);
}
}
``` | Springboot provides us with the capability to handle exceptions globally using the `@ControllerAdvice` annotation . So, instead of handling exceptions and logging it in each controller, you could actually throw the exception from every controller and handle it in a single place like :
```
BusinessException extends RunTimeException {
public BusinessException(String message, Throwable cause) {
super(message, cause);
}
}
@ControllerAdvice
public class ExceptionController {
@ExceptionHandler(value
= { BusinessException.class,IllegalArgumentException.class})
protected ResponseEntity<Object> handleCustomException(
RuntimeException ex, WebRequest request) {
String bodyOfResponse = "This should be application specific";
return handleExceptionInternal(ex, bodyOfResponse,
new HttpHeaders(), HttpStatus.NOTFOUND, request);
}
}
```
In your case, you could create a custom exception class and throw your custom exception from where ever your custom logic is needed. So, your could then handle this custom exception globally to provide your logic. This is one way to handle exceptions globally without duplicating logic. You could also do this using spring aop using pointcut.
```
@Aspect
public class LoggingAspect {
@AfterThrowing (pointcut = "execution(* com.yourservice.yourpackage.*(..))", throwing = "ex")
public void logAfterThrowingAllMethods(Exception ex) throws Throwable
{
System.out.println("****LoggingAspect.logAfterThrowingAllMethods() " + ex);
}
}
```
Just add `spring aop` and `aspectJ` as dependencies for this approach. |
2,248,612 | buy.php:
```
<form action="cart.php" method="post">
<?php foreach($product['varieties'] as $variety): ?>
<input style="width:10px; margin-left:9px; " name="price[]" type="checkbox" value="<?php echo $variety['price'] . '_' . $variety['size']; ?>" />';
<?php end foreach; ?>
</form>
```
cart.php:
```
list($aDoor, size) = split('_', $_POST['price']); // line 207
if(empty($aDoor))
{
echo("You didn't select any buildings.");
}
else
{
echo "Sum of vlues = ".array_sum($aDoor);
}
```
In cart.php there is the following syntax error:
>
> syntax error, unexpected ')',
> expecting T\_PAAMAYIM\_NEKUDOTAYIM in
> store/cart.php on line 207
>
>
>
I am expecting in cart.php to receive the two index values size and price independetly so I can use it and CSS it where ever i want. I am expecting that with the function list() and split() the variables variety and $aDoor with the price value will able to separate this two variables to be use wherever I want in cart.php
Help. | 2010/02/11 | [
"https://Stackoverflow.com/questions/2248612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/269837/"
] | Missing a `$`:
`list($aDoor, $size) = split('_', $_POST['price']); // line 207`
I think you are trying to do something like:
```
<?php
$aDoor = array();
$size = array();
foreach ($_POST['price'] as $p)
{
list($a, $b) = explode('_', $p);
$aDoor[] = $a;
$size[] = $b;
}
if(empty($aDoor))
{
echo("You didn't select any buildings.");
}
else
{
echo "Sum of vlues = ".array_sum($aDoor);
}
?>
``` | It's Hebrew. It means twice colon. It also happens when you miss the $, like you have.
<http://en.wikipedia.org/wiki/Scope_resolution_operator#PHP> |
2,248,612 | buy.php:
```
<form action="cart.php" method="post">
<?php foreach($product['varieties'] as $variety): ?>
<input style="width:10px; margin-left:9px; " name="price[]" type="checkbox" value="<?php echo $variety['price'] . '_' . $variety['size']; ?>" />';
<?php end foreach; ?>
</form>
```
cart.php:
```
list($aDoor, size) = split('_', $_POST['price']); // line 207
if(empty($aDoor))
{
echo("You didn't select any buildings.");
}
else
{
echo "Sum of vlues = ".array_sum($aDoor);
}
```
In cart.php there is the following syntax error:
>
> syntax error, unexpected ')',
> expecting T\_PAAMAYIM\_NEKUDOTAYIM in
> store/cart.php on line 207
>
>
>
I am expecting in cart.php to receive the two index values size and price independetly so I can use it and CSS it where ever i want. I am expecting that with the function list() and split() the variables variety and $aDoor with the price value will able to separate this two variables to be use wherever I want in cart.php
Help. | 2010/02/11 | [
"https://Stackoverflow.com/questions/2248612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/269837/"
] | Missing a `$`:
`list($aDoor, $size) = split('_', $_POST['price']); // line 207`
I think you are trying to do something like:
```
<?php
$aDoor = array();
$size = array();
foreach ($_POST['price'] as $p)
{
list($a, $b) = explode('_', $p);
$aDoor[] = $a;
$size[] = $b;
}
if(empty($aDoor))
{
echo("You didn't select any buildings.");
}
else
{
echo "Sum of vlues = ".array_sum($aDoor);
}
?>
``` | @Konforce I test your script and it works good.
Sorry I don't know what I was saying but I have to work it like this to list $size and prices $aDoor with the total below. I just have to style it now.
```
<?php
list($aDoor, $size) = split('_', $_POST['price']);
$aDoor = array();
$size = array();
foreach ($_POST['price'] as $p)
{
list($a, $b) = explode('_', $p);
$aDoor[] = $a;
$size[] = $b;
}
if(empty($aDoor))
{
echo("You didn't select any buildings.");
}
else
{
$V = count($size);
for($i=0; $i < $V; $i++)
{
echo($size[$i] . " ");
}
$A = count($aDoor);
for($i=0; $i < $A; $i++)
{
echo($aDoor[$i] . " ");
}
echo "Sum of vlues = ".array_sum($aDoor);
}
?>
``` |
2,248,612 | buy.php:
```
<form action="cart.php" method="post">
<?php foreach($product['varieties'] as $variety): ?>
<input style="width:10px; margin-left:9px; " name="price[]" type="checkbox" value="<?php echo $variety['price'] . '_' . $variety['size']; ?>" />';
<?php end foreach; ?>
</form>
```
cart.php:
```
list($aDoor, size) = split('_', $_POST['price']); // line 207
if(empty($aDoor))
{
echo("You didn't select any buildings.");
}
else
{
echo "Sum of vlues = ".array_sum($aDoor);
}
```
In cart.php there is the following syntax error:
>
> syntax error, unexpected ')',
> expecting T\_PAAMAYIM\_NEKUDOTAYIM in
> store/cart.php on line 207
>
>
>
I am expecting in cart.php to receive the two index values size and price independetly so I can use it and CSS it where ever i want. I am expecting that with the function list() and split() the variables variety and $aDoor with the price value will able to separate this two variables to be use wherever I want in cart.php
Help. | 2010/02/11 | [
"https://Stackoverflow.com/questions/2248612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/269837/"
] | Missing a `$`:
`list($aDoor, $size) = split('_', $_POST['price']); // line 207`
I think you are trying to do something like:
```
<?php
$aDoor = array();
$size = array();
foreach ($_POST['price'] as $p)
{
list($a, $b) = explode('_', $p);
$aDoor[] = $a;
$size[] = $b;
}
if(empty($aDoor))
{
echo("You didn't select any buildings.");
}
else
{
echo "Sum of vlues = ".array_sum($aDoor);
}
?>
``` | @konforce can you see at the begining where you have set up the variable $aDoor and $size as arrays?
```
$aDoor = array();
$size = array();
```
Well now I am adding another index value that is not an array it is an string
```
<input style="width:10px; margin-left:9px; " name="price[]" type="checkbox" value="' . $variety['price']. '_'. $variety['variety'] '_'. $product['name'].'" />
```
you see the '. $product['name'].' well how can I receive it in cart.php
in cart.php you have done the script as below but those are for arrays this time this one is not an array and I am seding it through the same form input.
```
$aDoor = array();
$size = array();
foreach ($_POST['price'] as $p)
{
list($a, $b) = explode('_', $p);
$aDoor[] = $a;
$size[] = $b;
}
``` |
2,248,612 | buy.php:
```
<form action="cart.php" method="post">
<?php foreach($product['varieties'] as $variety): ?>
<input style="width:10px; margin-left:9px; " name="price[]" type="checkbox" value="<?php echo $variety['price'] . '_' . $variety['size']; ?>" />';
<?php end foreach; ?>
</form>
```
cart.php:
```
list($aDoor, size) = split('_', $_POST['price']); // line 207
if(empty($aDoor))
{
echo("You didn't select any buildings.");
}
else
{
echo "Sum of vlues = ".array_sum($aDoor);
}
```
In cart.php there is the following syntax error:
>
> syntax error, unexpected ')',
> expecting T\_PAAMAYIM\_NEKUDOTAYIM in
> store/cart.php on line 207
>
>
>
I am expecting in cart.php to receive the two index values size and price independetly so I can use it and CSS it where ever i want. I am expecting that with the function list() and split() the variables variety and $aDoor with the price value will able to separate this two variables to be use wherever I want in cart.php
Help. | 2010/02/11 | [
"https://Stackoverflow.com/questions/2248612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/269837/"
] | See [this](https://stackoverflow.com/questions/2118755/questions-every-good-php-developer-should-be-able-to-answer/2118987#2118987) for a good primer. And Google is your friend :) | It's Hebrew. It means twice colon. It also happens when you miss the $, like you have.
<http://en.wikipedia.org/wiki/Scope_resolution_operator#PHP> |
2,248,612 | buy.php:
```
<form action="cart.php" method="post">
<?php foreach($product['varieties'] as $variety): ?>
<input style="width:10px; margin-left:9px; " name="price[]" type="checkbox" value="<?php echo $variety['price'] . '_' . $variety['size']; ?>" />';
<?php end foreach; ?>
</form>
```
cart.php:
```
list($aDoor, size) = split('_', $_POST['price']); // line 207
if(empty($aDoor))
{
echo("You didn't select any buildings.");
}
else
{
echo "Sum of vlues = ".array_sum($aDoor);
}
```
In cart.php there is the following syntax error:
>
> syntax error, unexpected ')',
> expecting T\_PAAMAYIM\_NEKUDOTAYIM in
> store/cart.php on line 207
>
>
>
I am expecting in cart.php to receive the two index values size and price independetly so I can use it and CSS it where ever i want. I am expecting that with the function list() and split() the variables variety and $aDoor with the price value will able to separate this two variables to be use wherever I want in cart.php
Help. | 2010/02/11 | [
"https://Stackoverflow.com/questions/2248612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/269837/"
] | See [this](https://stackoverflow.com/questions/2118755/questions-every-good-php-developer-should-be-able-to-answer/2118987#2118987) for a good primer. And Google is your friend :) | @Konforce I test your script and it works good.
Sorry I don't know what I was saying but I have to work it like this to list $size and prices $aDoor with the total below. I just have to style it now.
```
<?php
list($aDoor, $size) = split('_', $_POST['price']);
$aDoor = array();
$size = array();
foreach ($_POST['price'] as $p)
{
list($a, $b) = explode('_', $p);
$aDoor[] = $a;
$size[] = $b;
}
if(empty($aDoor))
{
echo("You didn't select any buildings.");
}
else
{
$V = count($size);
for($i=0; $i < $V; $i++)
{
echo($size[$i] . " ");
}
$A = count($aDoor);
for($i=0; $i < $A; $i++)
{
echo($aDoor[$i] . " ");
}
echo "Sum of vlues = ".array_sum($aDoor);
}
?>
``` |
2,248,612 | buy.php:
```
<form action="cart.php" method="post">
<?php foreach($product['varieties'] as $variety): ?>
<input style="width:10px; margin-left:9px; " name="price[]" type="checkbox" value="<?php echo $variety['price'] . '_' . $variety['size']; ?>" />';
<?php end foreach; ?>
</form>
```
cart.php:
```
list($aDoor, size) = split('_', $_POST['price']); // line 207
if(empty($aDoor))
{
echo("You didn't select any buildings.");
}
else
{
echo "Sum of vlues = ".array_sum($aDoor);
}
```
In cart.php there is the following syntax error:
>
> syntax error, unexpected ')',
> expecting T\_PAAMAYIM\_NEKUDOTAYIM in
> store/cart.php on line 207
>
>
>
I am expecting in cart.php to receive the two index values size and price independetly so I can use it and CSS it where ever i want. I am expecting that with the function list() and split() the variables variety and $aDoor with the price value will able to separate this two variables to be use wherever I want in cart.php
Help. | 2010/02/11 | [
"https://Stackoverflow.com/questions/2248612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/269837/"
] | See [this](https://stackoverflow.com/questions/2118755/questions-every-good-php-developer-should-be-able-to-answer/2118987#2118987) for a good primer. And Google is your friend :) | @konforce can you see at the begining where you have set up the variable $aDoor and $size as arrays?
```
$aDoor = array();
$size = array();
```
Well now I am adding another index value that is not an array it is an string
```
<input style="width:10px; margin-left:9px; " name="price[]" type="checkbox" value="' . $variety['price']. '_'. $variety['variety'] '_'. $product['name'].'" />
```
you see the '. $product['name'].' well how can I receive it in cart.php
in cart.php you have done the script as below but those are for arrays this time this one is not an array and I am seding it through the same form input.
```
$aDoor = array();
$size = array();
foreach ($_POST['price'] as $p)
{
list($a, $b) = explode('_', $p);
$aDoor[] = $a;
$size[] = $b;
}
``` |
2,248,612 | buy.php:
```
<form action="cart.php" method="post">
<?php foreach($product['varieties'] as $variety): ?>
<input style="width:10px; margin-left:9px; " name="price[]" type="checkbox" value="<?php echo $variety['price'] . '_' . $variety['size']; ?>" />';
<?php end foreach; ?>
</form>
```
cart.php:
```
list($aDoor, size) = split('_', $_POST['price']); // line 207
if(empty($aDoor))
{
echo("You didn't select any buildings.");
}
else
{
echo "Sum of vlues = ".array_sum($aDoor);
}
```
In cart.php there is the following syntax error:
>
> syntax error, unexpected ')',
> expecting T\_PAAMAYIM\_NEKUDOTAYIM in
> store/cart.php on line 207
>
>
>
I am expecting in cart.php to receive the two index values size and price independetly so I can use it and CSS it where ever i want. I am expecting that with the function list() and split() the variables variety and $aDoor with the price value will able to separate this two variables to be use wherever I want in cart.php
Help. | 2010/02/11 | [
"https://Stackoverflow.com/questions/2248612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/269837/"
] | @konforce can you see at the begining where you have set up the variable $aDoor and $size as arrays?
```
$aDoor = array();
$size = array();
```
Well now I am adding another index value that is not an array it is an string
```
<input style="width:10px; margin-left:9px; " name="price[]" type="checkbox" value="' . $variety['price']. '_'. $variety['variety'] '_'. $product['name'].'" />
```
you see the '. $product['name'].' well how can I receive it in cart.php
in cart.php you have done the script as below but those are for arrays this time this one is not an array and I am seding it through the same form input.
```
$aDoor = array();
$size = array();
foreach ($_POST['price'] as $p)
{
list($a, $b) = explode('_', $p);
$aDoor[] = $a;
$size[] = $b;
}
``` | It's Hebrew. It means twice colon. It also happens when you miss the $, like you have.
<http://en.wikipedia.org/wiki/Scope_resolution_operator#PHP> |
2,248,612 | buy.php:
```
<form action="cart.php" method="post">
<?php foreach($product['varieties'] as $variety): ?>
<input style="width:10px; margin-left:9px; " name="price[]" type="checkbox" value="<?php echo $variety['price'] . '_' . $variety['size']; ?>" />';
<?php end foreach; ?>
</form>
```
cart.php:
```
list($aDoor, size) = split('_', $_POST['price']); // line 207
if(empty($aDoor))
{
echo("You didn't select any buildings.");
}
else
{
echo "Sum of vlues = ".array_sum($aDoor);
}
```
In cart.php there is the following syntax error:
>
> syntax error, unexpected ')',
> expecting T\_PAAMAYIM\_NEKUDOTAYIM in
> store/cart.php on line 207
>
>
>
I am expecting in cart.php to receive the two index values size and price independetly so I can use it and CSS it where ever i want. I am expecting that with the function list() and split() the variables variety and $aDoor with the price value will able to separate this two variables to be use wherever I want in cart.php
Help. | 2010/02/11 | [
"https://Stackoverflow.com/questions/2248612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/269837/"
] | @konforce can you see at the begining where you have set up the variable $aDoor and $size as arrays?
```
$aDoor = array();
$size = array();
```
Well now I am adding another index value that is not an array it is an string
```
<input style="width:10px; margin-left:9px; " name="price[]" type="checkbox" value="' . $variety['price']. '_'. $variety['variety'] '_'. $product['name'].'" />
```
you see the '. $product['name'].' well how can I receive it in cart.php
in cart.php you have done the script as below but those are for arrays this time this one is not an array and I am seding it through the same form input.
```
$aDoor = array();
$size = array();
foreach ($_POST['price'] as $p)
{
list($a, $b) = explode('_', $p);
$aDoor[] = $a;
$size[] = $b;
}
``` | @Konforce I test your script and it works good.
Sorry I don't know what I was saying but I have to work it like this to list $size and prices $aDoor with the total below. I just have to style it now.
```
<?php
list($aDoor, $size) = split('_', $_POST['price']);
$aDoor = array();
$size = array();
foreach ($_POST['price'] as $p)
{
list($a, $b) = explode('_', $p);
$aDoor[] = $a;
$size[] = $b;
}
if(empty($aDoor))
{
echo("You didn't select any buildings.");
}
else
{
$V = count($size);
for($i=0; $i < $V; $i++)
{
echo($size[$i] . " ");
}
$A = count($aDoor);
for($i=0; $i < $A; $i++)
{
echo($aDoor[$i] . " ");
}
echo "Sum of vlues = ".array_sum($aDoor);
}
?>
``` |
35,034,391 | I've manage to create a form embedded in another form but I think I'm not doing something right. Here's my code
Category
```
class Category
{
private $id;
private $name;
/**
* @ORM\OneToMany(targetEntity="Category", mappedBy="category")
*/
private $subcategorues;
public function __construct()
{
$this->subcategorues = new \Doctrine\Common\Collections\ArrayCollection();
}
public function getId()
{
return $this->id;
}
public function setName($name)
{
$this->name = $name;
return $this;
}
public function getName()
{
return $this->name;
}
public function addSubcategorue(\AppBundle\Entity\Category $subcategorues)
{
$this->subcategorues[] = $subcategorues;
return $this;
}
public function removeSubcategorue(\AppBundle\Entity\Category $subcategorues)
{
$this->subcategorues->removeElement($subcategorues);
}
public function getSubcategorues()
{
return $this->subcategorues;
}
}
```
Subcategory
```
class Subcategory
{
private $id;
private $name;
/**
* @ORM\ManyToOne(targetEntity="Category", inversedBy="subcategories")
* @ORM\JoinColumn(name="category_id", referencedColumnName="id")
*/
private $category;
/**
* @return mixed
*/
public function getCategory()
{
return $this->category;
}
/**
* @param mixed $category
*/
public function setCategory($category)
{
$this->category = $category;
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
public function setName($name)
{
$this->name = $name;
return $this;
}
public function getName()
{
return $this->name;
}
}
```
CategoryType
```
.......
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', 'entity', [
'class' => 'AppBundle\Entity\Category',
'choice_label' => 'name'
]);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => 'AppBundle\Entity\Category'
]);
}
......
```
SubcategoryType
```
$builder
->add('category', new CategoryType(), [
'label' => false
])
->add('name', 'text')
->add('save', 'submit')
;
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => 'AppBundle\Entity\Subcategory'
]);
}
```
DefaultController
```
public function indexAction(Request $request)
{
$subcategory = new Subcategory();
$form = $this->createForm(new SubcategoryType(), $subcategory);
$form->handleRequest($request);
if($form->isValid()){
$em = $this->getDoctrine()->getManager();
$subcategory->setCategory($subcategory->getCategory()->getName());
$em->persist($subcategory);
$em->flush();
return new Response(sprintf('ID %d', $subcategory->getId()));
}
return $this->render('AppBundle::layout.html.twig', [
'form' => $form->createView(),
]);
}
```
Please notice this line of code `$subcategory->setCategory($subcategory->getCategory()->getName())`;
I need that line in order to save the entity to the database otherwise I get an error. So my question is is there a way to skip this line of code and pass category object on the fly to subcategory->category property instead of doing that manually?
//EDIT
Here's the output of dump($form->getData());
```
DefaultController.php on line 33:
Subcategory {#467 ▼
-id: null
-name: "Uncharted"
-category: Category {#588 ▼
-id: null
-name: Category {#685 ▼
-id: 2
-name: "Games"
-subcategorues: PersistentCollection {#686 ▶}
}
-subcategorues: ArrayCollection {#660 ▶}
}
}
``` | 2016/01/27 | [
"https://Stackoverflow.com/questions/35034391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4506747/"
] | Your `CategoryType` is not correctly mapped compared to your `Category` entity. Actually, in your case, you don't need to have a sub-form `CategoryType` with a `name` field, since you have a `category` field in `SubCategory` which is a relationship towards `Category`.
Just replace:
```
->add('category', new CategoryType(), [
'label' => false
])
```
by:
```
->add('category', 'entity', [
'class' => 'AppBundle\Entity\Category',
'choice_label' => 'name'
]);
``` | Could your try smth like this (for `Category` entity class):
```
public function addSubcategorue(\AppBundle\Entity\Category $subcategorues)
{
if ($this->subcategorues->contains($subcategorues)) {
$this->subcategorues->add($subcategorues);
$subcategorues->setCategory($this);
}
return $this;
}
``` |
9,739,888 | If we start to use 2 servers instead of one, with load balancing, is there a way to store sessions in memory, so we wouldn't need to change 50 webconfigs to set sessions are stored in database?
Obviously, 2 servers would be there if one fails, so storing sessions in memory would back things to beginning.
Thanks. | 2012/03/16 | [
"https://Stackoverflow.com/questions/9739888",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1010078/"
] | One option is to use a load balancer that supports "sticky sessions". What that means is that the load balancer will always forward requests with the same session id to the same server, so no session sharing is required. | If I understand your question correctly, then the answer is "No". If you are using the default inprocess session provider, then when you switch to using 2 machines, you will need to switch the session provider to some out of process (ie Sql Session provider or Memcached) session providers so that both machines can access the same session source. This means you will need to modify all the web.conf |
4,086,372 | The problem is as follows:
>
> Let the function $f(x)=\sec \frac{\pi}{3}-\csc^2 4x$.
> Find the complement of the domain of the function $f(x)$.
>
>
>
The given choices in my book are as follows:
$\begin{array}{ll}
1.&\left\{(2n+1)\frac{\pi}{16}/n\in \mathbb{Z}\right\}\\
2.&\left\{(2n+1)\frac{\pi}{4}/n\in \mathbb{Z}\right\}\\
3.&\left\{(4n+1)\frac{\pi}{2}/n\in \mathbb{Z}\right\}\\
4.&\left\{\frac{n\pi}{4}/n\in \mathbb{Z}\right\}\\
\end{array}$
Gee in this question I really don't know where to begin with. My workbook doesn't explain well this topic. Could someone help me how to solve this without much fuss?.
I wish I could offer more than just that. But I'm lost at the very beginning.
The only thing which I do recally is that secant can take all reals minus each $\frac{(2n-1)\pi}{2}$. Thus I believe I have discount these but I don't know how to do that.
All and all I don't know how to put these ideas together in order to solve this question. Can someone **guide me on what should be done first?** Please try to explain each line so I can understand what's happening. | 2021/04/02 | [
"https://math.stackexchange.com/questions/4086372",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/356728/"
] | First, recall that the domain is the set of $x$ values that you're allowed to plug in - that give you a well defined expression.The term $\sec\left(\frac{\pi}{3}\right)$ is a constant, and so it will not affect the domain; no matter what value of $x$ you plug in, that term will be the same, so it won't have any effect on the domain. This means that what you're really looking for is the domain of $-\csc^2(4x)$. Now, recall that $\csc(x) = \frac{1}{\sin(x)}$, so
$$-\csc^2(4x) = \frac{-1}{\sin^2(4x)}$$
This is the quotient of two things. The quotient of two things is only undefined when the denominator is $0$. This means that $x$ is not in the domain if and only if $\sin^2(4x) = 0$. Now, solve that equation, and the set of $x$ that you get will be the $x$ that are not in the domain, which should allow you to identify the correct option. | The complement of the domain is precisely the set where the given expression is not well defined.
To find out such set, observe that
\begin{align\*}
\csc^{2}(4x) = \frac{1}{\sin^{2}(4x)}
\end{align\*}
where the denominator cannot be zero. This means that we have to exclude the values of $x$ such that
\begin{align\*}
\sin^{2}(4x) = 0 & \Longleftrightarrow \sin(4x) = 0\\\\
& \Longleftrightarrow 4x = k\pi\\\\
& \Longleftrightarrow x = \frac{k\pi}{4}
\end{align\*}
where $k\in\mathbb{Z}$. Based on the given options, we deduce the right answer is given by the number (4).
Hopefully this helps! |
4,086,372 | The problem is as follows:
>
> Let the function $f(x)=\sec \frac{\pi}{3}-\csc^2 4x$.
> Find the complement of the domain of the function $f(x)$.
>
>
>
The given choices in my book are as follows:
$\begin{array}{ll}
1.&\left\{(2n+1)\frac{\pi}{16}/n\in \mathbb{Z}\right\}\\
2.&\left\{(2n+1)\frac{\pi}{4}/n\in \mathbb{Z}\right\}\\
3.&\left\{(4n+1)\frac{\pi}{2}/n\in \mathbb{Z}\right\}\\
4.&\left\{\frac{n\pi}{4}/n\in \mathbb{Z}\right\}\\
\end{array}$
Gee in this question I really don't know where to begin with. My workbook doesn't explain well this topic. Could someone help me how to solve this without much fuss?.
I wish I could offer more than just that. But I'm lost at the very beginning.
The only thing which I do recally is that secant can take all reals minus each $\frac{(2n-1)\pi}{2}$. Thus I believe I have discount these but I don't know how to do that.
All and all I don't know how to put these ideas together in order to solve this question. Can someone **guide me on what should be done first?** Please try to explain each line so I can understand what's happening. | 2021/04/02 | [
"https://math.stackexchange.com/questions/4086372",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/356728/"
] | First, recall that the domain is the set of $x$ values that you're allowed to plug in - that give you a well defined expression.The term $\sec\left(\frac{\pi}{3}\right)$ is a constant, and so it will not affect the domain; no matter what value of $x$ you plug in, that term will be the same, so it won't have any effect on the domain. This means that what you're really looking for is the domain of $-\csc^2(4x)$. Now, recall that $\csc(x) = \frac{1}{\sin(x)}$, so
$$-\csc^2(4x) = \frac{-1}{\sin^2(4x)}$$
This is the quotient of two things. The quotient of two things is only undefined when the denominator is $0$. This means that $x$ is not in the domain if and only if $\sin^2(4x) = 0$. Now, solve that equation, and the set of $x$ that you get will be the $x$ that are not in the domain, which should allow you to identify the correct option. | The input to secant is $\frac{\pi}3$, it is not a function of $x$.
We just have to handle $\csc^2 4x$ and it is not well defined when
$$4x = n\pi.$$ |
4,086,372 | The problem is as follows:
>
> Let the function $f(x)=\sec \frac{\pi}{3}-\csc^2 4x$.
> Find the complement of the domain of the function $f(x)$.
>
>
>
The given choices in my book are as follows:
$\begin{array}{ll}
1.&\left\{(2n+1)\frac{\pi}{16}/n\in \mathbb{Z}\right\}\\
2.&\left\{(2n+1)\frac{\pi}{4}/n\in \mathbb{Z}\right\}\\
3.&\left\{(4n+1)\frac{\pi}{2}/n\in \mathbb{Z}\right\}\\
4.&\left\{\frac{n\pi}{4}/n\in \mathbb{Z}\right\}\\
\end{array}$
Gee in this question I really don't know where to begin with. My workbook doesn't explain well this topic. Could someone help me how to solve this without much fuss?.
I wish I could offer more than just that. But I'm lost at the very beginning.
The only thing which I do recally is that secant can take all reals minus each $\frac{(2n-1)\pi}{2}$. Thus I believe I have discount these but I don't know how to do that.
All and all I don't know how to put these ideas together in order to solve this question. Can someone **guide me on what should be done first?** Please try to explain each line so I can understand what's happening. | 2021/04/02 | [
"https://math.stackexchange.com/questions/4086372",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/356728/"
] | First, recall that the domain is the set of $x$ values that you're allowed to plug in - that give you a well defined expression.The term $\sec\left(\frac{\pi}{3}\right)$ is a constant, and so it will not affect the domain; no matter what value of $x$ you plug in, that term will be the same, so it won't have any effect on the domain. This means that what you're really looking for is the domain of $-\csc^2(4x)$. Now, recall that $\csc(x) = \frac{1}{\sin(x)}$, so
$$-\csc^2(4x) = \frac{-1}{\sin^2(4x)}$$
This is the quotient of two things. The quotient of two things is only undefined when the denominator is $0$. This means that $x$ is not in the domain if and only if $\sin^2(4x) = 0$. Now, solve that equation, and the set of $x$ that you get will be the $x$ that are not in the domain, which should allow you to identify the correct option. | $\sec(\frac\pi3)$ is constant.
$\csc(y)$ and $\csc^2(y)$ are defined for all $y\ne n\pi$.
Here letting $y = 4x \ne n\pi\Rightarrow x\ne\frac{n\pi}{4}$
So the complement of the domain is $\{\frac{n\pi}{4} |n \in \Bbb Z \}$ |
30,696,076 | How to create a c code that receive int parameter n and return the value of this mathematical equation
>
> *f*(n) = 3 \* *f*(*n* - 1) + 4, where *f*(0) = 1
>
>
>
each time the program receive n , the program should start from the 0 to n which means in code (for loop) .
the problem here that i can't translate this into code , I'm stuck at the f(n-1) part , how can i make this work in c ?
Note. this code should be build only in basic C (no more the loops , no functions , in the void main etc) . | 2015/06/07 | [
"https://Stackoverflow.com/questions/30696076",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4425292/"
] | It's called recursion, and you have a base case where `f(0) == 1`, so just check `if (n == 0)` and return `1` or recurse
```
int f(int n)
{
if (n == 0)
return 1;
return 3 * f(n - 1) + 4;
}
```
An iterative solution is quite simple too, for example if `f(5)`
```
#include <stdio.h>
int
main(void)
{
int f;
int n;
f = 1;
for (n = 1 ; n <= 5 ; ++n)
f = 3 * f + 4;
printf("%d\n", f);
return 0;
}
``` | Best will be to use recursion . Learn it online .
Its is very powerful method for solving problems. Classical one is to calculate factorials. Its is used widely in many algorithms like tree/graph traversal etc.
Recursion in computer science is a method where the solution to a problem depends on solutions to smaller instances of the same problem.
Here you break you problem of size `n` into 3 instance of sub problem of size `n-1` + a problem of constant size at each such step.
Recursion will stop at base case i.e. the trivial case here for n=0 the function or the smallest sub problem has value 1. |
30,696,076 | How to create a c code that receive int parameter n and return the value of this mathematical equation
>
> *f*(n) = 3 \* *f*(*n* - 1) + 4, where *f*(0) = 1
>
>
>
each time the program receive n , the program should start from the 0 to n which means in code (for loop) .
the problem here that i can't translate this into code , I'm stuck at the f(n-1) part , how can i make this work in c ?
Note. this code should be build only in basic C (no more the loops , no functions , in the void main etc) . | 2015/06/07 | [
"https://Stackoverflow.com/questions/30696076",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4425292/"
] | It's called recursion, and you have a base case where `f(0) == 1`, so just check `if (n == 0)` and return `1` or recurse
```
int f(int n)
{
if (n == 0)
return 1;
return 3 * f(n - 1) + 4;
}
```
An iterative solution is quite simple too, for example if `f(5)`
```
#include <stdio.h>
int
main(void)
{
int f;
int n;
f = 1;
for (n = 1 ; n <= 5 ; ++n)
f = 3 * f + 4;
printf("%d\n", f);
return 0;
}
``` | A LRE (linear recurrence equation) can be converted into a matrix multiply. In this case:
```
F(0) = | 1 | (the current LRE value)
| 1 | (this is just copied, used for the + 4)
M = | 3 4 | (calculates LRE to new 1st number)
| 0 1 | (copies previous 2nd number to new 2nd number (the 1))
F(n) = M F(n-1) = matrixpower(M, n) F(0)
```
You can raise a matrix to the power n by using repeated squaring, sometimes called binary exponentiation. Example code for integer:
```
r = 1; /* result */
s = m; /* s = squares of integer m */
while(n){ /* while exponent != 0 */
if(n&1) /* if bit of exponent set */
r *= s; /* multiply by s */
s *= s; /* s = s squared */
n >>= 1; /* test next exponent bit */
}
```
For an unsigned 64 bit integer, the max value for n is 40, so the maximum number of loops would be 6, since 2^6 > 40.
If this expression was calculating f(n) = 3 f(n-1) + 4 modulo some prime number (like 1,000,000,007) for very large n, then the matrix method would be useful, but in this case, with a max value of n = 40, recursion or iteration is good enough and simpler. |
30,696,076 | How to create a c code that receive int parameter n and return the value of this mathematical equation
>
> *f*(n) = 3 \* *f*(*n* - 1) + 4, where *f*(0) = 1
>
>
>
each time the program receive n , the program should start from the 0 to n which means in code (for loop) .
the problem here that i can't translate this into code , I'm stuck at the f(n-1) part , how can i make this work in c ?
Note. this code should be build only in basic C (no more the loops , no functions , in the void main etc) . | 2015/06/07 | [
"https://Stackoverflow.com/questions/30696076",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4425292/"
] | A LRE (linear recurrence equation) can be converted into a matrix multiply. In this case:
```
F(0) = | 1 | (the current LRE value)
| 1 | (this is just copied, used for the + 4)
M = | 3 4 | (calculates LRE to new 1st number)
| 0 1 | (copies previous 2nd number to new 2nd number (the 1))
F(n) = M F(n-1) = matrixpower(M, n) F(0)
```
You can raise a matrix to the power n by using repeated squaring, sometimes called binary exponentiation. Example code for integer:
```
r = 1; /* result */
s = m; /* s = squares of integer m */
while(n){ /* while exponent != 0 */
if(n&1) /* if bit of exponent set */
r *= s; /* multiply by s */
s *= s; /* s = s squared */
n >>= 1; /* test next exponent bit */
}
```
For an unsigned 64 bit integer, the max value for n is 40, so the maximum number of loops would be 6, since 2^6 > 40.
If this expression was calculating f(n) = 3 f(n-1) + 4 modulo some prime number (like 1,000,000,007) for very large n, then the matrix method would be useful, but in this case, with a max value of n = 40, recursion or iteration is good enough and simpler. | Best will be to use recursion . Learn it online .
Its is very powerful method for solving problems. Classical one is to calculate factorials. Its is used widely in many algorithms like tree/graph traversal etc.
Recursion in computer science is a method where the solution to a problem depends on solutions to smaller instances of the same problem.
Here you break you problem of size `n` into 3 instance of sub problem of size `n-1` + a problem of constant size at each such step.
Recursion will stop at base case i.e. the trivial case here for n=0 the function or the smallest sub problem has value 1. |
68,531,464 | I have one state
```
const [data, setData] = useState("");
```
And 2 useEffects that call in parallel when component renders
```
useEffect(() => {
socket.on("message",()=>{
console.log(data)
})
}, [socket])
useEffect(() => {
const res = getDataFromServer()
setData(res.data)
}, [isLoading])
```
2nd useEffect get data from server and set state but when socket arrive in first useEffect data is on initial state that is empty. How can I get updated state data in first useEffect when socket arrives. If I set data as dependency to first useEffect then socket event is reinitialized and callback is calling multiple times. | 2021/07/26 | [
"https://Stackoverflow.com/questions/68531464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3338287/"
] | You can return a function in useEffect to clean unnecessary handlers / event listeners.
[Effects with Cleanup - React Docs](https://reactjs.org/docs/hooks-effect.html#example-using-hooks-1)
In this function you can use the [offAny method of socket.io client](https://socket.io/docs/v3/client-api/index.html#socket-offAny-listener) to remove previous listener.
```js
useEffect(() => {
const currentListener = socket.on("message",()=>{
console.log(data)
});
return () => {
socket.offAny(currentListener);
};
}, [socket, data]);
``` | This might help
```
React.useEffect(() => {
// This effect only executes on the initial render so that we aren't setting up the socket repeatedly.
socket.on("message",()=>{
console.log(data);
})
return () => {
socket.off('message',() => {});
}
}, []);
``` |
4,656 | Ich habe eine Kopie eines Manuskripts aus dem 18 Jahrhundert. Es handelt sich um [die Geburtstagskantate für Prinzessin Ulrike](http://de.wikipedia.org/wiki/Ulrike_Sophie_zu_Mecklenburg#cite_note-2) einschließlich des Textes.

Die Kopie ist nicht besonders gut. Die Handschrift ist teilweise schwer zu lesen. Einige Buchstaben kann ich [hier](http://www.suetterlinschrift.de/Lese/Sutterlin0.htm) auch nicht finden. Was ist eine gute Möglichkeit, diesen alten deutschen Text zu entziffern?
* [Seite 1](https://i.stack.imgur.com/hYDnz.png)
* [Seite 2](https://i.stack.imgur.com/D1Ecn.png) | 2012/06/01 | [
"https://german.stackexchange.com/questions/4656",
"https://german.stackexchange.com",
"https://german.stackexchange.com/users/514/"
] | Es handelt sich um eine bereits im 18. Jahrhundert gebräuchliche [Kurrentschrift](http://de.wikipedia.org/wiki/Deutsche_Kurrentschrift). Im verlinkten Wikipedia-Artikel findet sich auch eine Alphabettafel, mit deren Hilfe man einzelne Buchstaben zuordnen kann.
Von den ersten beiden Zeilen kann ich folgendes entziffern:
>
> So schön sang in der ... (Schäfer?) Welt der redliche ... (Liron?), als Luna durch die Sternen irrte, die Nymphen hörten den Gesang
>
>
>
Hier noch drei weitere Verweise mit Beispielen und Schreib- und Leseübungen, die vielleicht von Interesse sind:
* [Kurrent](http://www.kurrent.de/index.htm)
* [Freunde der deutschen Kurrentschrift](http://www.deutsche-kurrentschrift.de/)
* [Geschichte Online](http://gonline.univie.ac.at/htdocs/site/browse.php?a=2255&arttyp=k) | Zusätzlich zu Takkats Antwort empfehle ich, Stück für Stück vorzugehen, und den bisher entzifferten Inhalt zu beachten. Schreib Dir das, was Du erkennen kannst, als Lückentext auf. Wenn Du in einem Satz ein oder zwei Wörter nicht lesen kannst, überlege, was grammatikalisch und thematisch passen könnte. Wenn Du ein Zeilenende entziffert hast, reimt sich das zweite vielleicht darauf. |
4,656 | Ich habe eine Kopie eines Manuskripts aus dem 18 Jahrhundert. Es handelt sich um [die Geburtstagskantate für Prinzessin Ulrike](http://de.wikipedia.org/wiki/Ulrike_Sophie_zu_Mecklenburg#cite_note-2) einschließlich des Textes.

Die Kopie ist nicht besonders gut. Die Handschrift ist teilweise schwer zu lesen. Einige Buchstaben kann ich [hier](http://www.suetterlinschrift.de/Lese/Sutterlin0.htm) auch nicht finden. Was ist eine gute Möglichkeit, diesen alten deutschen Text zu entziffern?
* [Seite 1](https://i.stack.imgur.com/hYDnz.png)
* [Seite 2](https://i.stack.imgur.com/D1Ecn.png) | 2012/06/01 | [
"https://german.stackexchange.com/questions/4656",
"https://german.stackexchange.com",
"https://german.stackexchange.com/users/514/"
] | Es handelt sich um eine bereits im 18. Jahrhundert gebräuchliche [Kurrentschrift](http://de.wikipedia.org/wiki/Deutsche_Kurrentschrift). Im verlinkten Wikipedia-Artikel findet sich auch eine Alphabettafel, mit deren Hilfe man einzelne Buchstaben zuordnen kann.
Von den ersten beiden Zeilen kann ich folgendes entziffern:
>
> So schön sang in der ... (Schäfer?) Welt der redliche ... (Liron?), als Luna durch die Sternen irrte, die Nymphen hörten den Gesang
>
>
>
Hier noch drei weitere Verweise mit Beispielen und Schreib- und Leseübungen, die vielleicht von Interesse sind:
* [Kurrent](http://www.kurrent.de/index.htm)
* [Freunde der deutschen Kurrentschrift](http://www.deutsche-kurrentschrift.de/)
* [Geschichte Online](http://gonline.univie.ac.at/htdocs/site/browse.php?a=2255&arttyp=k) | **Seite 1:**
So schön, sang in der Schäfer Welt der redliche Ei=
ron, als Luna durch die Sternen irrte, die Nymphen hörten den Ge=
sang, der durch den Wald bis zum Olimpus drang. Voll Zuversicht
daß frommer Schäfer unentweyhte Pflicht, die Götter die den Hain be=
wohnen mit Beyfall segnen und belohnen, sang er, es neigten sich die
Wipfel hoher Bäume, der Schäfer Wunsch das Glück der guten
Träume der Luna und den Göttern vor. Die Götter
**Seite 2:**
segneten den redlichen Eiron, wer segnet uns, wenn wir so redlich
flehn (?) ! Zwar Luna, steigt aus unsren nächtlich frohen Chor kein (?) Lied zu
dir empor. Die Vorsicht bester Menschen Güter
dir Herr des Tages und der Nacht, dir eintziger Geber al - ler Güter, dir sey Danck und Ge=
beth - gebracht, dir eintziger Geber al - ler Güter, dir sey Danck und Gebet gebracht.
Geselle du der Mahanaim Wachen Ulrikens sanften Schlummer bey, laß morgen
sie vergnügt erwachen, daß ihr Geburtstag uns ein Fest der Freude sey.
*Bemerkung:*
Die Worte "Ulrikens" und "Geburtstag" scheinen mit einer anderen Feder als der Rest des Textes geschrieben zu sein - vielleicht wurden sie nachträglich an Leerstellen eingefügt. |
4,656 | Ich habe eine Kopie eines Manuskripts aus dem 18 Jahrhundert. Es handelt sich um [die Geburtstagskantate für Prinzessin Ulrike](http://de.wikipedia.org/wiki/Ulrike_Sophie_zu_Mecklenburg#cite_note-2) einschließlich des Textes.

Die Kopie ist nicht besonders gut. Die Handschrift ist teilweise schwer zu lesen. Einige Buchstaben kann ich [hier](http://www.suetterlinschrift.de/Lese/Sutterlin0.htm) auch nicht finden. Was ist eine gute Möglichkeit, diesen alten deutschen Text zu entziffern?
* [Seite 1](https://i.stack.imgur.com/hYDnz.png)
* [Seite 2](https://i.stack.imgur.com/D1Ecn.png) | 2012/06/01 | [
"https://german.stackexchange.com/questions/4656",
"https://german.stackexchange.com",
"https://german.stackexchange.com/users/514/"
] | Zusätzlich zu Takkats Antwort empfehle ich, Stück für Stück vorzugehen, und den bisher entzifferten Inhalt zu beachten. Schreib Dir das, was Du erkennen kannst, als Lückentext auf. Wenn Du in einem Satz ein oder zwei Wörter nicht lesen kannst, überlege, was grammatikalisch und thematisch passen könnte. Wenn Du ein Zeilenende entziffert hast, reimt sich das zweite vielleicht darauf. | **Seite 1:**
So schön, sang in der Schäfer Welt der redliche Ei=
ron, als Luna durch die Sternen irrte, die Nymphen hörten den Ge=
sang, der durch den Wald bis zum Olimpus drang. Voll Zuversicht
daß frommer Schäfer unentweyhte Pflicht, die Götter die den Hain be=
wohnen mit Beyfall segnen und belohnen, sang er, es neigten sich die
Wipfel hoher Bäume, der Schäfer Wunsch das Glück der guten
Träume der Luna und den Göttern vor. Die Götter
**Seite 2:**
segneten den redlichen Eiron, wer segnet uns, wenn wir so redlich
flehn (?) ! Zwar Luna, steigt aus unsren nächtlich frohen Chor kein (?) Lied zu
dir empor. Die Vorsicht bester Menschen Güter
dir Herr des Tages und der Nacht, dir eintziger Geber al - ler Güter, dir sey Danck und Ge=
beth - gebracht, dir eintziger Geber al - ler Güter, dir sey Danck und Gebet gebracht.
Geselle du der Mahanaim Wachen Ulrikens sanften Schlummer bey, laß morgen
sie vergnügt erwachen, daß ihr Geburtstag uns ein Fest der Freude sey.
*Bemerkung:*
Die Worte "Ulrikens" und "Geburtstag" scheinen mit einer anderen Feder als der Rest des Textes geschrieben zu sein - vielleicht wurden sie nachträglich an Leerstellen eingefügt. |
18,136,629 | I can run `SET` statements to assign variables and use "transaction" to maintain it in the mySQL session, but when I include the function `DATE_FORMAT` like this:
```
cursor.execute("SET @dowToday:=CAST( DATE_FORMAT( NOW(), '%w' ) AS UNSIGNED);")
```
Django complains that
>
> not enough arguments for format string in /usr/lib/pymodules/python2.6/MySQLdb/cursors.py in execute, line 151
>
>
>
It doesn't help to remove the CAST or to play with or escape the quotes.
Thoughts? | 2013/08/08 | [
"https://Stackoverflow.com/questions/18136629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1261511/"
] | My guess is that the issue is with the percent sign (`%`) in the query text. (Isn't that a bind variable placeholder in Django?) e.g. if we were going to use a bind variable, wouldn't that look something like this?
```
SELECT 'foo' FROM DUAL WHERE 'a' = %(varname)s ;
```
I think maybe Django is scanning your SQL text and encountering `%w` and expecting that to be a bind variable. Either that, or it's running an `sprintf` style function, and encountering the `%w` and expecting to replace that placeholder with an argument value.
(I haven't tested; so this is just an idea, just a guess.)
As a guess to a workaround, maybe you double up the percent signs, the same we get % literals through an sprintf:
```
query("SELECT ... ,'%%w') ...");
```
If that doesn't work, then maybe it's a backslash character, the same we escape characters in a regular expression:
```
query("SELECT ... ,'\%w') ...");
```
(Or, you might need to double up the backslashes. These are just guesses based on conventions used by other software.) | Are you sure the error is produced by *that* call?
---
Looking at the code of `cursor.py` on my system, that leads to:
```
def execute(self, query, args=None):
# ...
if isinstance(query, unicode):
query = query.encode(charset)
if args is not None:
query = query % db.literal(args) # Line 151
```
According to that, this exception could only be thrown if `args` is not `None` -- which seems impossible considering the call:
```
cursor.execute("SET @dowToday:=CAST( DATE_FORMAT( NOW(), '%w' ) AS UNSIGNED);")
``` |
18,136,629 | I can run `SET` statements to assign variables and use "transaction" to maintain it in the mySQL session, but when I include the function `DATE_FORMAT` like this:
```
cursor.execute("SET @dowToday:=CAST( DATE_FORMAT( NOW(), '%w' ) AS UNSIGNED);")
```
Django complains that
>
> not enough arguments for format string in /usr/lib/pymodules/python2.6/MySQLdb/cursors.py in execute, line 151
>
>
>
It doesn't help to remove the CAST or to play with or escape the quotes.
Thoughts? | 2013/08/08 | [
"https://Stackoverflow.com/questions/18136629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1261511/"
] | I totally missed the point in my previous answer. This is a Django cursor. Not a "standard Python" one.
According to the doc:
<https://docs.djangoproject.com/en/dev/topics/db/sql/>
>
> Note that if you want to include literal percent signs in the query,
> you have to double them in the case you are passing parameters:
>
>
>
> ```
> cursor.execute("SELECT foo FROM bar WHERE baz = '30%%' and id = %s", [self.id])
>
> ```
>
>
I assume if this does not work, your could fallback to some simple-and-stupid trick:
```
cursor.execute("SET @dowToday:=CAST( DATE_FORMAT( NOW(), '%sw' ) AS UNSIGNED);", ['%'])
```
The `%s` will be replaced by the `%` passed as an argument... | Are you sure the error is produced by *that* call?
---
Looking at the code of `cursor.py` on my system, that leads to:
```
def execute(self, query, args=None):
# ...
if isinstance(query, unicode):
query = query.encode(charset)
if args is not None:
query = query % db.literal(args) # Line 151
```
According to that, this exception could only be thrown if `args` is not `None` -- which seems impossible considering the call:
```
cursor.execute("SET @dowToday:=CAST( DATE_FORMAT( NOW(), '%w' ) AS UNSIGNED);")
``` |
3,875,739 | I have a ScheduledThreadPoolExecutor that seems to be eating Exceptions. I want my executor service to notify me if a submitted Runnable throws an exception.
For example, I'd like the code below to at the very least print the IndexArrayOutOfBoundsException's stackTrace
```
threadPool.scheduleAtFixedRate(
new Runnable() {
public void run() {
int[] array = new array[0];
array[42] = 5;
}
},
1000,
1500L,
TimeUnit.MILLISECONDS);
```
As a side question. Is there a way to write a general try catch block for a ScheduledThreadPoolExecutor?
//////////END OF ORIGINAL QUESTION //////////////
As suggested the following Decorator works well.
```
public class CatcherTask implements Runnable{
Runnable runMe;
public CatcherTask(Runnable runMe) {
this.runMe = runMe;
}
public void run() {
try {
runMe.run();
} catch (Exception ex){
ex.printStackTrace();
}
}
}
``` | 2010/10/06 | [
"https://Stackoverflow.com/questions/3875739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/460790/"
] | **Warning**: This method is not applicable to **scheduled** thread pool executors. This answer has been undeleted for its relevance to other thread pool executors. See [Willi's answer](https://stackoverflow.com/questions/3875739/exception-handling-in-threadpools/3875968#3875968).
Override the `ThreadFactory` to give Threads an UncaughtExceptionHandler:
```
ThreadPoolExecutor exec = new ThreadPoolExecutor...;
exec.setThreadFactory(new ExceptionCatchingThreadFactory(exec.getThreadFactory()));
//go on to submit tasks...
private static class ExceptionCatchingThreadFactory implements ThreadFactory {
private final ThreadFactory delegate;
private ExceptionCatchingThreadFactory(ThreadFactory delegate) {
this.delegate = delegate;
}
public Thread newThread(final Runnable r) {
Thread t = delegate.newThread(r);
t.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
e.printStackTrace(); //replace with your handling logic.
}
});
return t;
}
}
``` | You could also use a `ThreadPoolTaskScheduler` from the [Spring Framework](http://static.springsource.org/spring/docs/current/spring-framework-reference/html/scheduling.html), which exposes a method to set an error handler and does all the wrapping for you. The default behavior depends on the type of task:
*If the provided `ErrorHandler` is not null, it will be used. Otherwise, repeating tasks will have errors suppressed by default whereas one-shot tasks will have errors propagated by default since those errors may be expected through the returned `Future`. In both cases, the errors will be logged.*
If you only want to use the wrapping part and not the `TaskScheduler` you can use
```
TaskUtils.decorateTaskWithErrorHandler(task, errorHandler, isRepeatingTask)
```
which the `TaskScheduler` uses internally. |
3,875,739 | I have a ScheduledThreadPoolExecutor that seems to be eating Exceptions. I want my executor service to notify me if a submitted Runnable throws an exception.
For example, I'd like the code below to at the very least print the IndexArrayOutOfBoundsException's stackTrace
```
threadPool.scheduleAtFixedRate(
new Runnable() {
public void run() {
int[] array = new array[0];
array[42] = 5;
}
},
1000,
1500L,
TimeUnit.MILLISECONDS);
```
As a side question. Is there a way to write a general try catch block for a ScheduledThreadPoolExecutor?
//////////END OF ORIGINAL QUESTION //////////////
As suggested the following Decorator works well.
```
public class CatcherTask implements Runnable{
Runnable runMe;
public CatcherTask(Runnable runMe) {
this.runMe = runMe;
}
public void run() {
try {
runMe.run();
} catch (Exception ex){
ex.printStackTrace();
}
}
}
``` | 2010/10/06 | [
"https://Stackoverflow.com/questions/3875739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/460790/"
] | You can use the `get()` method from the `Future` you're getting by calling `scheduleAtFixedRate()`. It will throw an `ExecutionException` if an exeception occurred during the thread execution. | You can subclass ScheduledThreadPoolExecutor and override the [afterExecute](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadPoolExecutor.html#afterExecute(java.lang.Runnable,%20java.lang.Throwable)) method to handle exceptions and errors for any kind of Runnable that you submit. |
3,875,739 | I have a ScheduledThreadPoolExecutor that seems to be eating Exceptions. I want my executor service to notify me if a submitted Runnable throws an exception.
For example, I'd like the code below to at the very least print the IndexArrayOutOfBoundsException's stackTrace
```
threadPool.scheduleAtFixedRate(
new Runnable() {
public void run() {
int[] array = new array[0];
array[42] = 5;
}
},
1000,
1500L,
TimeUnit.MILLISECONDS);
```
As a side question. Is there a way to write a general try catch block for a ScheduledThreadPoolExecutor?
//////////END OF ORIGINAL QUESTION //////////////
As suggested the following Decorator works well.
```
public class CatcherTask implements Runnable{
Runnable runMe;
public CatcherTask(Runnable runMe) {
this.runMe = runMe;
}
public void run() {
try {
runMe.run();
} catch (Exception ex){
ex.printStackTrace();
}
}
}
``` | 2010/10/06 | [
"https://Stackoverflow.com/questions/3875739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/460790/"
] | I wrote a small [post](http://www.cosmocode.de/en/blog/schoenborn/2009-12/17-uncaught-exceptions-in-scheduled-tasks) about this problem a while ago. You have two options:
1. Use the [solution](https://stackoverflow.com/questions/3875739/exception-handling-in-threadpools/3875807#3875807) provided by Colin Herbert or
2. use a modified version of Mark Peters [solution](https://stackoverflow.com/questions/3875739/exception-handling-in-threadpools/3875784#3875784) but instead of assigning a `UncaughtExceptionHandler` you wrap each submitted runnable into a runnable of your own which executes (calls `run`) the real runnable inside a try-catch-block.
**EDIT**
As pointed out by Mark, it's important to wrap the `Runnable` passed to `ScheduledExecutorService` instead of the one passed to the `ThreadFactory`. | You can use the `get()` method from the `Future` you're getting by calling `scheduleAtFixedRate()`. It will throw an `ExecutionException` if an exeception occurred during the thread execution. |
3,875,739 | I have a ScheduledThreadPoolExecutor that seems to be eating Exceptions. I want my executor service to notify me if a submitted Runnable throws an exception.
For example, I'd like the code below to at the very least print the IndexArrayOutOfBoundsException's stackTrace
```
threadPool.scheduleAtFixedRate(
new Runnable() {
public void run() {
int[] array = new array[0];
array[42] = 5;
}
},
1000,
1500L,
TimeUnit.MILLISECONDS);
```
As a side question. Is there a way to write a general try catch block for a ScheduledThreadPoolExecutor?
//////////END OF ORIGINAL QUESTION //////////////
As suggested the following Decorator works well.
```
public class CatcherTask implements Runnable{
Runnable runMe;
public CatcherTask(Runnable runMe) {
this.runMe = runMe;
}
public void run() {
try {
runMe.run();
} catch (Exception ex){
ex.printStackTrace();
}
}
}
``` | 2010/10/06 | [
"https://Stackoverflow.com/questions/3875739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/460790/"
] | You can subclass ScheduledThreadPoolExecutor and override the [afterExecute](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadPoolExecutor.html#afterExecute(java.lang.Runnable,%20java.lang.Throwable)) method to handle exceptions and errors for any kind of Runnable that you submit. | Consider adding a static event in your *ScheduledThreadPoolExecutor* class that any of your tasks can call if an exception is thrown. That way, you can leverage that event to capture and handle the exceptions that occur within your threads. |
3,875,739 | I have a ScheduledThreadPoolExecutor that seems to be eating Exceptions. I want my executor service to notify me if a submitted Runnable throws an exception.
For example, I'd like the code below to at the very least print the IndexArrayOutOfBoundsException's stackTrace
```
threadPool.scheduleAtFixedRate(
new Runnable() {
public void run() {
int[] array = new array[0];
array[42] = 5;
}
},
1000,
1500L,
TimeUnit.MILLISECONDS);
```
As a side question. Is there a way to write a general try catch block for a ScheduledThreadPoolExecutor?
//////////END OF ORIGINAL QUESTION //////////////
As suggested the following Decorator works well.
```
public class CatcherTask implements Runnable{
Runnable runMe;
public CatcherTask(Runnable runMe) {
this.runMe = runMe;
}
public void run() {
try {
runMe.run();
} catch (Exception ex){
ex.printStackTrace();
}
}
}
``` | 2010/10/06 | [
"https://Stackoverflow.com/questions/3875739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/460790/"
] | You can use the `get()` method from the `Future` you're getting by calling `scheduleAtFixedRate()`. It will throw an `ExecutionException` if an exeception occurred during the thread execution. | Consider adding a static event in your *ScheduledThreadPoolExecutor* class that any of your tasks can call if an exception is thrown. That way, you can leverage that event to capture and handle the exceptions that occur within your threads. |
3,875,739 | I have a ScheduledThreadPoolExecutor that seems to be eating Exceptions. I want my executor service to notify me if a submitted Runnable throws an exception.
For example, I'd like the code below to at the very least print the IndexArrayOutOfBoundsException's stackTrace
```
threadPool.scheduleAtFixedRate(
new Runnable() {
public void run() {
int[] array = new array[0];
array[42] = 5;
}
},
1000,
1500L,
TimeUnit.MILLISECONDS);
```
As a side question. Is there a way to write a general try catch block for a ScheduledThreadPoolExecutor?
//////////END OF ORIGINAL QUESTION //////////////
As suggested the following Decorator works well.
```
public class CatcherTask implements Runnable{
Runnable runMe;
public CatcherTask(Runnable runMe) {
this.runMe = runMe;
}
public void run() {
try {
runMe.run();
} catch (Exception ex){
ex.printStackTrace();
}
}
}
``` | 2010/10/06 | [
"https://Stackoverflow.com/questions/3875739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/460790/"
] | You can use the `get()` method from the `Future` you're getting by calling `scheduleAtFixedRate()`. It will throw an `ExecutionException` if an exeception occurred during the thread execution. | You could also use a `ThreadPoolTaskScheduler` from the [Spring Framework](http://static.springsource.org/spring/docs/current/spring-framework-reference/html/scheduling.html), which exposes a method to set an error handler and does all the wrapping for you. The default behavior depends on the type of task:
*If the provided `ErrorHandler` is not null, it will be used. Otherwise, repeating tasks will have errors suppressed by default whereas one-shot tasks will have errors propagated by default since those errors may be expected through the returned `Future`. In both cases, the errors will be logged.*
If you only want to use the wrapping part and not the `TaskScheduler` you can use
```
TaskUtils.decorateTaskWithErrorHandler(task, errorHandler, isRepeatingTask)
```
which the `TaskScheduler` uses internally. |
3,875,739 | I have a ScheduledThreadPoolExecutor that seems to be eating Exceptions. I want my executor service to notify me if a submitted Runnable throws an exception.
For example, I'd like the code below to at the very least print the IndexArrayOutOfBoundsException's stackTrace
```
threadPool.scheduleAtFixedRate(
new Runnable() {
public void run() {
int[] array = new array[0];
array[42] = 5;
}
},
1000,
1500L,
TimeUnit.MILLISECONDS);
```
As a side question. Is there a way to write a general try catch block for a ScheduledThreadPoolExecutor?
//////////END OF ORIGINAL QUESTION //////////////
As suggested the following Decorator works well.
```
public class CatcherTask implements Runnable{
Runnable runMe;
public CatcherTask(Runnable runMe) {
this.runMe = runMe;
}
public void run() {
try {
runMe.run();
} catch (Exception ex){
ex.printStackTrace();
}
}
}
``` | 2010/10/06 | [
"https://Stackoverflow.com/questions/3875739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/460790/"
] | You could also use a `ThreadPoolTaskScheduler` from the [Spring Framework](http://static.springsource.org/spring/docs/current/spring-framework-reference/html/scheduling.html), which exposes a method to set an error handler and does all the wrapping for you. The default behavior depends on the type of task:
*If the provided `ErrorHandler` is not null, it will be used. Otherwise, repeating tasks will have errors suppressed by default whereas one-shot tasks will have errors propagated by default since those errors may be expected through the returned `Future`. In both cases, the errors will be logged.*
If you only want to use the wrapping part and not the `TaskScheduler` you can use
```
TaskUtils.decorateTaskWithErrorHandler(task, errorHandler, isRepeatingTask)
```
which the `TaskScheduler` uses internally. | Consider adding a static event in your *ScheduledThreadPoolExecutor* class that any of your tasks can call if an exception is thrown. That way, you can leverage that event to capture and handle the exceptions that occur within your threads. |
3,875,739 | I have a ScheduledThreadPoolExecutor that seems to be eating Exceptions. I want my executor service to notify me if a submitted Runnable throws an exception.
For example, I'd like the code below to at the very least print the IndexArrayOutOfBoundsException's stackTrace
```
threadPool.scheduleAtFixedRate(
new Runnable() {
public void run() {
int[] array = new array[0];
array[42] = 5;
}
},
1000,
1500L,
TimeUnit.MILLISECONDS);
```
As a side question. Is there a way to write a general try catch block for a ScheduledThreadPoolExecutor?
//////////END OF ORIGINAL QUESTION //////////////
As suggested the following Decorator works well.
```
public class CatcherTask implements Runnable{
Runnable runMe;
public CatcherTask(Runnable runMe) {
this.runMe = runMe;
}
public void run() {
try {
runMe.run();
} catch (Exception ex){
ex.printStackTrace();
}
}
}
``` | 2010/10/06 | [
"https://Stackoverflow.com/questions/3875739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/460790/"
] | **Warning**: This method is not applicable to **scheduled** thread pool executors. This answer has been undeleted for its relevance to other thread pool executors. See [Willi's answer](https://stackoverflow.com/questions/3875739/exception-handling-in-threadpools/3875968#3875968).
Override the `ThreadFactory` to give Threads an UncaughtExceptionHandler:
```
ThreadPoolExecutor exec = new ThreadPoolExecutor...;
exec.setThreadFactory(new ExceptionCatchingThreadFactory(exec.getThreadFactory()));
//go on to submit tasks...
private static class ExceptionCatchingThreadFactory implements ThreadFactory {
private final ThreadFactory delegate;
private ExceptionCatchingThreadFactory(ThreadFactory delegate) {
this.delegate = delegate;
}
public Thread newThread(final Runnable r) {
Thread t = delegate.newThread(r);
t.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
e.printStackTrace(); //replace with your handling logic.
}
});
return t;
}
}
``` | You can use the `get()` method from the `Future` you're getting by calling `scheduleAtFixedRate()`. It will throw an `ExecutionException` if an exeception occurred during the thread execution. |
3,875,739 | I have a ScheduledThreadPoolExecutor that seems to be eating Exceptions. I want my executor service to notify me if a submitted Runnable throws an exception.
For example, I'd like the code below to at the very least print the IndexArrayOutOfBoundsException's stackTrace
```
threadPool.scheduleAtFixedRate(
new Runnable() {
public void run() {
int[] array = new array[0];
array[42] = 5;
}
},
1000,
1500L,
TimeUnit.MILLISECONDS);
```
As a side question. Is there a way to write a general try catch block for a ScheduledThreadPoolExecutor?
//////////END OF ORIGINAL QUESTION //////////////
As suggested the following Decorator works well.
```
public class CatcherTask implements Runnable{
Runnable runMe;
public CatcherTask(Runnable runMe) {
this.runMe = runMe;
}
public void run() {
try {
runMe.run();
} catch (Exception ex){
ex.printStackTrace();
}
}
}
``` | 2010/10/06 | [
"https://Stackoverflow.com/questions/3875739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/460790/"
] | I wrote a small [post](http://www.cosmocode.de/en/blog/schoenborn/2009-12/17-uncaught-exceptions-in-scheduled-tasks) about this problem a while ago. You have two options:
1. Use the [solution](https://stackoverflow.com/questions/3875739/exception-handling-in-threadpools/3875807#3875807) provided by Colin Herbert or
2. use a modified version of Mark Peters [solution](https://stackoverflow.com/questions/3875739/exception-handling-in-threadpools/3875784#3875784) but instead of assigning a `UncaughtExceptionHandler` you wrap each submitted runnable into a runnable of your own which executes (calls `run`) the real runnable inside a try-catch-block.
**EDIT**
As pointed out by Mark, it's important to wrap the `Runnable` passed to `ScheduledExecutorService` instead of the one passed to the `ThreadFactory`. | **Warning**: This method is not applicable to **scheduled** thread pool executors. This answer has been undeleted for its relevance to other thread pool executors. See [Willi's answer](https://stackoverflow.com/questions/3875739/exception-handling-in-threadpools/3875968#3875968).
Override the `ThreadFactory` to give Threads an UncaughtExceptionHandler:
```
ThreadPoolExecutor exec = new ThreadPoolExecutor...;
exec.setThreadFactory(new ExceptionCatchingThreadFactory(exec.getThreadFactory()));
//go on to submit tasks...
private static class ExceptionCatchingThreadFactory implements ThreadFactory {
private final ThreadFactory delegate;
private ExceptionCatchingThreadFactory(ThreadFactory delegate) {
this.delegate = delegate;
}
public Thread newThread(final Runnable r) {
Thread t = delegate.newThread(r);
t.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
e.printStackTrace(); //replace with your handling logic.
}
});
return t;
}
}
``` |
3,875,739 | I have a ScheduledThreadPoolExecutor that seems to be eating Exceptions. I want my executor service to notify me if a submitted Runnable throws an exception.
For example, I'd like the code below to at the very least print the IndexArrayOutOfBoundsException's stackTrace
```
threadPool.scheduleAtFixedRate(
new Runnable() {
public void run() {
int[] array = new array[0];
array[42] = 5;
}
},
1000,
1500L,
TimeUnit.MILLISECONDS);
```
As a side question. Is there a way to write a general try catch block for a ScheduledThreadPoolExecutor?
//////////END OF ORIGINAL QUESTION //////////////
As suggested the following Decorator works well.
```
public class CatcherTask implements Runnable{
Runnable runMe;
public CatcherTask(Runnable runMe) {
this.runMe = runMe;
}
public void run() {
try {
runMe.run();
} catch (Exception ex){
ex.printStackTrace();
}
}
}
``` | 2010/10/06 | [
"https://Stackoverflow.com/questions/3875739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/460790/"
] | **Warning**: This method is not applicable to **scheduled** thread pool executors. This answer has been undeleted for its relevance to other thread pool executors. See [Willi's answer](https://stackoverflow.com/questions/3875739/exception-handling-in-threadpools/3875968#3875968).
Override the `ThreadFactory` to give Threads an UncaughtExceptionHandler:
```
ThreadPoolExecutor exec = new ThreadPoolExecutor...;
exec.setThreadFactory(new ExceptionCatchingThreadFactory(exec.getThreadFactory()));
//go on to submit tasks...
private static class ExceptionCatchingThreadFactory implements ThreadFactory {
private final ThreadFactory delegate;
private ExceptionCatchingThreadFactory(ThreadFactory delegate) {
this.delegate = delegate;
}
public Thread newThread(final Runnable r) {
Thread t = delegate.newThread(r);
t.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
e.printStackTrace(); //replace with your handling logic.
}
});
return t;
}
}
``` | Consider adding a static event in your *ScheduledThreadPoolExecutor* class that any of your tasks can call if an exception is thrown. That way, you can leverage that event to capture and handle the exceptions that occur within your threads. |
45,295,216 | I have MSVS 2013 and Windows 7.
I'v tried to install Codemaid, but there is a mistake, when I launch a studio:
```
The 'CodemaidPackage' package did not load correctly.
The problem may have been caused by a configuration change or by the
installation of another extension. You can get more information by examining
the file
'C:\Users\xxxx\AppData\Roaming\Microsoft\VisualStudio\12.0\ActivityLog.xml'.
```
There are some errors from Log:
```
<errorinfo>Exception has been thrown by the target of an invocation.</errorinfo>
<description>Package failed to load; error message suppressed by skip flag</description>
```
May somebody give an advice? | 2017/07/25 | [
"https://Stackoverflow.com/questions/45295216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7273346/"
] | Do you know what version of .NET you have installed? Starting with CodeMaid v10.3, .NET 4.6.2 was required.
There's some more information here: <https://github.com/codecadwallader/codemaid/issues/443>
If that doesn't answer your question, opening issues directly on the repository is usually the best way to get help. <https://github.com/codecadwallader/codemaid/issues> | Probably this can help you there is a known bug
<https://github.com/codecadwallader/codemaid/issues/634> |
58,426,254 | I am trying to execute the code from here:
[Change the class from factor to numeric of many columns in a data frame](https://stackoverflow.com/questions/3796266/change-the-class-from-factor-to-numeric-of-many-columns-in-a-data-frame)
in a dataframe with 140 columns
```
cols = c(1:140);
merged_dataset[,cols] = apply(merged_dataset[,cols], 2, function(x) as.numeric(as.character(x)));
```
the problem is for some columns I get NAs. Is there a way somehow exclude these columns from the code so that I keep the data and they don't get transformed into NAs? I see the type of these columns is character if that helps. | 2019/10/17 | [
"https://Stackoverflow.com/questions/58426254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4235960/"
] | If you already know the indices of the columns you want to drop, then you may subset your data frame to target only certain columns:
```
cols <- c(1:140) # all columns
cols.skip <- c(1,3,5,21) # columns which CAN'T be converted to numeric
cols.keep <- cols[!cols %in% cols.skip]
merged_dataset[,cols.keep] <- apply(merged_dataset[,cols.keep], 2, function(x) {
as.numeric(as.character(x))
})
```
To implement similar logic using column names rather than indices:
```
cols.skip <- c("a", "b", "c")
cols.keep <- !(names(merged_dataset) %in% cols.skip)
merged_dataset[,cols.keep] <- apply(merged_dataset[,cols.keep], 2, function(x) {
as.numeric(as.character(x))
})
``` | Substitution of any improper characters inside factor levels can also occur to better extract any numbers:
```
convert_factors_to_numeric <- function(df) {
as.data.frame(lapply(df,
function(x) {
if (is.factor(x)) {
as.numeric(as.character(trimws(x),
which = "both"))
} else{
x
}
}
),
stringsAsFactors = FALSE)
}
df_converted <- convert_factors_to_numeric(df)
``` |
54,718,994 | Something strange is happening with a database server I had to rebuild and restore from backup.
I'm pointing an old VB6 application using ADODB.Connection and a modern C# EF6 application at it, using what should be the same connection string for both, of the form
```
servername\INSTANCE
```
When run on the same machine that's running SQL Server, the VB6 application and EF6 application are both able to connect using this connection string.
When run on a different machine on the network, the VB6 application connects, but the EF6 application doesn't.
(with a standard "server not found" message, error: 26 - Error Locating Server/Instance Specified at System.Data.SqlClient.SqlInternalConnectionTds..ctor)
If I look at the specific instance port and connect with
```
servername,instance_port_number
```
then both applications connect, whatever machine I run them on. So it seems like something might be happening with SQL Server Browser to cause the issue.
Is there a way I can get some kind of diagnostic information out of SQL Server Browser, what data it's sent to where, without going as far as to monitor all network traffic? | 2019/02/16 | [
"https://Stackoverflow.com/questions/54718994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34384/"
] | An alternative to a network trace for troubleshooting is to send an instance enumeration query to the SQL Server Browser service and examine the results. This will verify the SQL Server Browser is reachable over UDP port 1434 and that the returned datagram contains the instance name and port information needed for the client to connect to a named instance.
Run the PowerShell script below on the problem machine.
```
# verify UDP port 1433 connectivity and query SQL Server Browser for all instances
Function Get-SqlServerBrowerDatagramForAllInstances($hostNameOrIpAddress)
{
Write-Host "Querying SQL Browser for all instances on host $hostNameOrIpAddress ..."
try
{
$udpClient = New-Object Net.Sockets.UdpClient($hostNameOrIpAddress, 1434)
$bufferLength = 1
$browserQueryMessage = New-Object byte[] 1
$browserQueryMessage[0] = 2
$bytesSent = $udpClient.Send($browserQueryMessage, $browserQueryMessage.Length)
$udpClient.Client.ReceiveTimeout = 10000
$remoteEndPoint = New-Object System.Net.IPEndPoint([System.Net.IPAddress]::Broadcast, 0)
$browserResponse = $udpClient.Receive([ref]$remoteEndPoint)
$payloadLength = $browserResponse.Length - 3
$browserResponseString = [System.Text.ASCIIEncoding]::ASCII.GetString($browserResponse, 3, $payloadLength)
$elements = $browserResponseString.Split(";")
Write-Host "SQL Server Browser query results:`r`n"
for($i = 0; $i -lt $elements.Length; $i = $i + 2)
{
if ($elements[$i] -ne "")
{
Write-Host "`t$($elements[$i])=$($elements[$i+1])"
}
else
{
Write-Host ""
# next instance
$i = $i - 1
}
}
}
catch [Exception]
{
Write-Host "ERROR: $($_.Exception.Message)" -ForegroundColor Red
}
}
# verify UDP port 1433 connectivity and query SQL Server Browser for single instance
Function Get-SqlServerBrowerDatagramByInstanceName($hostNameOrIpAddress, $instanceName)
{
Write-Host "Querying SQL Browser for host $hostNameOrIpAddress, instance $instanceName ..."
try
{
$instanceNameBytes = [System.Text.Encoding]::ASCII.GetBytes($instanceName)
$udpClient = New-Object Net.Sockets.UdpClient($hostNameOrIpAddress, 1434)
$bufferLength = $InstanceNameBytes.Length + 2
$browserQueryMessage = New-Object byte[] $bufferLength
$browserQueryMessage[0] = 4
$instanceNameBytes.CopyTo($browserQueryMessage, 1)
$browserQueryMessage[$bufferLength-1] = 0
$bytesSent = $udpClient.Send($browserQueryMessage, $browserQueryMessage.Length)
$udpClient.Client.ReceiveTimeout = 10000
$remoteEndPoint = New-Object System.Net.IPEndPoint([System.Net.IPAddress]::Broadcast, 0)
$browserResponse = $udpClient.Receive([ref]$remoteEndPoint)
$payloadLength = $browserResponse.Length - 3
$browserResponseString = [System.Text.ASCIIEncoding]::ASCII.GetString($browserResponse, 3, $payloadLength)
$elements = $browserResponseString.Split(";")
$namedInstancePort = ""
Write-Host "SQL Server Browser query results:`r`n"
for($i = 0; $i -lt $elements.Length; $i = $i + 2)
{
if ($elements[$i] -ne "")
{
Write-Host "`t$($elements[$i])=$($elements[$i+1])"
if($elements[$i] -eq "tcp")
{
$namedInstancePort = $elements[$i+1]
}
}
}
}
catch [Exception]
{
Write-Host "ERROR: $($_.Exception.Message)" -ForegroundColor Red
}
}
Get-SqlServerBrowerDatagramForAllInstances -hostNameOrIpAddress "servername"
Get-SqlServerBrowerDatagramByInstanceName -hostNameOrIpAddress "servername" -instanceName "INSTANCE"
``` | In entity framework 6 you can take the dbcontext object and do something like. Yourcontext.Database.log = s => mylogger.Debug(s);
The right hand side is a lambda function that takes a string s and logs it.
All of the sql and parameters get logged. |
63,928,980 | Very new to xslt (still). I think I need to use a 'When-Otherwise' to do the following (correct me if I'm wrong), so looking for some guidance on correct syntax for the following logic:
When 'Contribution\_Amount' is <=0, then ignore the row and do not output.
Otherwise return 'Contribution\_Amount'.
Or I could also use opposite if that's easier/better
When 'Contribution\_Amount' is >0, then 'Contribution\_Amount'
Otherwise do not produce output
Here is the xsl. Any suggestions or help would be greatly appreciated. Thanks in advance!
```
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:out="http://www.workday.com/integration/output"
xmlns:etv="urn:com.workday/etv" exclude-result-prefixes="xs" version="2.0"
xmlns:xtt="urn:com.workday/xtt"
xmlns:wd="urn:com.workday.report/Pay_Calculation_Results_-__Deduction_Register">
<xsl:template match="wd:Report_Data">
<File xtt:separator="
">
<Header xtt:separator="|">
<Record_Type>FH</Record_Type>
<Administractor_Code>FTB</Administractor_Code>
<Employer_Code>555</Employer_Code>
<Flag></Flag>
<Submitted_Date><xsl:value-of select="format-date(current-date(),'[M01][D01][Y0001]')"/></Submitted_Date>
<Submitted_Time><xsl:value-of select="format-time(current-time(),'[H01][m01][s01]')"/></Submitted_Time>
<File_Version>2.0</File_Version>
</Header>
<xsl:for-each-group select="wd:Report_Entry" group-by="wd:Worker/wd:SSN">
<xsl:for-each-group select="current-group()" group-by="wd:Deduction_Description">
<CT xtt:separator="|">
<Record_Type>CT</Record_Type>
<Participant_File_Import_Id><xsl:value-of select="wd:Worker/wd:SSN"/></Participant_File_Import_Id>
<Plan_Name>HSA</Plan_Name>
<contribution_date><xsl:value-of select="format-date(wd:Payment_Date,'[M01][D01][Y0001]')"/></contribution_date>
<Contribution_desc><xsl:value-of select="wd:Deduction_Description"/></Contribution_desc>
<contribution_Amount><xsl:value-of select="format-number(sum(current-group()//wd:Current_Period_Result),'#0.00')"/></contribution_Amount>
<amount_type>Actual</amount_type>
</CT>
</xsl:for-each-group>
</xsl:for-each-group>
<Footer xtt:separator="|">
<xsl:variable name="Total_Count" select="count(wd:Report_Entry)"/>
<Record_Type>FF</Record_Type>
<Record_Count><xsl:value-of select="$Total_Count + 2"/></Record_Count>
<Administrator_Total>FTB</Administrator_Total>
<Employer_Code>555</Employer_Code>
<Submitted_Date><xsl:value-of select="format-date(current-date(),'[M01][D01][Y0001]')"/></Submitted_Date>
<Submitted_Time><xsl:value-of select="format-time(current-time(),'[H01][m01][s01]')"/></Submitted_Time>
</Footer>
</File>
</xsl:template>
</xsl:stylesheet>
```
Here is the xml input. I labeled it 1.0 because that's what our original developer created it as. I'm not versed enough to really know the difference or when to switch it over, apologies.
```
<?xml version='1.0' encoding='UTF-8'?>
<wd:Report_Data xmlns:wd="urn:com.workday.report/Pay_Calculation_Results_-__Deduction_Register">
<wd:Report_Entry>
<wd:Payroll_Result wd:Descriptor="Daffy Duck | Daffy Duck (12345): 03/08/2020 (Regular) - Complete">
<wd:ID wd:type="WID">1</wd:ID>
</wd:Payroll_Result>
<wd:Worker wd:Descriptor="Daffy Duck | Daffy Duck (12345)">
<wd:ID wd:type="WID">6</wd:ID>
<wd:ID wd:type="Employee_ID">12345</wd:ID>
</wd:Worker>
<wd:Worker>
<wd:SSN>123456789</wd:SSN>
</wd:Worker>
<wd:Employee_ID>12345</wd:Employee_ID>
<wd:Company wd:Descriptor="ACME Corp">
<wd:ID wd:type="WID">2</wd:ID>
<wd:ID wd:type="Organization_Reference_ID">ACME</wd:ID>
<wd:ID wd:type="Company_Reference_ID">ACME</wd:ID>
</wd:Company>
<wd:Organizations wd:Descriptor="Cost Center: Management Team 90">
<wd:ID wd:type="WID">3</wd:ID>
<wd:ID wd:type="Organization_Reference_ID">10090</wd:ID>
<wd:ID wd:type="Cost_Center_Reference_ID">10090</wd:ID>
</wd:Organizations>
<wd:Organizations wd:Descriptor="Location: Location 1">
<wd:ID wd:type="WID">4</wd:ID>
<wd:ID wd:type="Location_ID">LOC01</wd:ID>
</wd:Organizations>
<wd:Period wd:Descriptor="02/24/2020 - 03/08/2020 (Bi-weekly (Mon-Sun))">
<wd:ID wd:type="WID">5</wd:ID>
<wd:ID wd:type="Period_ID">19</wd:ID>
</wd:Period>
<wd:Deduction>HSA Employer Contribution</wd:Deduction>
<wd:Deduction_Description>Employer Contribution</wd:Deduction_Description>
<wd:Payment_Date>2020-03-13-07:00</wd:Payment_Date>
<wd:Deduction_Code>HSA ER CON</wd:Deduction_Code>
<wd:Current_Period_Result>41.66</wd:Current_Period_Result>
</wd:Report_Entry>
<wd:Report_Entry>
<wd:Payroll_Result wd:Descriptor="Daffy Duck | Daffy Duck (12345): 03/08/2020 (Regular) - Complete">
<wd:ID wd:type="WID">1</wd:ID>
</wd:Payroll_Result>
<wd:Worker wd:Descriptor="Daffy Duck | Daffy Duck (12345)">
<wd:ID wd:type="WID">6</wd:ID>
<wd:ID wd:type="Employee_ID">12345</wd:ID>
</wd:Worker>
<wd:Worker>
<wd:SSN>123456789</wd:SSN>
</wd:Worker>
<wd:Employee_ID>12345</wd:Employee_ID>
<wd:Company wd:Descriptor="ACME Corp">
<wd:ID wd:type="WID">2</wd:ID>
<wd:ID wd:type="Organization_Reference_ID">ACME</wd:ID>
<wd:ID wd:type="Company_Reference_ID">ACME</wd:ID>
</wd:Company>
<wd:Organizations wd:Descriptor="Cost Center: Management Team 90">
<wd:ID wd:type="WID">3</wd:ID>
<wd:ID wd:type="Organization_Reference_ID">10090</wd:ID>
<wd:ID wd:type="Cost_Center_Reference_ID">10090</wd:ID>
</wd:Organizations>
<wd:Organizations wd:Descriptor="Location: Location 1">
<wd:ID wd:type="WID">4</wd:ID>
<wd:ID wd:type="Location_ID">LOC01</wd:ID>
</wd:Organizations>
<wd:Period wd:Descriptor="02/24/2020 - 03/08/2020 (Bi-weekly (Mon-Sun))">
<wd:ID wd:type="WID">5</wd:ID>
<wd:ID wd:type="Period_ID">19</wd:ID>
</wd:Period>
<wd:Deduction>HSA - Contribution</wd:Deduction>
<wd:Deduction_Description>Payroll Deduction</wd:Deduction_Description>
<wd:Payment_Date>2020-03-13-07:00</wd:Payment_Date>
<wd:Deduction_Code>HSA</wd:Deduction_Code>
<wd:Current_Period_Result>254.17</wd:Current_Period_Result>
</wd:Report_Entry>
<wd:Report_Entry>
<wd:Payroll_Result wd:Descriptor="Daffy Duck | Daffy Duck (12345): 03/08/2020 (Regular) - Complete">
<wd:ID wd:type="WID">1</wd:ID>
</wd:Payroll_Result>
<wd:Worker wd:Descriptor="Daffy Duck | Daffy Duck (12345)">
<wd:ID wd:type="WID">6</wd:ID>
<wd:ID wd:type="Employee_ID">12345</wd:ID>
</wd:Worker>
<wd:Worker>
<wd:SSN>123456789</wd:SSN>
</wd:Worker>
<wd:Employee_ID>12345</wd:Employee_ID>
<wd:Company wd:Descriptor="ACME Corp">
<wd:ID wd:type="WID">2</wd:ID>
<wd:ID wd:type="Organization_Reference_ID">ACME</wd:ID>
<wd:ID wd:type="Company_Reference_ID">ACME</wd:ID>
</wd:Company>
<wd:Organizations wd:Descriptor="Cost Center: Management Team 90">
<wd:ID wd:type="WID">3</wd:ID>
<wd:ID wd:type="Organization_Reference_ID">10090</wd:ID>
<wd:ID wd:type="Cost_Center_Reference_ID">10090</wd:ID>
</wd:Organizations>
<wd:Organizations wd:Descriptor="Location: Location 1">
<wd:ID wd:type="WID">4</wd:ID>
<wd:ID wd:type="Location_ID">LOC01</wd:ID>
</wd:Organizations>
<wd:Period wd:Descriptor="02/24/2020 - 03/08/2020 (Bi-weekly (Mon-Sun))">
<wd:ID wd:type="WID">5</wd:ID>
<wd:ID wd:type="Period_ID">19</wd:ID>
</wd:Period>
<wd:Deduction>HSA - Contribution</wd:Deduction>
<wd:Deduction_Description>Payroll Deduction</wd:Deduction_Description>
<wd:Payment_Date>2020-03-13-07:00</wd:Payment_Date>
<wd:Deduction_Code>HSA</wd:Deduction_Code>
<wd:Current_Period_Result>-250</wd:Current_Period_Result>
</wd:Report_Entry>
<wd:Report_Entry>
<wd:Payroll_Result wd:Descriptor="Daffy Duck | Daffy Duck (12345): 03/08/2020 (Regular) - Complete">
<wd:ID wd:type="WID">1</wd:ID>
</wd:Payroll_Result>
<wd:Worker wd:Descriptor="Daffy Duck | Daffy Duck (12345)">
<wd:ID wd:type="WID">6</wd:ID>
<wd:ID wd:type="Employee_ID">12345</wd:ID>
</wd:Worker>
<wd:Worker>
<wd:SSN>123456789</wd:SSN>
</wd:Worker>
<wd:Employee_ID>12345</wd:Employee_ID>
<wd:Company wd:Descriptor="ACME Corp">
<wd:ID wd:type="WID">2</wd:ID>
<wd:ID wd:type="Organization_Reference_ID">ACME</wd:ID>
<wd:ID wd:type="Company_Reference_ID">ACME</wd:ID>
</wd:Company>
<wd:Organizations wd:Descriptor="Cost Center: Management Team 90">
<wd:ID wd:type="WID">3</wd:ID>
<wd:ID wd:type="Organization_Reference_ID">10090</wd:ID>
<wd:ID wd:type="Cost_Center_Reference_ID">10090</wd:ID>
</wd:Organizations>
<wd:Organizations wd:Descriptor="Location: Location 1">
<wd:ID wd:type="WID">4</wd:ID>
<wd:ID wd:type="Location_ID">LOC01</wd:ID>
</wd:Organizations>
<wd:Period wd:Descriptor="02/24/2020 - 03/08/2020 (Bi-weekly (Mon-Sun))">
<wd:ID wd:type="WID">5</wd:ID>
<wd:ID wd:type="Period_ID">19</wd:ID>
</wd:Period>
<wd:Deduction>HSA - Contribution</wd:Deduction>
<wd:Deduction_Description>Payroll Deduction</wd:Deduction_Description>
<wd:Payment_Date>2020-03-13-07:00</wd:Payment_Date>
<wd:Deduction_Code>HSA</wd:Deduction_Code>
<wd:Current_Period_Result>250</wd:Current_Period_Result>
</wd:Report_Entry>
</wd:Report_Data>
``` | 2020/09/16 | [
"https://Stackoverflow.com/questions/63928980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4276270/"
] | I would have streamlined this to:
```
<xsl:variable name="amt" select="sum(current-group()//wd:Current_Period_Result)" />
<xsl:if test="$amt">
<contribution_Amount>
<xsl:value-of select="format-number($amt, '0.00')"/>
</contribution_Amount>
</xsl:if>
```
(Should be a comment, but it's too much code). | I think I got it guys! I went with this:
```
<xsl:if test="format-number(sum(current-group()//wd:Current_Period_Result),'#0.00') > '0.00'">
<contribution_Amount><xsl:value-of select="format-number(sum(current-group()//wd:Current_Period_Result),'#0.00')"/></contribution_Amount>
</xsl:if>
``` |
14,037,901 | I have just started playing the Azure Mobile Services stuff. It's super cool however there are a few weird things I have noticed while trying to change the server side database scripts. One specific thing is that while writing a simple statement like:
if (results.length == 0)
it warned me saying that I should use === instead of == while comparing with zero.
Anyone know why that is? | 2012/12/26 | [
"https://Stackoverflow.com/questions/14037901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1020338/"
] | In loosely-typed languages, it's often useful to use === (strict equality operator) rather than == (equality operator), because otherwise the types of objects will be coerced during the equality check.
For example, `"0" == 0`, and `"" == 0`, and `[] == 0`.
However, none of those `=== 0`.
So if `results` happened to be an object with an empty property `length`, like so:
```
var results = {
length: ""
}
```
`results.length == 0` would still evaluate to `true`. | Because
```
[] == 0
```
is true, but
```
[] === 0
```
Isn't.
Read about [JavaScript comparison operators](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Comparison_Operators) (and *strict equality* in particular). |
5,079 | I'm trying to create one report (to be as a mailing list) that combines Opportunities with Accounts and Contacts but I can't find a way.
I need all the Contacts for Accounts which have Opportunities on them where the Opp stage is Trial.
Any ideas.
Thanks | 2012/12/05 | [
"https://salesforce.stackexchange.com/questions/5079",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/490/"
] | Create a Roll-Up Summary field on Account that gives you the `COUNT` of Opportunities where `Stage = 'Trial'`.
Then your report will be on Accounts and Contacts, where `Account.Count_of_Trial_Opps__c > 0`. | You can do it with SOQL, not so easy with reports. Reports aren't great when you want to go into 2 different "branches" (from Account to Contacts + from Account to Opportunities).
Joined report might be OK but will show you a lot of "false positives" (only the opportunity-related side will respect your filter by Stage). This might change in later releases, after all in the beginning joined reports didn't support charts or exporting to excel...
Can you consider fixing your data so for example once Opp is in Trial state all contacts from Account are linked to it via OpportunityContactRole? This will probably require some triggers in order to maintain...
If that's also not a valid solution - you might be able to pull it off with some kind of analytic snapshots?
SOQL could be as easy as
```
SELECT FirstName, LastName, Email, Account.Name
FROM Contact
WHERE AccountId IN (SELECT AccountId FROM Opportunity WHERE StageName = 'Trial')
``` |
5,079 | I'm trying to create one report (to be as a mailing list) that combines Opportunities with Accounts and Contacts but I can't find a way.
I need all the Contacts for Accounts which have Opportunities on them where the Opp stage is Trial.
Any ideas.
Thanks | 2012/12/05 | [
"https://salesforce.stackexchange.com/questions/5079",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/490/"
] | You can do it with SOQL, not so easy with reports. Reports aren't great when you want to go into 2 different "branches" (from Account to Contacts + from Account to Opportunities).
Joined report might be OK but will show you a lot of "false positives" (only the opportunity-related side will respect your filter by Stage). This might change in later releases, after all in the beginning joined reports didn't support charts or exporting to excel...
Can you consider fixing your data so for example once Opp is in Trial state all contacts from Account are linked to it via OpportunityContactRole? This will probably require some triggers in order to maintain...
If that's also not a valid solution - you might be able to pull it off with some kind of analytic snapshots?
SOQL could be as easy as
```
SELECT FirstName, LastName, Email, Account.Name
FROM Contact
WHERE AccountId IN (SELECT AccountId FROM Opportunity WHERE StageName = 'Trial')
``` | You can create a custom report type with a primary object Contacts with Opportunities, and filter by Opp stage. |
5,079 | I'm trying to create one report (to be as a mailing list) that combines Opportunities with Accounts and Contacts but I can't find a way.
I need all the Contacts for Accounts which have Opportunities on them where the Opp stage is Trial.
Any ideas.
Thanks | 2012/12/05 | [
"https://salesforce.stackexchange.com/questions/5079",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/490/"
] | Create a Roll-Up Summary field on Account that gives you the `COUNT` of Opportunities where `Stage = 'Trial'`.
Then your report will be on Accounts and Contacts, where `Account.Count_of_Trial_Opps__c > 0`. | You could do this with [Custom Report Types](http://login.salesforce.com/help/doc/en/reports_report_type_def.htm) (CRT). Create a CRT based on Contacts that have at least one Opportunity. When you build a report on that type you can than filter on the Opportunity Stage and the Contact's Account. |
5,079 | I'm trying to create one report (to be as a mailing list) that combines Opportunities with Accounts and Contacts but I can't find a way.
I need all the Contacts for Accounts which have Opportunities on them where the Opp stage is Trial.
Any ideas.
Thanks | 2012/12/05 | [
"https://salesforce.stackexchange.com/questions/5079",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/490/"
] | You could do this with [Custom Report Types](http://login.salesforce.com/help/doc/en/reports_report_type_def.htm) (CRT). Create a CRT based on Contacts that have at least one Opportunity. When you build a report on that type you can than filter on the Opportunity Stage and the Contact's Account. | You can create a custom report type with a primary object Contacts with Opportunities, and filter by Opp stage. |
5,079 | I'm trying to create one report (to be as a mailing list) that combines Opportunities with Accounts and Contacts but I can't find a way.
I need all the Contacts for Accounts which have Opportunities on them where the Opp stage is Trial.
Any ideas.
Thanks | 2012/12/05 | [
"https://salesforce.stackexchange.com/questions/5079",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/490/"
] | Create a Roll-Up Summary field on Account that gives you the `COUNT` of Opportunities where `Stage = 'Trial'`.
Then your report will be on Accounts and Contacts, where `Account.Count_of_Trial_Opps__c > 0`. | You can create a custom report type with a primary object Contacts with Opportunities, and filter by Opp stage. |
23,557,410 | I would like to take numbers from a .txt file and input them through the command line into a program like the example below. I run the exe using ./program < input.txt. However it prints random numbers. What am I doing wrong?
```
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
//print 1st number
cout << argv[1];
}
``` | 2014/05/09 | [
"https://Stackoverflow.com/questions/23557410",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2791483/"
] | You can do this:
```
./program $(cat input.txt)
```
This does the trick.
For example, if input.txt has numbers separated by spaces:
33 1212 1555
Running:
```
./program $(cat input.txt)
```
prints 33 to the terminal. | To be able to use argv numbers need to be supplied as arguments, i.e.
./program 23 45 67
For ./program < input.txt you need to read from cin (standard input).
```
#include <iostream>
using namespace std;
int n;
int main()
{
cin >> n;
cout << n;
}
``` |
23,557,410 | I would like to take numbers from a .txt file and input them through the command line into a program like the example below. I run the exe using ./program < input.txt. However it prints random numbers. What am I doing wrong?
```
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
//print 1st number
cout << argv[1];
}
``` | 2014/05/09 | [
"https://Stackoverflow.com/questions/23557410",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2791483/"
] | ```
cout << argv[1];
```
is equivalent to:
```
char* arg = argv[1];
cout << arg;
```
It just prints the value of the first argument to the program
In your case, you didn't provide an argument to the program.
When you use,
```
./program < input.txt
```
the contents of `input.ext` becomes `stdin` of your program. You can process that using:
```
int c;
while ( (c = fgetc(stdin)) != EOF )
{
fputc(c, stdout);
}
```
If you want to stay with C++ streams, you can use:
```
int c;
while ( (c = cin.get()) != EOF )
{
cout.put(c);
}
``` | To be able to use argv numbers need to be supplied as arguments, i.e.
./program 23 45 67
For ./program < input.txt you need to read from cin (standard input).
```
#include <iostream>
using namespace std;
int n;
int main()
{
cin >> n;
cout << n;
}
``` |
23,557,410 | I would like to take numbers from a .txt file and input them through the command line into a program like the example below. I run the exe using ./program < input.txt. However it prints random numbers. What am I doing wrong?
```
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
//print 1st number
cout << argv[1];
}
``` | 2014/05/09 | [
"https://Stackoverflow.com/questions/23557410",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2791483/"
] | ```
cout << argv[1];
```
is equivalent to:
```
char* arg = argv[1];
cout << arg;
```
It just prints the value of the first argument to the program
In your case, you didn't provide an argument to the program.
When you use,
```
./program < input.txt
```
the contents of `input.ext` becomes `stdin` of your program. You can process that using:
```
int c;
while ( (c = fgetc(stdin)) != EOF )
{
fputc(c, stdout);
}
```
If you want to stay with C++ streams, you can use:
```
int c;
while ( (c = cin.get()) != EOF )
{
cout.put(c);
}
``` | You can do this:
```
./program $(cat input.txt)
```
This does the trick.
For example, if input.txt has numbers separated by spaces:
33 1212 1555
Running:
```
./program $(cat input.txt)
```
prints 33 to the terminal. |
116,853 | Google Ngram Viewer shows a decline in the use of “nothing loath” since the 1970s unlike its antonym “loath” which is still widely used.
Would it be appropriate for me to use it or has it become obsolete? | 2013/06/17 | [
"https://english.stackexchange.com/questions/116853",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/-1/"
] | The Motivated Grammar blog has [this useful summary](http://motivatedgrammar.wordpress.com/2010/04/22/jealousy-and-envy/):
>
> *Envy* is pretty well restricted to the feeling you get from wanting someone else’s stuff. *Jealousy* is a bit more inclusive, allowing you
> to either want to have someone else’s stuff or want to keep your own
> stuff.
>
>
>
Grammar Girl, however, dispenses [this caveat](http://grammar.quickanddirtytips.com/jealousy-versus-envy.aspx):
>
> The trouble is that “jealous” and “envious” have overlapping meanings
> and are often used interchangeably, but some people argue that they
> mean different things.
>
>
> If you wish to be precise, make a distinction between “jealous” and
> “envious” in your writing, but don’t be surprised when the definitions
> are blurred in pop culture.
>
>
>
My usage tends to agree with the one from Motivated Grammar; by that measure, it would be more positive to tell your friend, "I am *envious* of your good fortune." | I think you can in good conscience say you envy your friend, and it will be taken as a friendly remark. I don't see *jealous* as quite so innocent, but in general there isn't much to differentiate the two terms. For example, wiktionary usage notes for *[jealous](http://en.wiktionary.org/wiki/jealous)* say
>
> Some usage guides seek to distinguish “jealous” from “envious”, using jealous to mean “protective of one’s own position or possessions” – one “jealously guards what one has” – and envious to mean “desirous of others’ position or possessions” – one “envies what others have”. This distinction is also maintained in the psychological and philosophical literature. However, this distinction is not reflected in usage, as reflected in the quotations of famous authors (above) using the word jealous in the sense “envious (of the possessions of others)”.
>
>
>
When taken to extremes, neither envy nor jealousy is a positive emotion; for example, *[envy](http://www.deadlysins.com/sins/envy.html)* is known as the second deadly sin. But if you are envious or jealous, to say otherwise would be lying, which generally is not recommended except in social situations where the truth will offend. |
116,853 | Google Ngram Viewer shows a decline in the use of “nothing loath” since the 1970s unlike its antonym “loath” which is still widely used.
Would it be appropriate for me to use it or has it become obsolete? | 2013/06/17 | [
"https://english.stackexchange.com/questions/116853",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/-1/"
] | The Motivated Grammar blog has [this useful summary](http://motivatedgrammar.wordpress.com/2010/04/22/jealousy-and-envy/):
>
> *Envy* is pretty well restricted to the feeling you get from wanting someone else’s stuff. *Jealousy* is a bit more inclusive, allowing you
> to either want to have someone else’s stuff or want to keep your own
> stuff.
>
>
>
Grammar Girl, however, dispenses [this caveat](http://grammar.quickanddirtytips.com/jealousy-versus-envy.aspx):
>
> The trouble is that “jealous” and “envious” have overlapping meanings
> and are often used interchangeably, but some people argue that they
> mean different things.
>
>
> If you wish to be precise, make a distinction between “jealous” and
> “envious” in your writing, but don’t be surprised when the definitions
> are blurred in pop culture.
>
>
>
My usage tends to agree with the one from Motivated Grammar; by that measure, it would be more positive to tell your friend, "I am *envious* of your good fortune." | If I were forced to differentiate between the two in your particular example,:
>
> **I'm envious of you** could just mean that you are envious of him getting married - and that you would like to get married.
>
>
> **I'm jealous of you** could mean that you would have liked to marry his wife.
>
>
>
Note that these are **not** definitive answers, and context (or tone of voice) can considerably affect the implied meaning. Also, as others have said, there is considerable overlap,, and people may use them in different ways. |
116,853 | Google Ngram Viewer shows a decline in the use of “nothing loath” since the 1970s unlike its antonym “loath” which is still widely used.
Would it be appropriate for me to use it or has it become obsolete? | 2013/06/17 | [
"https://english.stackexchange.com/questions/116853",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/-1/"
] | The Motivated Grammar blog has [this useful summary](http://motivatedgrammar.wordpress.com/2010/04/22/jealousy-and-envy/):
>
> *Envy* is pretty well restricted to the feeling you get from wanting someone else’s stuff. *Jealousy* is a bit more inclusive, allowing you
> to either want to have someone else’s stuff or want to keep your own
> stuff.
>
>
>
Grammar Girl, however, dispenses [this caveat](http://grammar.quickanddirtytips.com/jealousy-versus-envy.aspx):
>
> The trouble is that “jealous” and “envious” have overlapping meanings
> and are often used interchangeably, but some people argue that they
> mean different things.
>
>
> If you wish to be precise, make a distinction between “jealous” and
> “envious” in your writing, but don’t be surprised when the definitions
> are blurred in pop culture.
>
>
>
My usage tends to agree with the one from Motivated Grammar; by that measure, it would be more positive to tell your friend, "I am *envious* of your good fortune." | Both envious and jealous have similar definitions:
[Compact OED](http://oxforddictionaries.com/definition/english/envy?view=uk) defines *envy* as
>
> a feeling of discontented or resentful longing aroused by someone else’s possessions, qualities, or luck
>
>
>
It defines jealousy as the state of being jealous and defines *[jealous](http://oxforddictionaries.com/definition/english/jealous?q=jealous)* as
>
> feeling or showing an envious resentment of someone or their achievements, possessions, or perceived advantages
>
>
>
While they can often be interchanged, jealous can also be used to refer to a guarding of ones own possessions or rights. [COED](http://oxforddictionaries.com/definition/english/jealous?q=jealous) offers
>
> feeling or showing a resentful suspicion that one’s partner is attracted to or involved with someone else: a jealous husband
>
>
> fiercely protective of one’s rights or possessions: the men were proud of their achievements and jealous of their independence
>
>
> (of God) demanding faithfulness and exclusive worship.
>
>
>
While both envy and jealousy are usually fairly negative emotions, in American English the phrases "I am envious of you" or "I am jealous of you" can be used to express an admiration of the position of the listener. More frequently, the phrase "I envy you" would probably be used.
Perhaps a better construction, to emphasize the positive aspects of your views, would be "I admire you". |
116,853 | Google Ngram Viewer shows a decline in the use of “nothing loath” since the 1970s unlike its antonym “loath” which is still widely used.
Would it be appropriate for me to use it or has it become obsolete? | 2013/06/17 | [
"https://english.stackexchange.com/questions/116853",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/-1/"
] | The Motivated Grammar blog has [this useful summary](http://motivatedgrammar.wordpress.com/2010/04/22/jealousy-and-envy/):
>
> *Envy* is pretty well restricted to the feeling you get from wanting someone else’s stuff. *Jealousy* is a bit more inclusive, allowing you
> to either want to have someone else’s stuff or want to keep your own
> stuff.
>
>
>
Grammar Girl, however, dispenses [this caveat](http://grammar.quickanddirtytips.com/jealousy-versus-envy.aspx):
>
> The trouble is that “jealous” and “envious” have overlapping meanings
> and are often used interchangeably, but some people argue that they
> mean different things.
>
>
> If you wish to be precise, make a distinction between “jealous” and
> “envious” in your writing, but don’t be surprised when the definitions
> are blurred in pop culture.
>
>
>
My usage tends to agree with the one from Motivated Grammar; by that measure, it would be more positive to tell your friend, "I am *envious* of your good fortune." | The important thing to keep in mind is as follows: jealousy is triggered by a third party. I'll say it again: jealous feelings are triggered by a **third** party.
Let's modify the example you gave by adding the following component: you are very much attracted to your friend's wife. If your friend finds out about it and sees you chatting up his wife, he would likely display a measure of *jealous* behavior.
On the other hand, let's keep your example as it is. You say your friend's wife is "a very cute lady." Fine. Of you it could be said, "You're a little *envious*!" In other words, you *might* want (deep in the recesses of your unconscious mind!) what is not yours to have. Envy, by the way, is called the "green-eyed monster." Another saying is, "The grass is always greener on the other side of the hill." But I digress.
True, there are three parties involved in both of the above scenarios, but what triggers jealous feelings is one party's right (within reason, of course) to protect the third party (i.e., his wife). Your friend does NOT want to share his wife with another person--even you, his good friend. This is normal.
Jealous feelings get out of hand, however, when a husband becomes so suspicious of his wife's behavior, that every time she talks to another man, her husband flies into a jealous rage. Clearly he is overreacting (if in fact his wife is simply talking with another male in the normal course of events). Maybe she's just asking a guy for the time!
Jealous feelings can become a cancer in a committed relationship, because a critical element in the foundation to a good marriage is trust. When trust evaporates, jealousy rears its ugly head.
Being envious can also be destructive, like a cancer. An envious person is never satisfied with what she has but is forever gazing enviously on the abilities, gifts, possessions, and good looks of others. Contentment eludes her.
Which has a more "positive" implication? Offhand, I'd say neither.
Nevertheless, it is perfectly acceptable in normal conversation for you to say to your friend in a friendly, non-threatening way, "Hey man, I'm really envious of your for marrying such a great gal! I hope I do as well as you did when the time comes for me to marry!"
I've noticed that people today use the terms *envious* and *jealous* almost interchangeably, which is OK, I guess. If they use the word *jealous*, however, usually they mean *envious*, and when they use *envious* they could mean *jealous*.
Is it worth correcting people when they mix the two words up? If you're the teacher and they're the students, then OK; otherwise, just pride yourself on knowing the difference between the words *envious* and *jealous* and keep this knowledge to yourself! |
116,853 | Google Ngram Viewer shows a decline in the use of “nothing loath” since the 1970s unlike its antonym “loath” which is still widely used.
Would it be appropriate for me to use it or has it become obsolete? | 2013/06/17 | [
"https://english.stackexchange.com/questions/116853",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/-1/"
] | The Motivated Grammar blog has [this useful summary](http://motivatedgrammar.wordpress.com/2010/04/22/jealousy-and-envy/):
>
> *Envy* is pretty well restricted to the feeling you get from wanting someone else’s stuff. *Jealousy* is a bit more inclusive, allowing you
> to either want to have someone else’s stuff or want to keep your own
> stuff.
>
>
>
Grammar Girl, however, dispenses [this caveat](http://grammar.quickanddirtytips.com/jealousy-versus-envy.aspx):
>
> The trouble is that “jealous” and “envious” have overlapping meanings
> and are often used interchangeably, but some people argue that they
> mean different things.
>
>
> If you wish to be precise, make a distinction between “jealous” and
> “envious” in your writing, but don’t be surprised when the definitions
> are blurred in pop culture.
>
>
>
My usage tends to agree with the one from Motivated Grammar; by that measure, it would be more positive to tell your friend, "I am *envious* of your good fortune." | In this situation, I would sidestep the possibility of offense by saying "You are a man of obvious good fortune." That said "envy" has had a less covetous flavor in my experience than "jealousy." |
5,095,234 | I have All Android SDK versions(from 1.5 to 2.3.3), and I tried many methods for getting root in Android emulator. I don't use any Android device and test everything on emulator(AVD).
I need to get root access in any one of the Android emulator to use the 'iptables' and 'busybox' functionality. And to use iptables I must have root access. Atleast 'su' command should execute in the terminal emulator.
I also installed `z4root` application,
But it takes very long time and doesn't finish rooting, and gets stuck. some say that if we downgrade the system to below RC30, this way we can get root access. if this is true, then how to do this? I use both Linux and Windows OS.
Please someone tell me any method to root my emulator. | 2011/02/23 | [
"https://Stackoverflow.com/questions/5095234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/545643/"
] | I know this question is pretty old. But we can able to get root in Emulator with the help of Magisk by following <https://github.com/shakalaca/MagiskOnEmulator>
Basically, it patch initrd.img(if present) and ramdisk.img for working with Magisk. | I tried many of the above suggestions, including SuperSU and couldn't get any to work but found something much simpler that worked for my purposes. In my case, I only wanted to be able to run sqlite at the command prompt. I simply spun up an emulator with an older version of Android (Lollipop) and got root access immediately. |
5,095,234 | I have All Android SDK versions(from 1.5 to 2.3.3), and I tried many methods for getting root in Android emulator. I don't use any Android device and test everything on emulator(AVD).
I need to get root access in any one of the Android emulator to use the 'iptables' and 'busybox' functionality. And to use iptables I must have root access. Atleast 'su' command should execute in the terminal emulator.
I also installed `z4root` application,
But it takes very long time and doesn't finish rooting, and gets stuck. some say that if we downgrade the system to below RC30, this way we can get root access. if this is true, then how to do this? I use both Linux and Windows OS.
Please someone tell me any method to root my emulator. | 2011/02/23 | [
"https://Stackoverflow.com/questions/5095234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/545643/"
] | If you have a virtual device with root access, this should do the job:
```
$ > adb shell
generic_x86:/ $
generic_x86:/ $ exit
$ > adb root
restarting adbd as root
$ > adb shell
generic_x86:/ #
```
If you don't, you might be interested in this [answer](https://stackoverflow.com/a/45668555/1682419) to a different question, which explains how to create an virtual device with root access, with Google APIs (aka *Google Play services*), but without the Google Play app.
If you really need the Google Play app, you might be interested in other answers which instruct how to root an Android virtual device. | I believe that the easiest way is to create an alias for the command `sh`, e.g.
```
adb shell
mount -o rw,remount -t yaffs2 /dev/block/mtdblock3 /system
cd /system/bin
cat sh > su && chmod 4775 su
```
Tested on Android Emulator 3.0 and higher. |
5,095,234 | I have All Android SDK versions(from 1.5 to 2.3.3), and I tried many methods for getting root in Android emulator. I don't use any Android device and test everything on emulator(AVD).
I need to get root access in any one of the Android emulator to use the 'iptables' and 'busybox' functionality. And to use iptables I must have root access. Atleast 'su' command should execute in the terminal emulator.
I also installed `z4root` application,
But it takes very long time and doesn't finish rooting, and gets stuck. some say that if we downgrade the system to below RC30, this way we can get root access. if this is true, then how to do this? I use both Linux and Windows OS.
Please someone tell me any method to root my emulator. | 2011/02/23 | [
"https://Stackoverflow.com/questions/5095234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/545643/"
] | For AVD with 5.1.1 and 6.0 I used next script in windows:
```
set adb=adb -s emulator-5558
set arch=x64
set pie=
adb start-server
%adb% root
%adb% remount
rem %adb% shell mount -o remount,rw /system
%adb% shell setenforce 0
%adb% install common/Superuser.apk
%adb% push %arch%/su%pie% /system/bin/su
%adb% shell chmod 0755 /system/bin/su
%adb% push %arch%/su%pie% /system/xbin/su
%adb% shell chmod 0755 /system/xbin/su
%adb% shell su --install
%adb% shell "su --daemon&"
rem %adb% shell mount -o remount,ro /system
exit /b
```
Need UPDATE.zip from SuperSU. Unpacked them to any folder. Create bat file with content above. Do not forget specify necessary architecture and device: `set adb=adb -s emulator-5558` and `set arch=x64`. If you run Android above or equal 5.0, change `set pie=` to `set pie=.pie`. Run it. You get temporary root for current run.
If you got error on remount system partition then you need start AVD from command line. See below first step for Android 7.
If you want make it persistent - update binary in SuperSU and store system.img from temp folder as replace of default system.img.
**How to convert the resulting temporary root on a permanent**
First - it goes to SuperSu. It offers a binary upgrade. Update in the normal way. Reboot reject.
Second - only relevant for emulators. The same AVD. The bottom line is that changes in the system image will not be saved. You need to keep them for themselves.
There are already instructions vary for different emulators.
For AVD you can try to find a temporary file system.img, save it somewhere and use when you start the emulator.
In Windows it is located in the `%LOCALAPPDATA%\Temp\AndroidEmulator` and has a name something like `TMP4980.tmp`.
You copy it to a folder avd device (`%HOMEPATH%\.android\avd\%AVD_NAME%.avd\`), and renamed to the `system.img`.
Now it will be used at the start, instead of the usual. True if the image in the SDK is updated, it will have the old one.
In this case, you will need to remove this `system.img`, and repeat the operation on its creation.
More detailed manual in Russian: <http://4pda.ru/forum/index.php?showtopic=318487&view=findpost&p=45421931>
---
For android 7 you need run additional steps:
1. Need run emulator manually.
Go to sdk folder `sdk\tools\lib64\qt\lib`.
Run from this folder emulator with options `-writable-system -selinux disabled`
Like this:
```
F:\android\sdk\tools\lib64\qt\lib>F:\android\sdk\tools\emulator.exe -avd 7.0_x86 -verbose -writable-system -selinux disabled
```
2. You need restart `adbd` from root:
adb -s emulator-5554 root
And remount system:
```
adb -s emulator-5554 remount
```
It can be doned only once per run emulator. And any another remount can break write mode. Because of this you not need run of any other commands with remount, like `mount -o remount,rw /system`.
Another steps stay same - upload binary, run binary as daemon and so on.
Picture from AVD Android 7 x86 with root:
[](https://i.stack.imgur.com/gD7qj.png)
---
If you see error about PIE on execute `su` binary - then you upload to emulator wrong binary. You must upload binary named `su.pie` inside archive, but on emulator it must be named as `su`, not `su.pie`. | I know this question is pretty old. But we can able to get root in Emulator with the help of Magisk by following <https://github.com/shakalaca/MagiskOnEmulator>
Basically, it patch initrd.img(if present) and ramdisk.img for working with Magisk. |
5,095,234 | I have All Android SDK versions(from 1.5 to 2.3.3), and I tried many methods for getting root in Android emulator. I don't use any Android device and test everything on emulator(AVD).
I need to get root access in any one of the Android emulator to use the 'iptables' and 'busybox' functionality. And to use iptables I must have root access. Atleast 'su' command should execute in the terminal emulator.
I also installed `z4root` application,
But it takes very long time and doesn't finish rooting, and gets stuck. some say that if we downgrade the system to below RC30, this way we can get root access. if this is true, then how to do this? I use both Linux and Windows OS.
Please someone tell me any method to root my emulator. | 2011/02/23 | [
"https://Stackoverflow.com/questions/5095234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/545643/"
] | I just replaced and assigned attributes for su to ~/Android/Sdk/system-images/android-22/google\_apis/x86/system.img
and now on android 5 I always have root even for new systems, it’s enough to install SuperSu.apk
```
Android 6 is necessary only
adb root
adb shell
>/system/xbin/su --daemon &
>setenfoce 0
```
after that, SuperSu.apk sees root. But I do not update the binary file | I tried many of the above suggestions, including SuperSU and couldn't get any to work but found something much simpler that worked for my purposes. In my case, I only wanted to be able to run sqlite at the command prompt. I simply spun up an emulator with an older version of Android (Lollipop) and got root access immediately. |
5,095,234 | I have All Android SDK versions(from 1.5 to 2.3.3), and I tried many methods for getting root in Android emulator. I don't use any Android device and test everything on emulator(AVD).
I need to get root access in any one of the Android emulator to use the 'iptables' and 'busybox' functionality. And to use iptables I must have root access. Atleast 'su' command should execute in the terminal emulator.
I also installed `z4root` application,
But it takes very long time and doesn't finish rooting, and gets stuck. some say that if we downgrade the system to below RC30, this way we can get root access. if this is true, then how to do this? I use both Linux and Windows OS.
Please someone tell me any method to root my emulator. | 2011/02/23 | [
"https://Stackoverflow.com/questions/5095234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/545643/"
] | I used part of the method from the solutions above; however, they did not work completely. On the latest version of Andy, this worked for me:
On Andy (Root Shell) [To get, right click the HandyAndy icon and select Term Shell]
Inside the shell, run these commands:
```
mount -o rw,remount -t yaffs2 /dev/block/mtdblock3 /system
cd /system/bin
cat sh > su && chmod 4775 su
```
Then, install SuperSU and install SU binary. This will replace the SU binary we just created.
(Optional)
Remove SuperSU and install Superuser by CWM. Install the su binary again.
Now, root works! | I found that default API 23 x86\_64 emulator is rooted by default. |
5,095,234 | I have All Android SDK versions(from 1.5 to 2.3.3), and I tried many methods for getting root in Android emulator. I don't use any Android device and test everything on emulator(AVD).
I need to get root access in any one of the Android emulator to use the 'iptables' and 'busybox' functionality. And to use iptables I must have root access. Atleast 'su' command should execute in the terminal emulator.
I also installed `z4root` application,
But it takes very long time and doesn't finish rooting, and gets stuck. some say that if we downgrade the system to below RC30, this way we can get root access. if this is true, then how to do this? I use both Linux and Windows OS.
Please someone tell me any method to root my emulator. | 2011/02/23 | [
"https://Stackoverflow.com/questions/5095234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/545643/"
] | I know this question is pretty old. But we can able to get root in Emulator with the help of Magisk by following <https://github.com/shakalaca/MagiskOnEmulator>
Basically, it patch initrd.img(if present) and ramdisk.img for working with Magisk. | I found that default API 23 x86\_64 emulator is rooted by default. |
5,095,234 | I have All Android SDK versions(from 1.5 to 2.3.3), and I tried many methods for getting root in Android emulator. I don't use any Android device and test everything on emulator(AVD).
I need to get root access in any one of the Android emulator to use the 'iptables' and 'busybox' functionality. And to use iptables I must have root access. Atleast 'su' command should execute in the terminal emulator.
I also installed `z4root` application,
But it takes very long time and doesn't finish rooting, and gets stuck. some say that if we downgrade the system to below RC30, this way we can get root access. if this is true, then how to do this? I use both Linux and Windows OS.
Please someone tell me any method to root my emulator. | 2011/02/23 | [
"https://Stackoverflow.com/questions/5095234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/545643/"
] | I just replaced and assigned attributes for su to ~/Android/Sdk/system-images/android-22/google\_apis/x86/system.img
and now on android 5 I always have root even for new systems, it’s enough to install SuperSu.apk
```
Android 6 is necessary only
adb root
adb shell
>/system/xbin/su --daemon &
>setenfoce 0
```
after that, SuperSu.apk sees root. But I do not update the binary file | I used part of the method from the solutions above; however, they did not work completely. On the latest version of Andy, this worked for me:
On Andy (Root Shell) [To get, right click the HandyAndy icon and select Term Shell]
Inside the shell, run these commands:
```
mount -o rw,remount -t yaffs2 /dev/block/mtdblock3 /system
cd /system/bin
cat sh > su && chmod 4775 su
```
Then, install SuperSU and install SU binary. This will replace the SU binary we just created.
(Optional)
Remove SuperSU and install Superuser by CWM. Install the su binary again.
Now, root works! |
5,095,234 | I have All Android SDK versions(from 1.5 to 2.3.3), and I tried many methods for getting root in Android emulator. I don't use any Android device and test everything on emulator(AVD).
I need to get root access in any one of the Android emulator to use the 'iptables' and 'busybox' functionality. And to use iptables I must have root access. Atleast 'su' command should execute in the terminal emulator.
I also installed `z4root` application,
But it takes very long time and doesn't finish rooting, and gets stuck. some say that if we downgrade the system to below RC30, this way we can get root access. if this is true, then how to do this? I use both Linux and Windows OS.
Please someone tell me any method to root my emulator. | 2011/02/23 | [
"https://Stackoverflow.com/questions/5095234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/545643/"
] | Here is the list of commands you have to run while the emulator is running, I test this solution for an avd on Android 2.2 :
```
adb shell mount -o rw,remount -t yaffs2 /dev/block/mtdblock03 /system
adb push su /system/xbin/su
adb shell chmod 06755 /system
adb shell chmod 06755 /system/xbin/su
```
It assumes that the su binary is located in the working directory. You can find su and superuser here : <http://forum.xda-developers.com/showthread.php?t=682828>.
You need to run these commands each time you launch the emulator. You can write a script that launch the emulator and root it. | [Here](https://yadi.sk/d/hP4bHmqK3PrA9Z) my pack with all you need.
Or you can use this script:
```
echo on
set device=emulator-5554
set avd_name=
set adb=d:\Poprygun\DevTools\Android\Android-sdk\platform-tools\adb -s %device%
set emulator=d:\Poprygun\DevTools\Android\Android-sdk\emulator\emulator
set arch=x86
set pie=
echo Close all ANDROID emulators and press any key
pause
start %emulator% -avd Nexus_One_API_25 -verbose -writable-system
echo Wait until ANDROID emulator loading and press any key
pause
%adb% start-server
%adb% root
%adb% remount
%adb% shell setenforce 0
%adb% install D:\SuperSU\SuperSU.apk
%adb% push D:\SuperSU\su\%arch%\su.pie /system/bin/su
%adb% shell chmod 0755 /system/bin/su
%adb% push D:\SuperSU\su\%arch%\su.pie /system/xbin/su
%adb% shell chmod 0755 /system/xbin/su
%adb% shell su --install
%adb% shell "su --daemon&"
pause
exit /b
``` |
5,095,234 | I have All Android SDK versions(from 1.5 to 2.3.3), and I tried many methods for getting root in Android emulator. I don't use any Android device and test everything on emulator(AVD).
I need to get root access in any one of the Android emulator to use the 'iptables' and 'busybox' functionality. And to use iptables I must have root access. Atleast 'su' command should execute in the terminal emulator.
I also installed `z4root` application,
But it takes very long time and doesn't finish rooting, and gets stuck. some say that if we downgrade the system to below RC30, this way we can get root access. if this is true, then how to do this? I use both Linux and Windows OS.
Please someone tell me any method to root my emulator. | 2011/02/23 | [
"https://Stackoverflow.com/questions/5095234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/545643/"
] | [Here](https://yadi.sk/d/hP4bHmqK3PrA9Z) my pack with all you need.
Or you can use this script:
```
echo on
set device=emulator-5554
set avd_name=
set adb=d:\Poprygun\DevTools\Android\Android-sdk\platform-tools\adb -s %device%
set emulator=d:\Poprygun\DevTools\Android\Android-sdk\emulator\emulator
set arch=x86
set pie=
echo Close all ANDROID emulators and press any key
pause
start %emulator% -avd Nexus_One_API_25 -verbose -writable-system
echo Wait until ANDROID emulator loading and press any key
pause
%adb% start-server
%adb% root
%adb% remount
%adb% shell setenforce 0
%adb% install D:\SuperSU\SuperSU.apk
%adb% push D:\SuperSU\su\%arch%\su.pie /system/bin/su
%adb% shell chmod 0755 /system/bin/su
%adb% push D:\SuperSU\su\%arch%\su.pie /system/xbin/su
%adb% shell chmod 0755 /system/xbin/su
%adb% shell su --install
%adb% shell "su --daemon&"
pause
exit /b
``` | I tried many of the above suggestions, including SuperSU and couldn't get any to work but found something much simpler that worked for my purposes. In my case, I only wanted to be able to run sqlite at the command prompt. I simply spun up an emulator with an older version of Android (Lollipop) and got root access immediately. |
5,095,234 | I have All Android SDK versions(from 1.5 to 2.3.3), and I tried many methods for getting root in Android emulator. I don't use any Android device and test everything on emulator(AVD).
I need to get root access in any one of the Android emulator to use the 'iptables' and 'busybox' functionality. And to use iptables I must have root access. Atleast 'su' command should execute in the terminal emulator.
I also installed `z4root` application,
But it takes very long time and doesn't finish rooting, and gets stuck. some say that if we downgrade the system to below RC30, this way we can get root access. if this is true, then how to do this? I use both Linux and Windows OS.
Please someone tell me any method to root my emulator. | 2011/02/23 | [
"https://Stackoverflow.com/questions/5095234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/545643/"
] | **How to root android emulator (tested on Android 7.1.1/ Nougat)**
**Requirements**:
* [SuperSU app (chainfire) latest version 2.82](https://supersu.en.uptodown.com/android)
* [Recovery flashable.zip (contains su binary)](http://www.supersu.com/download) (Here is **alternative backup** link provided by XDA user [Ibuprophen](https://forum.xda-developers.com/member.php?u=4828250) for flashable zips if the main link is not working: [**Flashable zip releases**](https://androidfilehost.com/?w=files&flid=154643))
**Instructions**
1. **Install the SuperSu.apk**
* Install the SuperSu app firstly, just do drag and drop (if running latest emulator version or sideload through adb i.e `adb -e install supersu.apk`)
* After installing it, when you run it shows a screen as shown below indicating “There is no SU binary installed..”. This error just confirms the device is not yet rooted.
[](https://i.stack.imgur.com/25iufm.png)
---
2. **Make emulator’ system partition writable**
* As it suggests, we need to give the emulator permission to write system files.
* Type the following code to accomplish this: `emulator -avd {emulator_name} -writable-system`
*If you have more than one AVD, you can get a list of avds by using the command: `emulator -list-avds`*
*Note: Navigate to the **tools** folder where Android SDK is installed and open command prompt there by pressing shift and right clicking.*
---
3. **Pushing su binary in system directory**
* Extract the Recovery flashable.zip (containing the su binaries of different architectures)
**Important! Only use the su binary that matches your avd architecture e.g x86, arm etc.., and note the path where you extracted these binaries.**
* Make sure you are running adb as root and also you need to remount.
Just enter these codes
`adb root`
`adb remount`
Now its time to push the su binary:
**This is the code I successfully used**: `adb -e push C:\Users\User1\Desktop\rootemu\x86\su.pie /system/bin/su`
*(nevermind about my specific location of su binary, any location is okay as long there is no white space)*
**note: To figure out `bin` or `xbin` do in console before: > `adb shell`, > `ls /system/xbin/su`**
If this fails try this pushing to this directory instead `/system/xbin/su`. Also for emulators running android 5.1 and below use the `su` and not `su.pie`
---
4. **Change permissions of the su binary**
* Next let’s do a bit of modification of the permissions of su binary. We have to do this in emulator device through adb:
```
adb -e shell
su root
cd /system/bin
chmod 06755 su
```
**Important!! Take note of su binary path (mine is /system/bin)**
---
5. **Setting the `install` directive on su binary and set a `daemon`**
Type the codes:
`su --install`
and for setting up daemon:
`su --daemon&`
**Important!! Take note of spacing**
---
6. **Setting SELinux to Permissive(i.e turning off SE Linux)**
* Finally turn off selinux through this code:
`setenforce 0`
---
7.
Open SuperSU app and it may ask to update binaries, you can use Normal method.
Note: If you're experiencing bootloops, rather don't update the binaries, just use it as it is.
---
That’s pretty much it!!
Open any application requiring SU permissions just to double check and indeed SuperSU ask if you wish to grant it su permissions.
[](https://i.stack.imgur.com/muPTim.png)
To have the root persist update su binary (using Normal method), then copy system.img from temp directory (`Users\AppData\Local\Temp\Android Emulator` the file is usually randomly named e.g `1359g.tmp` with a large size) and replace default `system.img`.
**Update**:
I have noted is is easier to obtain a temporary system image in Linux, than Windows. You can try using snapshot image.
##Update 4 August 2018
With the emergence of emulator `27.3.x` it now makes preserving root much easier through snapshot feature (if copying the `system.img` method isn't working):
Ideally it is more like hibernarig the virtual device with config intact, hence everything is preserved.
*Snapshots*
>
> You can now save multiple AVD snapshots for a given device
> configuration and choose which of the saved snapshots to load when you
> start the emulator. Starting a virtual device by loading a snapshot is
> much like waking a physical from a sleep state, as opposed to booting
> it from a powered-off state.
>
>
>
This implies the only requirement to start the emulator is adding the `-writable-system` parameter to the normal `emulator -avd [avdname]` command to start the emulator. (*Running the emulator just with `emulator -avd [avdname]` doesn't launch the rooted version/copy or may lead to some error*)
*Tested on API level 22*
Also for bootloop issues see the other post: [Android Emulator: How to avoid boot loop after rooting?](https://android.stackexchange.com/a/180516/209414) and updates thereof.
**Remarks**
Most content in reference was for older android versions and hence the reason for different commands and paths which I modified.
**Acknowledgements;**
* [Irvin H: Rooting the android emulator -on Android Studio 2.3((Android 4.4)](https://infosectrek.wordpress.com/2017/03/06/rooting-the-android-emulator/)
* [Android AVD root access fail.](https://github.com/idanr1986/cuckoo-droid/issues/4) | Use android image **without PlayServices** then you'll be able to run add root and access whatever you want. |
15,516,429 | I just want to create a dynamic URL. I am calling the listServices method and it is working as expected where as the getPortNumber which i am calling from listService is not working. I added dubug point in getPortNumber method. I am getting value for domainValue but I am not able to debug after $(document).ready(function(). The control directly goes to return portNumber and in the final URL i am getting the port number value as undefined. I checked and validated the port\_url (json file). my json file looks like this
```
{
"servers": [
{
"listeningPort": "6080",
"shutdownPort": "8180",
"redirectPort": "8443",
"sslPort": "8443",
"openWirePort": "61610",
"jmxPort": "9332",
"category": "Test A"
}
}
```
I got struck. I hope this issue is not becoz of calling javascript method from another method.
```
function getPortNumber()
{
var portNumber;
var domainValue = $("#domain").val();
$(document).ready(function() {
$.getJSON(port_url, function(result) {
$.each(result, function() {
$.each(this, function(k, v) {
if (v.category == domainValue) {
portNumber = v.listeningPort;
return false;
}
});
});
});
});
return portNumber;
}
function listServices()
{
$(document).ready(function() {
$("#list").text("");
var jList = $("#list");
var listOfServers = $("#servers").text();
var serverArray = listOfServers.split(",");
for (var i = 0; i < serverArray.length; i++)
{
var port = getPortNumber();
var tempURL = "http://"+serverArray[i].trim().toLowerCase()+".javaworkspace.com:"+port+"/services/listServices";
jList.append("<li><a href="+tempURL+" target='_blank'>"+tempURL+"</a></li>");
}
});
}
``` | 2013/03/20 | [
"https://Stackoverflow.com/questions/15516429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2189478/"
] | you don't need to call `document.ready` inside a function.....since (i bet) that function is called after document is ready...
remove that
```
function getPortNumber()
{
var portNumber;
var domainValue = $("#domain").val();
$.getJSON(port_url, function(result) {
$.each(result, function() {
$.each(this, function(k, v) {
if (v.category == domainValue) {
portNumber = v.listeningPort;
return false;
}
});
});
});
return portNumber;
}
```
and do the same for the other one.. | If some error exist there then it will skip.
Why you used `$(document).ready(function()` |
15,516,429 | I just want to create a dynamic URL. I am calling the listServices method and it is working as expected where as the getPortNumber which i am calling from listService is not working. I added dubug point in getPortNumber method. I am getting value for domainValue but I am not able to debug after $(document).ready(function(). The control directly goes to return portNumber and in the final URL i am getting the port number value as undefined. I checked and validated the port\_url (json file). my json file looks like this
```
{
"servers": [
{
"listeningPort": "6080",
"shutdownPort": "8180",
"redirectPort": "8443",
"sslPort": "8443",
"openWirePort": "61610",
"jmxPort": "9332",
"category": "Test A"
}
}
```
I got struck. I hope this issue is not becoz of calling javascript method from another method.
```
function getPortNumber()
{
var portNumber;
var domainValue = $("#domain").val();
$(document).ready(function() {
$.getJSON(port_url, function(result) {
$.each(result, function() {
$.each(this, function(k, v) {
if (v.category == domainValue) {
portNumber = v.listeningPort;
return false;
}
});
});
});
});
return portNumber;
}
function listServices()
{
$(document).ready(function() {
$("#list").text("");
var jList = $("#list");
var listOfServers = $("#servers").text();
var serverArray = listOfServers.split(",");
for (var i = 0; i < serverArray.length; i++)
{
var port = getPortNumber();
var tempURL = "http://"+serverArray[i].trim().toLowerCase()+".javaworkspace.com:"+port+"/services/listServices";
jList.append("<li><a href="+tempURL+" target='_blank'>"+tempURL+"</a></li>");
}
});
}
``` | 2013/03/20 | [
"https://Stackoverflow.com/questions/15516429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2189478/"
] | you don't need to call `document.ready` inside a function.....since (i bet) that function is called after document is ready...
remove that
```
function getPortNumber()
{
var portNumber;
var domainValue = $("#domain").val();
$.getJSON(port_url, function(result) {
$.each(result, function() {
$.each(this, function(k, v) {
if (v.category == domainValue) {
portNumber = v.listeningPort;
return false;
}
});
});
});
return portNumber;
}
```
and do the same for the other one.. | It sounds like you need to learn the art of stepping into callback functions in the javascript debugger. It doesn't quite work the simple way you'd like. It won't step into a callback function even thought the callback function looks like the logical next line of execution. Technically it isn't. When you say to step over a line of code, it steps over everything that line of code does including any callback functions that it calls.
When you step over `$(document).ready(function()` and the document is not yet ready, it does NOT execute the callback function and the debugger does not go into that function. So, if you want to see what happens when that callback function is actually executed, you have to manually put a breakpoint in that callback function. You can't just step into it line by line.
The same is true of your `$.getJSON(port_url, function(result) {` call and your `$.each()` call. When you say to step over the `$.each()` function, it literally steps over that function and onto the next line after that function. That skips the entire callback. If you want to step into the `$.each()`, you have to either manually set a breakpoint in the callback or you have to single step into the `$.each()` implementation in jQuery and watch it eventually call your callback.
So in this code:
```
function getPortNumber()
{
var portNumber;
var domainValue = $("#domain").val();
$(document).ready(function() {
$.getJSON(port_url, function(result) {
$.each(result, function() {
$.each(this, function(k, v) {
if (v.category == domainValue) {
portNumber = v.listeningPort;
return false;
}
});
});
});
});
return portNumber;
}
```
If you want to see what happens in the inner `$.each()` loop, you will have to set a breakpoint on this line `if (v.category == domainValue) {` and let the code run until it hits that breakpoint. Single stepping through getPortNumber() in the debugger will encounter problems at each of the four places that you use callback functions: `$(document).ready()`, `$.getJSON()`, `$.each()` and `$.each()`. So, to get inside of those, you will want to set a breakpoint inside them and let the code run until it hits that breakpoint. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.