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 |
|---|---|---|---|---|---|
42,469,945 | I have two input boxes on my form.
One is a dropdown select and the other is the textbox.
I need to update the textbox value depending on what is chosen on the select box.
For example, if I choose "1" on select box, the textbox value should have "299.00" and if I choose "2", the textbox value should be "399.0"
Can you help me on editing the code? Thank you in advanced.
Here is my html code:
```
<select style="width: 25%;height:25px;margin-left:15px;" onchange="ChooseContact(this)">
<option id="extra1" value='1'>1</option>
<option id="extra2" value='2'>2</option>
</select>
<input style="width: 25%;margin-left:15px;" id="extraper">
```
and here is the javascript:
```
function ChooseContact(data) {
var x = 0;
var y = 0;
var e = obj.id.toString();
if (e == 'tb1') {
x = Number("PHP 299");
y = document.getElementById ("extraper").value = x;
}
};
```
I'm sure that my javascript is wrong. Can you help me with it? | 2017/02/26 | [
"https://Stackoverflow.com/questions/42469945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7415564/"
] | The \* tells scanf to read in but ignore the input. Take a look at <http://www.cplusplus.com/reference/cstdio/scanf/> . why it always prints 67 you might need to step through a debugger to see what the int is initialized with and how that changes. | Use correct format specifiers for their respective data types
```
float %f
double %lf
int %d or %i
unsigned int %u
char %c
char * %s
long int %ld
long long int %lld
``` |
42,469,945 | I have two input boxes on my form.
One is a dropdown select and the other is the textbox.
I need to update the textbox value depending on what is chosen on the select box.
For example, if I choose "1" on select box, the textbox value should have "299.00" and if I choose "2", the textbox value should be "399.0"
Can you help me on editing the code? Thank you in advanced.
Here is my html code:
```
<select style="width: 25%;height:25px;margin-left:15px;" onchange="ChooseContact(this)">
<option id="extra1" value='1'>1</option>
<option id="extra2" value='2'>2</option>
</select>
<input style="width: 25%;margin-left:15px;" id="extraper">
```
and here is the javascript:
```
function ChooseContact(data) {
var x = 0;
var y = 0;
var e = obj.id.toString();
if (e == 'tb1') {
x = Number("PHP 299");
y = document.getElementById ("extraper").value = x;
}
};
```
I'm sure that my javascript is wrong. Can you help me with it? | 2017/02/26 | [
"https://Stackoverflow.com/questions/42469945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7415564/"
] | In the above program, the `scanf()` reads but does not assign the value due to the `*` format specifier. As a result, whatever is the value of a (which is not initialized) is produced as output by `printf()`. In this case, 67 is the garbage value. | Use correct format specifiers for their respective data types
```
float %f
double %lf
int %d or %i
unsigned int %u
char %c
char * %s
long int %ld
long long int %lld
``` |
73,859,557 | I'm trying to do this: I have an array of objects with the detail of a sale, with this format:
```
[
{
product:Banana,
quantity:34,
...(other fields)
},
{
product:Apple,
quantity:11,
...(other fields)
},
{
product:Banana,
quantity:15,
...(other fields)
},
{
product:Apple,
quantity:9,
...(other fields)
},
{
product:Orange,
quantity:7,
...(other fields)
}
]
```
From that array, I'd like to create a new one, with just one field by each product existing in the original array, and the total quantity of every product on the detail, like this:
```
[
{
product:Banana,
quantity:49 //(34 + 15) from the original array
},
{
product:Apple,
quantity:20 //(11 + 9) from the original array
},
{
product:Orange,
quantity:7 //Just 7 from the original array
}
]
```
Currently, I have this code which actually works (the variable names are in spanish):
```
const validarDetalle = async function (detalle) {
//'detalle' is the original array received by parameter
let error=false;
let arrayProductosCantidades=[]; //This is the new array which I'm generating
//I iterate on the original array with a for
for (const elemDetalle of detalle) {
console.log(elemDetalle);
//When the new array it's initially empty, I just concatenate
//the first product and quantity found on the original array to it
if(arrayProductosCantidades.length==0) {
arrayProductosCantidades=arrayProductosCantidades.concat(
{
producto:elemDetalle.producto,
cantidad:Number(elemDetalle.cantidad)
});
}
//If it isn't empty, I look if the product of the element
//of the original array
//where I'm standing already exists on the new array
else if(
(!arrayProductosCantidades.some (
function(productoCantidad) {
return (productoCantidad.producto == elemDetalle.producto)
}
)
)
)
{
//If it doesn't exists, I concatenate an element to the new array
//with the product and quantity of that element of the original array
arrayProductosCantidades=arrayProductosCantidades.concat(
{
producto:elemDetalle.producto,
cantidad:Number(elemDetalle.cantidad)
}
);
}
//If the product already exists on the new array,
//I create a variable 'elementoProductoCantidad' with the
//previous value of that element in the new array
else{
let elementoProductoCantidad=
arrayProductosCantidades.find (
function(productoCantidad) {
return(productoCantidad.producto == elemDetalle.producto)
}
);
//In that variable, I update the quantity field, adding to it the quantity
//of the element of the original array in where I'm standing
elementoProductoCantidad.cantidad += Number(elemDetalle.cantidad);
//After that, I delete the element of the new array with the old quantity value
arrayProductosCantidades=arrayProductosCantidades.filter(prodCant => prodCant.producto!=elemDetalle.producto);
//Finally I concatenate it again, with the quantity value updated
arrayProductosCantidades=arrayProductosCantidades.concat(elementoProductoCantidad);
}
}
console.log(arrayProductosCantidades);
//Once I've generated the new array, I make a validation for every product existing in my database
//(I should never get a negative stock in any product sold)
for (const elemProdCant of arrayProductosCantidades) {
const producto = await Number(elemProdCant.producto);
const cantidad = await Number(elemProdCant.cantidad);
let productoActualizado= await Producto.findById(elemProdCant.producto);
if(Number(productoActualizado.stock) - Number(cantidad) < 0) {
error=true;
}
}
return error;
}
```
Althrough this works fine, I think it should be a better way to do this in a functional way, using functions like map and reduce instead of for loops.
Does anyone have an idea if this it's possible and/or convenient?
Thank's a lot! | 2022/09/26 | [
"https://Stackoverflow.com/questions/73859557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13365958/"
] | This means that you are using an older version of PHP. Prior to PHP 8.0 locale setting affected the [conversion of floats to strings](https://wiki.php.net/rfc/locale_independent_float_to_string). This means that if you had a float and you used something like `echo` to output it out, the conversion to string would replace `.` with `,` for locales that use `,` for decimal separator. e.g.
```
setlocale(LC_ALL, "de_DE.UTF-8");
$number = 42.42;
echo $number; // outputs 42,42 in PHP 7
```
Once you upgrade to PHP 8 or newer, the output should be always the same irrespective of the locale.
---
As to why there's a difference between prepared and non-prepared queries in mysqli: mysqli prepared statements use a binary protocol (as opposed to textual) when talking to the database. This means that the data that arrives from MySQL is already an integer, float or string. It was decided that by default there will be no cast to a string. After all, what sense would that make? But to make the textual protocol compatible with binary one, an opt-in setting was added that would ask PHP to automatically cast numerical strings into PHP native integers and floats. You can enable that setting at any time by calling:
```
$mysqli->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE, true);
```
The binary protocol (prepared statements) ignores this setting.
I don't know why the setting is opt-in and not opt-out. PHP 8.1 changed this in PDO, but not in mysqli. | When you use the prepared statement, you're also using the MySQL Native Driver (MYSQLND). When it fetches MySQL `FLOAT` columns, by default it returns them as PHP floats rather than strings. So PHP's locale is used when formatting them.
This is controlled by the option `MYSQLI_OPT_INT_AND_FLOAT_NATIVE`. You can unset this to get strings as before.
```
$conn->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE, false);
```
Note that this has to be called between creating the `mysqli` object and connecting to the server. So you can't use `new mysqli`, you have to call `mysqli_init()` and `$conn->real_connect()`:
```
$conn = mysqli_init();
$conn->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE, true);
$conn->real_connect('server', 'user', 'pass', 'database');
``` |
56,368,620 | I have a flexbox, and elements in it are "p" elements.
I'm trying to align it right, but it's still not working and everything is still aligned center.
```css
.box1{
display: flex;
flex-direction: column;
text-align: right;
justify-content: space-between;
font-family: 'Merriweather', sans-serif;
font-size: 60px;
width: 30%;
}
```
Is it possible to align it right? | 2019/05/29 | [
"https://Stackoverflow.com/questions/56368620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9547590/"
] | `align-items: flex-end;` will align the `<p>` elements to the right side of the container, but only if the container's width is greater than the children's width.
```css
div {
width: 200px;
display: flex;
flex-direction: column;
align-items: flex-end;
box-sizing: border-box;
border: solid red 3px;
}
p {
width: 100px;
text-align: right; // you might also want to use this so that your text is aligned to the far right side.
box-sizing: border-box;
border: solid lime 3px;
}
```
```html
<div>
<p>Testing 1...</p>
<p>Testing 2...</p>
<p>Testing 3...</p>
<p>Testing 4...</p>
</div>
```
Flex boxes can be a bit tricky since the `justify-content` property always aligns content in the same direction of the flex box (i.e. vertically for columns and horizontally for rows), whereas `align-items` always aligns content in the cross direction (i.e. horizontally for columns and vertically for rows). For example...
```
display: flex;
flex-direction: column;
justify-content:; /* aligns content vertically */
align-items:; /* aligns content horizontally */
display: flex;
/* flex-direction: row; is the default value */
justify-content:; /* aligns content horizontally */
align-items:; /* aligns content vertically */
``` | Apply the text-align to the paragraphs:
```
.box1 p {
text-align: right;
}
``` |
140,046 | I am running many tasks on a Linux cluster. Each task creates many output files. When all tasks are finished, I run something like `tar cf foo.tar output_files/`to create a `tar` archive. This is a very slow process since there are many thousands of files and directories.
Is there any way to do this in parallel as the output files are being created?
Is it possible to have multiple `tar` processes, spread across multiple machines, all adding their files to the same archive at once?
The cluster has a shared filesystem.
I am not interested in compression since it slows things down even more, and because all of the input files are themselves already compressed. Ideally the output would be a `tar` file, but I would consider other archive formats as well. | 2014/06/30 | [
"https://unix.stackexchange.com/questions/140046",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/-1/"
] | You can't have multiple processes adding to the same tar archive (or any other usual archive format, compressed or not). Each file is stored contiguously, and there is no way to insert data in a file, only to append or overwrite, so continuing to write to a file that isn't the last one would overwrite subsequent files.
If you know the file size in advance, you could reserve the size in the tar archive and have the program keep writing. That would require a lot of coding: it's a very unusual thing to do.
Unix has a feature designed to accommodate a group of files that are written to independently. It's called a directory.
There are very few cases where you'd gain anything from an uncompressed archive over a directory. Reading it might be slightly faster in some circumstances; this is an intrinsic consequence of the directory format (where each file entry is a pointer to its content) as opposed to the archive format (where each file entry is its content directly), which is precisely what makes it possible to build the directory piecewise. Transforming a directory tree to an archive is post-processing that needs to be done sequentially. | You can start the creation of the final `tar` file before all output files are created: Maybe that achieves the speed up you want.
You can call tar this way:
```
tar -cf foo.tar -T file-list
```
`file-list` would be a FIFO. You need a script which detects
1. new files in the source directory (`inotifywatch`)
2. when each of these new files is finished (`fuser`)
If a file is finished then its path is written to the FIFO. Maybe it is useful not to create an archive with completely mixed paths. You can start with the directory which gets the first input file and add new directories only after their last file has been finished (create a flag file after the respective process has been finished). The first approach has the advantage that probably the file is completely in the cache yet. |
140,046 | I am running many tasks on a Linux cluster. Each task creates many output files. When all tasks are finished, I run something like `tar cf foo.tar output_files/`to create a `tar` archive. This is a very slow process since there are many thousands of files and directories.
Is there any way to do this in parallel as the output files are being created?
Is it possible to have multiple `tar` processes, spread across multiple machines, all adding their files to the same archive at once?
The cluster has a shared filesystem.
I am not interested in compression since it slows things down even more, and because all of the input files are themselves already compressed. Ideally the output would be a `tar` file, but I would consider other archive formats as well. | 2014/06/30 | [
"https://unix.stackexchange.com/questions/140046",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/-1/"
] | You can't have multiple processes adding to the same tar archive (or any other usual archive format, compressed or not). Each file is stored contiguously, and there is no way to insert data in a file, only to append or overwrite, so continuing to write to a file that isn't the last one would overwrite subsequent files.
If you know the file size in advance, you could reserve the size in the tar archive and have the program keep writing. That would require a lot of coding: it's a very unusual thing to do.
Unix has a feature designed to accommodate a group of files that are written to independently. It's called a directory.
There are very few cases where you'd gain anything from an uncompressed archive over a directory. Reading it might be slightly faster in some circumstances; this is an intrinsic consequence of the directory format (where each file entry is a pointer to its content) as opposed to the archive format (where each file entry is its content directly), which is precisely what makes it possible to build the directory piecewise. Transforming a directory tree to an archive is post-processing that needs to be done sequentially. | GNU tar has --append:
```
tar -f foo.tar --append newfiles
```
Unfortunately it reads the full tar file. |
140,046 | I am running many tasks on a Linux cluster. Each task creates many output files. When all tasks are finished, I run something like `tar cf foo.tar output_files/`to create a `tar` archive. This is a very slow process since there are many thousands of files and directories.
Is there any way to do this in parallel as the output files are being created?
Is it possible to have multiple `tar` processes, spread across multiple machines, all adding their files to the same archive at once?
The cluster has a shared filesystem.
I am not interested in compression since it slows things down even more, and because all of the input files are themselves already compressed. Ideally the output would be a `tar` file, but I would consider other archive formats as well. | 2014/06/30 | [
"https://unix.stackexchange.com/questions/140046",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/-1/"
] | You can start the creation of the final `tar` file before all output files are created: Maybe that achieves the speed up you want.
You can call tar this way:
```
tar -cf foo.tar -T file-list
```
`file-list` would be a FIFO. You need a script which detects
1. new files in the source directory (`inotifywatch`)
2. when each of these new files is finished (`fuser`)
If a file is finished then its path is written to the FIFO. Maybe it is useful not to create an archive with completely mixed paths. You can start with the directory which gets the first input file and add new directories only after their last file has been finished (create a flag file after the respective process has been finished). The first approach has the advantage that probably the file is completely in the cache yet. | GNU tar has --append:
```
tar -f foo.tar --append newfiles
```
Unfortunately it reads the full tar file. |
47,923,668 | I am using `Laravel Framework 5.5.26` and I am querying my db with the following call:
```
$symbolsArray = DB::table('exchanges')
->join('markets', 'exchanges.id', '=', 'markets.exchanges_id')
->where('name', $exchangeName)
->get(array(
'symbol',
));
```
If I `var_dump($symbolsArray)` I get the following output:
```
class Illuminate\Support\Collection#619 (1) {
protected $items =>
array(99) {
[0] =>
class stdClass#626 (1) {
public $symbol =>
string(7) "BCN/BTC"
}
[1] =>
class stdClass#621 (1) {
public $symbol =>
string(8) "BELA/BTC"
}
[2] =>
class stdClass#623 (1) {
public $symbol =>
string(7) "BLK/BTC"
}
[3] =>
class stdClass#627 (1) {
public $symbol =>
string(8) "BTCD/BTC"
}
...
}
}
```
I am trying to get the `$symbol` like the following:
`$symbolsArray[$key]['symbol']`
However, I get the following error:
```
Cannot use object of type stdClass as array
```
Any suggestions how to access the `symbol` from the query output? | 2017/12/21 | [
"https://Stackoverflow.com/questions/47923668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2847689/"
] | It's a collection of objects, not arrays. So you need to use this syntax to get property of an object in a collection:
```
$symbolsArray[$key]->symbol
```
If you need to get just symbols, use `pluck()` instead of `get()`:
```
->pluck('symbol')->toArray()
``` | **Simple convert given output as an array like shown below**
```
$symbolsArray = DB::table('exchanges')
->join('markets', 'exchanges.id', '=', 'markets.exchanges_id')
->where('name', $exchangeName)
->get(array(
'symbol',
))->toArray(); // get data as array not object
``` |
47,923,668 | I am using `Laravel Framework 5.5.26` and I am querying my db with the following call:
```
$symbolsArray = DB::table('exchanges')
->join('markets', 'exchanges.id', '=', 'markets.exchanges_id')
->where('name', $exchangeName)
->get(array(
'symbol',
));
```
If I `var_dump($symbolsArray)` I get the following output:
```
class Illuminate\Support\Collection#619 (1) {
protected $items =>
array(99) {
[0] =>
class stdClass#626 (1) {
public $symbol =>
string(7) "BCN/BTC"
}
[1] =>
class stdClass#621 (1) {
public $symbol =>
string(8) "BELA/BTC"
}
[2] =>
class stdClass#623 (1) {
public $symbol =>
string(7) "BLK/BTC"
}
[3] =>
class stdClass#627 (1) {
public $symbol =>
string(8) "BTCD/BTC"
}
...
}
}
```
I am trying to get the `$symbol` like the following:
`$symbolsArray[$key]['symbol']`
However, I get the following error:
```
Cannot use object of type stdClass as array
```
Any suggestions how to access the `symbol` from the query output? | 2017/12/21 | [
"https://Stackoverflow.com/questions/47923668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2847689/"
] | It's a collection of objects, not arrays. So you need to use this syntax to get property of an object in a collection:
```
$symbolsArray[$key]->symbol
```
If you need to get just symbols, use `pluck()` instead of `get()`:
```
->pluck('symbol')->toArray()
``` | The result of DB::table()->get() is always a [Collection](https://laravel.com/docs/5.5/eloquent-collections), whose attributes you access like variables within a PHP class with `->`.
In your example, your `$symbolsArray` is not actually an array, you access the content with `$symbolsArray[$key]->symbol`.
Assuming that you are new to Laravel, I suggest you have a look at Laravel's built in ORM [Eloquent](https://laravel.com/docs/5.5/eloquent "Eloqent"). It makes working with Databases easy and straightforward, and if you dive a bit into Eloquent's Collections you will see that they make working with data a breeze. |
47,923,668 | I am using `Laravel Framework 5.5.26` and I am querying my db with the following call:
```
$symbolsArray = DB::table('exchanges')
->join('markets', 'exchanges.id', '=', 'markets.exchanges_id')
->where('name', $exchangeName)
->get(array(
'symbol',
));
```
If I `var_dump($symbolsArray)` I get the following output:
```
class Illuminate\Support\Collection#619 (1) {
protected $items =>
array(99) {
[0] =>
class stdClass#626 (1) {
public $symbol =>
string(7) "BCN/BTC"
}
[1] =>
class stdClass#621 (1) {
public $symbol =>
string(8) "BELA/BTC"
}
[2] =>
class stdClass#623 (1) {
public $symbol =>
string(7) "BLK/BTC"
}
[3] =>
class stdClass#627 (1) {
public $symbol =>
string(8) "BTCD/BTC"
}
...
}
}
```
I am trying to get the `$symbol` like the following:
`$symbolsArray[$key]['symbol']`
However, I get the following error:
```
Cannot use object of type stdClass as array
```
Any suggestions how to access the `symbol` from the query output? | 2017/12/21 | [
"https://Stackoverflow.com/questions/47923668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2847689/"
] | It's a collection of objects, not arrays. So you need to use this syntax to get property of an object in a collection:
```
$symbolsArray[$key]->symbol
```
If you need to get just symbols, use `pluck()` instead of `get()`:
```
->pluck('symbol')->toArray()
``` | $symbolsArray is a collection and not an array. The get an array, you could pluck symbol from the collection `$symbolsArray = DB::table('exchanges')
->join('markets', 'exchanges.id', '=', 'markets.exchanges_id')
->where('name', $exchangeName)
->pluck('symbol')->all();` or you could actually convert your collection to an array by `$new_array = $symbolsArray->toArray()` |
47,923,668 | I am using `Laravel Framework 5.5.26` and I am querying my db with the following call:
```
$symbolsArray = DB::table('exchanges')
->join('markets', 'exchanges.id', '=', 'markets.exchanges_id')
->where('name', $exchangeName)
->get(array(
'symbol',
));
```
If I `var_dump($symbolsArray)` I get the following output:
```
class Illuminate\Support\Collection#619 (1) {
protected $items =>
array(99) {
[0] =>
class stdClass#626 (1) {
public $symbol =>
string(7) "BCN/BTC"
}
[1] =>
class stdClass#621 (1) {
public $symbol =>
string(8) "BELA/BTC"
}
[2] =>
class stdClass#623 (1) {
public $symbol =>
string(7) "BLK/BTC"
}
[3] =>
class stdClass#627 (1) {
public $symbol =>
string(8) "BTCD/BTC"
}
...
}
}
```
I am trying to get the `$symbol` like the following:
`$symbolsArray[$key]['symbol']`
However, I get the following error:
```
Cannot use object of type stdClass as array
```
Any suggestions how to access the `symbol` from the query output? | 2017/12/21 | [
"https://Stackoverflow.com/questions/47923668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2847689/"
] | **Simple convert given output as an array like shown below**
```
$symbolsArray = DB::table('exchanges')
->join('markets', 'exchanges.id', '=', 'markets.exchanges_id')
->where('name', $exchangeName)
->get(array(
'symbol',
))->toArray(); // get data as array not object
``` | $symbolsArray is a collection and not an array. The get an array, you could pluck symbol from the collection `$symbolsArray = DB::table('exchanges')
->join('markets', 'exchanges.id', '=', 'markets.exchanges_id')
->where('name', $exchangeName)
->pluck('symbol')->all();` or you could actually convert your collection to an array by `$new_array = $symbolsArray->toArray()` |
47,923,668 | I am using `Laravel Framework 5.5.26` and I am querying my db with the following call:
```
$symbolsArray = DB::table('exchanges')
->join('markets', 'exchanges.id', '=', 'markets.exchanges_id')
->where('name', $exchangeName)
->get(array(
'symbol',
));
```
If I `var_dump($symbolsArray)` I get the following output:
```
class Illuminate\Support\Collection#619 (1) {
protected $items =>
array(99) {
[0] =>
class stdClass#626 (1) {
public $symbol =>
string(7) "BCN/BTC"
}
[1] =>
class stdClass#621 (1) {
public $symbol =>
string(8) "BELA/BTC"
}
[2] =>
class stdClass#623 (1) {
public $symbol =>
string(7) "BLK/BTC"
}
[3] =>
class stdClass#627 (1) {
public $symbol =>
string(8) "BTCD/BTC"
}
...
}
}
```
I am trying to get the `$symbol` like the following:
`$symbolsArray[$key]['symbol']`
However, I get the following error:
```
Cannot use object of type stdClass as array
```
Any suggestions how to access the `symbol` from the query output? | 2017/12/21 | [
"https://Stackoverflow.com/questions/47923668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2847689/"
] | The result of DB::table()->get() is always a [Collection](https://laravel.com/docs/5.5/eloquent-collections), whose attributes you access like variables within a PHP class with `->`.
In your example, your `$symbolsArray` is not actually an array, you access the content with `$symbolsArray[$key]->symbol`.
Assuming that you are new to Laravel, I suggest you have a look at Laravel's built in ORM [Eloquent](https://laravel.com/docs/5.5/eloquent "Eloqent"). It makes working with Databases easy and straightforward, and if you dive a bit into Eloquent's Collections you will see that they make working with data a breeze. | $symbolsArray is a collection and not an array. The get an array, you could pluck symbol from the collection `$symbolsArray = DB::table('exchanges')
->join('markets', 'exchanges.id', '=', 'markets.exchanges_id')
->where('name', $exchangeName)
->pluck('symbol')->all();` or you could actually convert your collection to an array by `$new_array = $symbolsArray->toArray()` |
48,485,117 | I want to use some of the icons from font awesome rather than google's material icons, however the font awesome icons do not line up correctly in a link collection.
```
<div class="col s12 m4 l3 xl2">
<div class="collection with-header white">
<h6 class="collection-header"><i class=" material-icons left">insert_link</i>Links</h6>
<!-- Font Awesome Icon -->
<a href="#!" class="collection-item orange-text valign-wrapper"><i class="fab fa-github fa-2x left"></i>Font Awesome</a>
<!-- Material Icon -->
<a href="#!" class="collection-item orange-text"><i class="material-icons left">insert_chart</i>Material Icons</a>
</div>
</div>
```
The material icon leaves a nice gap to the text, but the font awesome icon doesn't.
[](https://i.stack.imgur.com/LsmX6.png) | 2018/01/28 | [
"https://Stackoverflow.com/questions/48485117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6126468/"
] | Try to give some width to the icons. And as I see you don't need to use `.left` class to the icons.
Simply use `display:inline-block` and `vertical-align:middle;`
***Stack Snippet***
```css
.collection i {
width: 40px;
vertical-align: middle;
display: inline-block;
}
```
```html
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css">
<div class="col s12 m4 l3 xl2">
<div class="collection with-header white">
<h6 class="collection-header"><i class=" material-icons">insert_link</i>Links</h6>
<a href="#!" class="collection-item orange-text valign-wrapper"><i class="fab fa-github fa-2x"></i>Font Awesome</a>
<a href="#!" class="collection-item orange-text"><i class="material-icons">insert_chart</i>Material Icons</a>
</div>
</div>
``` | Adding CSS fixed the issue by putting a margin next to the font-awesome icons
```
.fa-2x {
margin-right: 15px;
}
``` |
18,483,443 | I'm using `meteor.js` and I just went to change some of the HTML output in the .html file only and it started giving me the error:
>
> Error: database names cannot contain the character '.'
>
>
>
I haven't changed anything, the only thing I recall doing inbetween is starting a new project which I created using meteor.js, which then updated meteor and now I have this problem.
Rest of error details:
>
> Error: database names cannot contain the character '.'
>
>
> W20130828-09:52:22.049(1)? (STDERR) at validateDatabaseName (/Users/jumpingcode/.meteor/packages/mongo-livedata/86ae77f282/npm/node\_modules/mongodb/lib/mongodb/db.js:216:59)
>
>
> W20130828-09:52:22.050(1)? (STDERR) at new Db (/Users/jumpingcode/.meteor/packages/mongo-livedata/86ae77f282/npm/node\_modules/mongodb/lib/mongodb/db.js:90:3)
>
>
> W20130828-09:52:22.050(1)? (STDERR) at MongoClient.connect.connectFunction (/Users/jumpingcode/.meteor/packages/mongo-livedata/86ae77f282/npm/node\_modules/mongodb/lib/mongodb/mongo\_client.js:238:29)
>
>
> W20130828-09:52:22.050(1)? (STDERR) at Function.MongoClient.connect (/Users/jumpingcode/.meteor/packages/mongo-livedata/86ae77f282/npm/node\_modules/mongodb/lib/mongodb/mongo\_client.js:291:5)
>
>
> W20130828-09:52:22.050(1)? (STDERR) at Function.Db.connect (/Users/jumpingcode/.meteor/packages/mongo-livedata/86ae77f282/npm/node\_modules/mongodb/lib/mongodb/db.js:1854:23)
>
>
> W20130828-09:52:22.051(1)? (STDERR) at new MongoConnection (packages/mongo-livedata/mongo\_driver.js:113)
>
>
> W20130828-09:52:22.051(1)? (STDERR) at new MongoInternals.RemoteCollectionDriver (packages/mongo-livedata/remote\_collection\_driver.js:3)
>
>
> W20130828-09:52:22.051(1)? (STDERR) at Object. (packages/mongo-livedata/remote\_collection\_driver.js:34)
>
>
> W20130828-09:52:22.051(1)? (STDERR) at Object.\_.once [as defaultRemoteCollectionDriver] (packages/underscore/underscore.js:704)
>
>
> W20130828-09:52:22.053(1)? (STDERR) at new Meteor.Collection (packages/mongo-livedata/collection.js:66)
>
>
> | 2013/08/28 | [
"https://Stackoverflow.com/questions/18483443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/849843/"
] | Have a look at your collection in `.meteor/local/db` to see if any files were added in.
If it really still continues you could use `meteor reset` but it would clear your database.
The issue arises from mongodb, because `.` notation lets you peak inside objects in javascript the character is reserved and can't be used as a collection or database name.
If there is any environmental variable that you've used it could also cause the issue with a new typo or something. Try using just `meteor` like you usually would in a fresh terminal window. | when I use expressjs with mongoose, above error was occured.It resolve by doing
1.create a database.js file
make a exportble database configuration inside it as follows
```
module.exports = {database : "mongodb://myUsername:myPassword@ds161039.mlab.com:61039/accounttest"};
```
2.Require it to your current JS file
```
var connection = mongoose.connect(config.database);
``` |
6,323 | I recently "upgraded" to a [Romin Comp Gel](http://www.specialized.com/us/en/bc/SBCEqProduct.jsp?spid=53997) saddle from a soft racing saddle because my old one, while extremely comfortable on long road rides, wasn't working for the TT position I'm now practicing for an upcoming Ironman.
I've been professionally fit with the seat, so I think things are lined up well. I've ridden nearly 200 miles over the last week with it and the problem is: it still freaking hurts. It's not chafing; it's pressure right in that, uh, under-area that's supposed to sit in the gap of the saddle.
Can I expect it to get awesome any time soon, or should I try another saddle at this point?
**Edit:**
Regarding seat position, I have my current seat *all the way forward*, which is where I've been steadily moving it over the last two weeks since my professional fitting. Moving it forward did help, but now I'm stuck again (and I have one of those bent seatposts that is pointing forward as well). | 2011/09/30 | [
"https://bicycles.stackexchange.com/questions/6323",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/1044/"
] | That saddle is unlikely to adjust to you. Man-made materials generally don't budge. You may want to try a Brooks or other leather saddle. If you do, apply the saddle dressing that should come with it, and don't do long rides on it for a few weeks. I've found that two or three weeks of commuting (25 km round-trip) usually does the job.
If you are a woman, your pelvic bones are probably wider, and you'll want a saddle designed for women. Presumably the bike shop already took that into consideration, but I've seen a shop or two where the staff didn't know about this basic issue. | Having your saddle straight ahead is not always best either. Every body is different - I'd urge you to set up your bike to fit your actual body, not some aesthetic ideal of "supposed to be\_***\_***. " |
6,323 | I recently "upgraded" to a [Romin Comp Gel](http://www.specialized.com/us/en/bc/SBCEqProduct.jsp?spid=53997) saddle from a soft racing saddle because my old one, while extremely comfortable on long road rides, wasn't working for the TT position I'm now practicing for an upcoming Ironman.
I've been professionally fit with the seat, so I think things are lined up well. I've ridden nearly 200 miles over the last week with it and the problem is: it still freaking hurts. It's not chafing; it's pressure right in that, uh, under-area that's supposed to sit in the gap of the saddle.
Can I expect it to get awesome any time soon, or should I try another saddle at this point?
**Edit:**
Regarding seat position, I have my current seat *all the way forward*, which is where I've been steadily moving it over the last two weeks since my professional fitting. Moving it forward did help, but now I'm stuck again (and I have one of those bent seatposts that is pointing forward as well). | 2011/09/30 | [
"https://bicycles.stackexchange.com/questions/6323",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/1044/"
] | [This question](https://bicycles.stackexchange.com/questions/5906/adjusting-saddle-angle-on-a-road-bike-drop-bars/5922#5922) was answered by a suggestion to slide the saddle forwards on the seat post. You could give that a try.
I doubt you'll get used to an existing, uncomfortable saddle position. I don't think that part of your anatomy will 'toughen up'. | It's vital to adjust your bike to fit your body from the start if you want to keep appropriate alignment and avoid physical difficulties. This will also help you stay comfortable during your bike ride. Setting your [bike seat](https://www.bikeshepherd.org/how-to-make-my-bike-seat-more-comfortable/) to the same height as your hip bones is a good idea. |
6,323 | I recently "upgraded" to a [Romin Comp Gel](http://www.specialized.com/us/en/bc/SBCEqProduct.jsp?spid=53997) saddle from a soft racing saddle because my old one, while extremely comfortable on long road rides, wasn't working for the TT position I'm now practicing for an upcoming Ironman.
I've been professionally fit with the seat, so I think things are lined up well. I've ridden nearly 200 miles over the last week with it and the problem is: it still freaking hurts. It's not chafing; it's pressure right in that, uh, under-area that's supposed to sit in the gap of the saddle.
Can I expect it to get awesome any time soon, or should I try another saddle at this point?
**Edit:**
Regarding seat position, I have my current seat *all the way forward*, which is where I've been steadily moving it over the last two weeks since my professional fitting. Moving it forward did help, but now I'm stuck again (and I have one of those bent seatposts that is pointing forward as well). | 2011/09/30 | [
"https://bicycles.stackexchange.com/questions/6323",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/1044/"
] | Take it back and get a different one. A decent bike shop will let you do this. I went through 3 saddles the last time.
The goal is that the "saddle fits you", and not, "you fit the saddle".
>
> It really doesn't take weeks.
>
>
>
to determine whether a saddle is right or not! A long ride will do.
*An anecdotal note... My current road bike saddle would qualify as a "hard leather saddle". At the time I bought the bike, I didn't like the original saddle, then tried a Specialized, then a Fizik, and then settled on a Selle Italia. I'm not knocking either Specialized or Fizik or any other brand; it's just that the Selle Italia saddle worked for my anatomy, and I often spend an entire day+ sitting on that saddle. Saddles are like shoes, they have to fit the wearer. A 30 mile ride told me which saddle to get.* | [This question](https://bicycles.stackexchange.com/questions/5906/adjusting-saddle-angle-on-a-road-bike-drop-bars/5922#5922) was answered by a suggestion to slide the saddle forwards on the seat post. You could give that a try.
I doubt you'll get used to an existing, uncomfortable saddle position. I don't think that part of your anatomy will 'toughen up'. |
6,323 | I recently "upgraded" to a [Romin Comp Gel](http://www.specialized.com/us/en/bc/SBCEqProduct.jsp?spid=53997) saddle from a soft racing saddle because my old one, while extremely comfortable on long road rides, wasn't working for the TT position I'm now practicing for an upcoming Ironman.
I've been professionally fit with the seat, so I think things are lined up well. I've ridden nearly 200 miles over the last week with it and the problem is: it still freaking hurts. It's not chafing; it's pressure right in that, uh, under-area that's supposed to sit in the gap of the saddle.
Can I expect it to get awesome any time soon, or should I try another saddle at this point?
**Edit:**
Regarding seat position, I have my current seat *all the way forward*, which is where I've been steadily moving it over the last two weeks since my professional fitting. Moving it forward did help, but now I'm stuck again (and I have one of those bent seatposts that is pointing forward as well). | 2011/09/30 | [
"https://bicycles.stackexchange.com/questions/6323",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/1044/"
] | [This question](https://bicycles.stackexchange.com/questions/5906/adjusting-saddle-angle-on-a-road-bike-drop-bars/5922#5922) was answered by a suggestion to slide the saddle forwards on the seat post. You could give that a try.
I doubt you'll get used to an existing, uncomfortable saddle position. I don't think that part of your anatomy will 'toughen up'. | I dont't know that saddle model but, as always, the answer is really subjective. It could also be *forever*.
My suggestion is to try a saddle before buying and buy always the better shorts you can afford. |
6,323 | I recently "upgraded" to a [Romin Comp Gel](http://www.specialized.com/us/en/bc/SBCEqProduct.jsp?spid=53997) saddle from a soft racing saddle because my old one, while extremely comfortable on long road rides, wasn't working for the TT position I'm now practicing for an upcoming Ironman.
I've been professionally fit with the seat, so I think things are lined up well. I've ridden nearly 200 miles over the last week with it and the problem is: it still freaking hurts. It's not chafing; it's pressure right in that, uh, under-area that's supposed to sit in the gap of the saddle.
Can I expect it to get awesome any time soon, or should I try another saddle at this point?
**Edit:**
Regarding seat position, I have my current seat *all the way forward*, which is where I've been steadily moving it over the last two weeks since my professional fitting. Moving it forward did help, but now I'm stuck again (and I have one of those bent seatposts that is pointing forward as well). | 2011/09/30 | [
"https://bicycles.stackexchange.com/questions/6323",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/1044/"
] | That saddle is unlikely to adjust to you. Man-made materials generally don't budge. You may want to try a Brooks or other leather saddle. If you do, apply the saddle dressing that should come with it, and don't do long rides on it for a few weeks. I've found that two or three weeks of commuting (25 km round-trip) usually does the job.
If you are a woman, your pelvic bones are probably wider, and you'll want a saddle designed for women. Presumably the bike shop already took that into consideration, but I've seen a shop or two where the staff didn't know about this basic issue. | I dont't know that saddle model but, as always, the answer is really subjective. It could also be *forever*.
My suggestion is to try a saddle before buying and buy always the better shorts you can afford. |
6,323 | I recently "upgraded" to a [Romin Comp Gel](http://www.specialized.com/us/en/bc/SBCEqProduct.jsp?spid=53997) saddle from a soft racing saddle because my old one, while extremely comfortable on long road rides, wasn't working for the TT position I'm now practicing for an upcoming Ironman.
I've been professionally fit with the seat, so I think things are lined up well. I've ridden nearly 200 miles over the last week with it and the problem is: it still freaking hurts. It's not chafing; it's pressure right in that, uh, under-area that's supposed to sit in the gap of the saddle.
Can I expect it to get awesome any time soon, or should I try another saddle at this point?
**Edit:**
Regarding seat position, I have my current seat *all the way forward*, which is where I've been steadily moving it over the last two weeks since my professional fitting. Moving it forward did help, but now I'm stuck again (and I have one of those bent seatposts that is pointing forward as well). | 2011/09/30 | [
"https://bicycles.stackexchange.com/questions/6323",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/1044/"
] | Take it back and get a different one. A decent bike shop will let you do this. I went through 3 saddles the last time.
The goal is that the "saddle fits you", and not, "you fit the saddle".
>
> It really doesn't take weeks.
>
>
>
to determine whether a saddle is right or not! A long ride will do.
*An anecdotal note... My current road bike saddle would qualify as a "hard leather saddle". At the time I bought the bike, I didn't like the original saddle, then tried a Specialized, then a Fizik, and then settled on a Selle Italia. I'm not knocking either Specialized or Fizik or any other brand; it's just that the Selle Italia saddle worked for my anatomy, and I often spend an entire day+ sitting on that saddle. Saddles are like shoes, they have to fit the wearer. A 30 mile ride told me which saddle to get.* | It's vital to adjust your bike to fit your body from the start if you want to keep appropriate alignment and avoid physical difficulties. This will also help you stay comfortable during your bike ride. Setting your [bike seat](https://www.bikeshepherd.org/how-to-make-my-bike-seat-more-comfortable/) to the same height as your hip bones is a good idea. |
6,323 | I recently "upgraded" to a [Romin Comp Gel](http://www.specialized.com/us/en/bc/SBCEqProduct.jsp?spid=53997) saddle from a soft racing saddle because my old one, while extremely comfortable on long road rides, wasn't working for the TT position I'm now practicing for an upcoming Ironman.
I've been professionally fit with the seat, so I think things are lined up well. I've ridden nearly 200 miles over the last week with it and the problem is: it still freaking hurts. It's not chafing; it's pressure right in that, uh, under-area that's supposed to sit in the gap of the saddle.
Can I expect it to get awesome any time soon, or should I try another saddle at this point?
**Edit:**
Regarding seat position, I have my current seat *all the way forward*, which is where I've been steadily moving it over the last two weeks since my professional fitting. Moving it forward did help, but now I'm stuck again (and I have one of those bent seatposts that is pointing forward as well). | 2011/09/30 | [
"https://bicycles.stackexchange.com/questions/6323",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/1044/"
] | Take it back and get a different one. A decent bike shop will let you do this. I went through 3 saddles the last time.
The goal is that the "saddle fits you", and not, "you fit the saddle".
>
> It really doesn't take weeks.
>
>
>
to determine whether a saddle is right or not! A long ride will do.
*An anecdotal note... My current road bike saddle would qualify as a "hard leather saddle". At the time I bought the bike, I didn't like the original saddle, then tried a Specialized, then a Fizik, and then settled on a Selle Italia. I'm not knocking either Specialized or Fizik or any other brand; it's just that the Selle Italia saddle worked for my anatomy, and I often spend an entire day+ sitting on that saddle. Saddles are like shoes, they have to fit the wearer. A 30 mile ride told me which saddle to get.* | Having your saddle straight ahead is not always best either. Every body is different - I'd urge you to set up your bike to fit your actual body, not some aesthetic ideal of "supposed to be\_***\_***. " |
6,323 | I recently "upgraded" to a [Romin Comp Gel](http://www.specialized.com/us/en/bc/SBCEqProduct.jsp?spid=53997) saddle from a soft racing saddle because my old one, while extremely comfortable on long road rides, wasn't working for the TT position I'm now practicing for an upcoming Ironman.
I've been professionally fit with the seat, so I think things are lined up well. I've ridden nearly 200 miles over the last week with it and the problem is: it still freaking hurts. It's not chafing; it's pressure right in that, uh, under-area that's supposed to sit in the gap of the saddle.
Can I expect it to get awesome any time soon, or should I try another saddle at this point?
**Edit:**
Regarding seat position, I have my current seat *all the way forward*, which is where I've been steadily moving it over the last two weeks since my professional fitting. Moving it forward did help, but now I'm stuck again (and I have one of those bent seatposts that is pointing forward as well). | 2011/09/30 | [
"https://bicycles.stackexchange.com/questions/6323",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/1044/"
] | Take it back and get a different one. A decent bike shop will let you do this. I went through 3 saddles the last time.
The goal is that the "saddle fits you", and not, "you fit the saddle".
>
> It really doesn't take weeks.
>
>
>
to determine whether a saddle is right or not! A long ride will do.
*An anecdotal note... My current road bike saddle would qualify as a "hard leather saddle". At the time I bought the bike, I didn't like the original saddle, then tried a Specialized, then a Fizik, and then settled on a Selle Italia. I'm not knocking either Specialized or Fizik or any other brand; it's just that the Selle Italia saddle worked for my anatomy, and I often spend an entire day+ sitting on that saddle. Saddles are like shoes, they have to fit the wearer. A 30 mile ride told me which saddle to get.* | It can take a few weeks to get used to a new saddle, or other components, but if adjusted properly they should be 'uncomfortable', not 'freaking hurts' painful.
When it comes to saddles, even after a professional fit you may need to make adjustments at home. Using a grease pencil or other means of marking the position you can start by doing two things likely to help:
1. Decrease the nose angle a few degrees. This could be especially helpful since in a time-trial position most riders are inclined closer to horizontal an this can significantly increase the pressure on the perineum.
2. Move the saddle a few millimeters forward. This compensates for the tendency to slide slightly forward when in the drops or on your aero-bars, and helps keep the saddle pressure on your sit bones.
Finally, you may want to use a small plumb bob to make sure that the nose is centered left to right over the top tube. Again, in a TT position small deviations can make a big difference. |
6,323 | I recently "upgraded" to a [Romin Comp Gel](http://www.specialized.com/us/en/bc/SBCEqProduct.jsp?spid=53997) saddle from a soft racing saddle because my old one, while extremely comfortable on long road rides, wasn't working for the TT position I'm now practicing for an upcoming Ironman.
I've been professionally fit with the seat, so I think things are lined up well. I've ridden nearly 200 miles over the last week with it and the problem is: it still freaking hurts. It's not chafing; it's pressure right in that, uh, under-area that's supposed to sit in the gap of the saddle.
Can I expect it to get awesome any time soon, or should I try another saddle at this point?
**Edit:**
Regarding seat position, I have my current seat *all the way forward*, which is where I've been steadily moving it over the last two weeks since my professional fitting. Moving it forward did help, but now I'm stuck again (and I have one of those bent seatposts that is pointing forward as well). | 2011/09/30 | [
"https://bicycles.stackexchange.com/questions/6323",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/1044/"
] | Take it back and get a different one. A decent bike shop will let you do this. I went through 3 saddles the last time.
The goal is that the "saddle fits you", and not, "you fit the saddle".
>
> It really doesn't take weeks.
>
>
>
to determine whether a saddle is right or not! A long ride will do.
*An anecdotal note... My current road bike saddle would qualify as a "hard leather saddle". At the time I bought the bike, I didn't like the original saddle, then tried a Specialized, then a Fizik, and then settled on a Selle Italia. I'm not knocking either Specialized or Fizik or any other brand; it's just that the Selle Italia saddle worked for my anatomy, and I often spend an entire day+ sitting on that saddle. Saddles are like shoes, they have to fit the wearer. A 30 mile ride told me which saddle to get.* | I dont't know that saddle model but, as always, the answer is really subjective. It could also be *forever*.
My suggestion is to try a saddle before buying and buy always the better shorts you can afford. |
6,323 | I recently "upgraded" to a [Romin Comp Gel](http://www.specialized.com/us/en/bc/SBCEqProduct.jsp?spid=53997) saddle from a soft racing saddle because my old one, while extremely comfortable on long road rides, wasn't working for the TT position I'm now practicing for an upcoming Ironman.
I've been professionally fit with the seat, so I think things are lined up well. I've ridden nearly 200 miles over the last week with it and the problem is: it still freaking hurts. It's not chafing; it's pressure right in that, uh, under-area that's supposed to sit in the gap of the saddle.
Can I expect it to get awesome any time soon, or should I try another saddle at this point?
**Edit:**
Regarding seat position, I have my current seat *all the way forward*, which is where I've been steadily moving it over the last two weeks since my professional fitting. Moving it forward did help, but now I'm stuck again (and I have one of those bent seatposts that is pointing forward as well). | 2011/09/30 | [
"https://bicycles.stackexchange.com/questions/6323",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/1044/"
] | That saddle is unlikely to adjust to you. Man-made materials generally don't budge. You may want to try a Brooks or other leather saddle. If you do, apply the saddle dressing that should come with it, and don't do long rides on it for a few weeks. I've found that two or three weeks of commuting (25 km round-trip) usually does the job.
If you are a woman, your pelvic bones are probably wider, and you'll want a saddle designed for women. Presumably the bike shop already took that into consideration, but I've seen a shop or two where the staff didn't know about this basic issue. | It's vital to adjust your bike to fit your body from the start if you want to keep appropriate alignment and avoid physical difficulties. This will also help you stay comfortable during your bike ride. Setting your [bike seat](https://www.bikeshepherd.org/how-to-make-my-bike-seat-more-comfortable/) to the same height as your hip bones is a good idea. |
8,985,061 | I try to put some strings to `CharBuffer` with `CharBuffer.put()` function
but the buffer is left blank.
my code:
```
CharBuffer charBuf = CharBuffer.allocate(1000);
for (int i = 0; i < 10; i++)
{
String text = "testing" + i + "\n";
charBuf.put(text);
}
System.out.println(charBuf);
```
I tried to use with `clear()` or `rewind()` after `allocate(1000)` but that did not change the result. | 2012/01/24 | [
"https://Stackoverflow.com/questions/8985061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/927045/"
] | You must rewind it after you put in the objects, try this
```
CharBuffer charBuf = CharBuffer.allocate(1000);
for (int i = 0; i < 10; i++)
{
String text = "testing" + i + "\n";
charBuf.put(text);
}
charBuf.rewind();
System.out.println(charBuf);
``` | Add a call to [`rewind()`](http://docs.oracle.com/javase/1.5.0/docs/api/java/nio/Buffer.html#rewind%28%29) right **after** the loop. |
8,985,061 | I try to put some strings to `CharBuffer` with `CharBuffer.put()` function
but the buffer is left blank.
my code:
```
CharBuffer charBuf = CharBuffer.allocate(1000);
for (int i = 0; i < 10; i++)
{
String text = "testing" + i + "\n";
charBuf.put(text);
}
System.out.println(charBuf);
```
I tried to use with `clear()` or `rewind()` after `allocate(1000)` but that did not change the result. | 2012/01/24 | [
"https://Stackoverflow.com/questions/8985061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/927045/"
] | You must rewind it after you put in the objects, try this
```
CharBuffer charBuf = CharBuffer.allocate(1000);
for (int i = 0; i < 10; i++)
{
String text = "testing" + i + "\n";
charBuf.put(text);
}
charBuf.rewind();
System.out.println(charBuf);
``` | Try this:
```
CharBuffer charBuf = CharBuffer.allocate(1000);
for (int i = 0; i < 10; i++)
{
String text = "testing" + i + "\n";
charBuf.put(text);
}
charBuf.rewind();
System.out.println(charBuf);
```
The detail you're missing is that writing moves the current pointer to the end of the written data, so when you're printing it out, it's starting at the current pointer, which has nothing written. |
8,985,061 | I try to put some strings to `CharBuffer` with `CharBuffer.put()` function
but the buffer is left blank.
my code:
```
CharBuffer charBuf = CharBuffer.allocate(1000);
for (int i = 0; i < 10; i++)
{
String text = "testing" + i + "\n";
charBuf.put(text);
}
System.out.println(charBuf);
```
I tried to use with `clear()` or `rewind()` after `allocate(1000)` but that did not change the result. | 2012/01/24 | [
"https://Stackoverflow.com/questions/8985061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/927045/"
] | You must rewind it after you put in the objects, try this
```
CharBuffer charBuf = CharBuffer.allocate(1000);
for (int i = 0; i < 10; i++)
{
String text = "testing" + i + "\n";
charBuf.put(text);
}
charBuf.rewind();
System.out.println(charBuf);
``` | You will need to `flip()` the buffer before you can read from the buffer. The `flip()` method needs to be called before reading the data from the buffer. When the `flip()` method is called the limit is set to the current position, and the position to 0. e.g.
```
CharBuffer charBuf = CharBuffer.allocate(1000);
for (int i = 0; i < 10; i++)
{
String text = "testing" + i + "\n";
charBuf.put(text);
}
charBuf.flip();
System.out.println(charBuf);
```
The above will only print the characters in the buffers and not the unwritten space in the buffer. |
18,856,607 | I have used the below code in app code `session.cs` file. It has been loaded initially in httpmodule.cs, whenever every page hit in browser. I found the `httpcontext.current.session` value is `null`.
```
if (HttpContext.Current != null && HttpContext.Current.Session != null)
{
try
{
if (HttpContext.Current.Session.Keys.Count > 0)
{
}
else
{
HttpContext.Current.Response.Cookies["ecm"].Expires = DateTime.Now;
HttpContext.Current.Response.Cookies["ecmSecure"].Expires = DateTime.Now;
}
}
catch (Exception ex)
{
}
}
```
web.config session settings :
```
<sessionState mode="InProc"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes"
cookieless="false"
timeout="5" />
``` | 2013/09/17 | [
"https://Stackoverflow.com/questions/18856607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2739544/"
] | You don't mention if you have an endpoint configured for your Azure VM. If not, make sure you create an endpoint with a private port of 8172.
EDIT: [Here is a troubleshooting guide](http://www.iis.net/learn/publish/troubleshooting-web-deploy/troubleshooting-common-problems-with-web-deploy) for web deploy that includes the error message you've encountered. Additionally, from my own experience I have managed to mistype the site name and not install .NET and seeing similar errors. | Helpful but in the end in our case it was TLS mismatch. Check both machines can do TLS 1.2 if you are forcing it. Have put more detail here <https://fuseit.zendesk.com/hc/en-us/articles/360000328595>. Cheers |
18,856,607 | I have used the below code in app code `session.cs` file. It has been loaded initially in httpmodule.cs, whenever every page hit in browser. I found the `httpcontext.current.session` value is `null`.
```
if (HttpContext.Current != null && HttpContext.Current.Session != null)
{
try
{
if (HttpContext.Current.Session.Keys.Count > 0)
{
}
else
{
HttpContext.Current.Response.Cookies["ecm"].Expires = DateTime.Now;
HttpContext.Current.Response.Cookies["ecmSecure"].Expires = DateTime.Now;
}
}
catch (Exception ex)
{
}
}
```
web.config session settings :
```
<sessionState mode="InProc"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes"
cookieless="false"
timeout="5" />
``` | 2013/09/17 | [
"https://Stackoverflow.com/questions/18856607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2739544/"
] | After dealing with this for about an hour now, I figured out how to fix this on my Azure Virtual Machine.
First the obvious
* Check that port 8172 (if you're using default settings) is open in your firewall
* Check that the processes MsDepSvc and WMSVC are running.
* Check that the site name is correct.
**Management Service**
In ISS, at the root level of the server, check your settings under Management Service.
It should have `Enable Remote Connections` checked:

**Did you download the full package**
This was the one that got me, I hadn't installed everything.
On the bottom of the WebDeploy page: <http://www.iis.net/downloads/microsoft/web-deploy>
You can download the full package, and then just install everything. | Helpful but in the end in our case it was TLS mismatch. Check both machines can do TLS 1.2 if you are forcing it. Have put more detail here <https://fuseit.zendesk.com/hc/en-us/articles/360000328595>. Cheers |
61,808 | It is good practice to use walk commands rather than holding direction buttons as much as possible lest you accidentally run into a monster you can't handle and die as a result, a mistake I've made more than once. However, walking in Nethack is... not awesome. This is my situation right now:
```
where I want to go
↑
### # # ##
# # # #
# #########@0#####
# #----------#
-----.--------- #|........|#
|.............| #|........-#
|.............| #|........|
|.....<.......-######.........|
--------------- ----------
```
If from here I pressed shift-H (run left) I would run all the way to here:
```
where I want to go
↑
### # # ##
# # # #
# ##########0#####
# #----------#
-----.--------- #|........|#
|.............| #|........-#
|.............| #|........|
|.....<.......-#####@.........|
--------------- ----------
```
If from here I pressed shift-K (run up) I would run up to the boulder and then push it into the intersection.
All other run directions (like the diagonals) don't seem to do anything in my quest to walk up in that T junction. What can I do then?
How can I make walking behave more sensibly? | 2012/04/09 | [
"https://gaming.stackexchange.com/questions/61808",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/23/"
] | Press "g" and then the direction to stop at intersections. Not SHIFT-direction.
More generally, use the "?" command to read the documentation for various nethack commands, including the differences between SHIFT, "g", "G"/CTRL, and "m" as movement modifiers.
See also <http://strategywiki.org/wiki/NetHack/Controls#Advanced_movement> | I strongly disagree with the first sentence, but the answer is to use `_` to run to where you want to go. |
73,646,111 | I created a hook to be able to set a timeout. Every callback that will be added in that hook will be delayed with a certain amount of time:
```
import "./styles.css";
import React, { useRef, useCallback, useState, useEffect } from "react";
const useTimer = () => {
const timer = useRef();
const fn = useCallback((callback, timeout = 0) => {
timer.current = setTimeout(() => {
callback();
}, timeout);
}, []);
const clearTimeoutHandler = () => {
console.log("clear");
return clearTimeout(timer);
};
useEffect(() => {
return clearTimeoutHandler();
}, []);
return { fn, clearTimeoutHandler };
};
export default function App() {
const [state, setState] = useState(false);
const timer = useTimer();
const onClickHandler = () => {
setState(true);
timer.fn(() => {
console.log(5000);
setState(false);
}, 5000);
};
return (
<div className="App">
{state && <h1>Hello</h1>}
<button onClick={onClickHandler}>Open</button>
</div>
);
}
```
In my case `Hello` text will appear after user will click on the button and will disappear after 5000 sec.
Issue: After clicking 1 time on the button and after 3 sec again clicking on it i expect to see `Hello` text 5 sec right after the last click, but in my case if i click twice the timer will take into account only the first click and if i will click after 3 sec one more time the text will disappear after 2 sec not 5.
Question: how to fix the hook and to reset the timer if the user click many times or the hook is called many times?
demo: <https://codesandbox.io/s/recursing-ride-mlqnri?file=/src/App.js:0-880> | 2022/09/08 | [
"https://Stackoverflow.com/questions/73646111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12540500/"
] | All you need is to add `clearTimeout()` to your `useTimer()` function.
Here's your working code:
```js
import "./styles.css";
import React, { useRef, useCallback, useState, useEffect } from "react";
const useTimer = () => {
const timer = useRef();
const fn = useCallback((callback, timeout = 0) => {
// Add this line here
clearTimeout(timer.current);
timer.current = setTimeout(() => {
callback();
}, timeout);
}, []);
const clearTimeoutHandler = () => {
console.log("clear");
return clearTimeout(timer);
};
useEffect(() => {
return clearTimeoutHandler();
}, []);
return { fn, clearTimeoutHandler };
};
export default function App() {
const [state, setState] = useState(false);
const timer = useTimer();
const onClickHandler = () => {
setState(true);
timer.fn(() => {
console.log(5000);
setState(false);
}, 5000);
};
return (
<div className="App">
{state && <h1>Hello</h1>}
<button onClick={onClickHandler}>Open</button>
</div>
);
}
```
And a sandbox demo: <https://codesandbox.io/s/angry-dream-xmzh9v?file=/src/App.js> | You are passing the ref directly to clearTimeout
```js
const clearTimeoutHandler = () => {
console.log("clear");
return clearTimeout(timer); // should be timer.current
};
``` |
73,646,111 | I created a hook to be able to set a timeout. Every callback that will be added in that hook will be delayed with a certain amount of time:
```
import "./styles.css";
import React, { useRef, useCallback, useState, useEffect } from "react";
const useTimer = () => {
const timer = useRef();
const fn = useCallback((callback, timeout = 0) => {
timer.current = setTimeout(() => {
callback();
}, timeout);
}, []);
const clearTimeoutHandler = () => {
console.log("clear");
return clearTimeout(timer);
};
useEffect(() => {
return clearTimeoutHandler();
}, []);
return { fn, clearTimeoutHandler };
};
export default function App() {
const [state, setState] = useState(false);
const timer = useTimer();
const onClickHandler = () => {
setState(true);
timer.fn(() => {
console.log(5000);
setState(false);
}, 5000);
};
return (
<div className="App">
{state && <h1>Hello</h1>}
<button onClick={onClickHandler}>Open</button>
</div>
);
}
```
In my case `Hello` text will appear after user will click on the button and will disappear after 5000 sec.
Issue: After clicking 1 time on the button and after 3 sec again clicking on it i expect to see `Hello` text 5 sec right after the last click, but in my case if i click twice the timer will take into account only the first click and if i will click after 3 sec one more time the text will disappear after 2 sec not 5.
Question: how to fix the hook and to reset the timer if the user click many times or the hook is called many times?
demo: <https://codesandbox.io/s/recursing-ride-mlqnri?file=/src/App.js:0-880> | 2022/09/08 | [
"https://Stackoverflow.com/questions/73646111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12540500/"
] | All you need is to add `clearTimeout()` to your `useTimer()` function.
Here's your working code:
```js
import "./styles.css";
import React, { useRef, useCallback, useState, useEffect } from "react";
const useTimer = () => {
const timer = useRef();
const fn = useCallback((callback, timeout = 0) => {
// Add this line here
clearTimeout(timer.current);
timer.current = setTimeout(() => {
callback();
}, timeout);
}, []);
const clearTimeoutHandler = () => {
console.log("clear");
return clearTimeout(timer);
};
useEffect(() => {
return clearTimeoutHandler();
}, []);
return { fn, clearTimeoutHandler };
};
export default function App() {
const [state, setState] = useState(false);
const timer = useTimer();
const onClickHandler = () => {
setState(true);
timer.fn(() => {
console.log(5000);
setState(false);
}, 5000);
};
return (
<div className="App">
{state && <h1>Hello</h1>}
<button onClick={onClickHandler}>Open</button>
</div>
);
}
```
And a sandbox demo: <https://codesandbox.io/s/angry-dream-xmzh9v?file=/src/App.js> | I think you should clear previous timer in `fn` function, and assign null to `timer.current` after callback function is invoke.
this is my code below:
<https://codesandbox.io/s/exciting-fire-jgujww?file=/src/App.js:0-977> |
52,473,687 | I have one string
```
var inp = "ABCABCABC";
```
To get second occurrence of "A" am doing below
```
int index = inp.indexOf("A", inp.indexOf("A")+1);
```
But if I need third occurrence of "A", Why I cant do like this ?
```
int index = inp.indexOf("A", inp.indexOf("A")+2); ---Not Working WHY....?
```
But this is
```
int index = inp.indexOf("A", inp.indexOf("A", inp.indexOf("A")+1)+1); --- Working
```
Any suggestions ? | 2018/09/24 | [
"https://Stackoverflow.com/questions/52473687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9748223/"
] | In this case, `+1` just adds `1`, nothing more. It doesn't skip `n` occurrences.
What I suggest you do is use a loop.
```
public static int findNth(String text, String find, int nth) {
int last = -1;
for (int i = 0; i < nth; i++) {
last = text.indexOf(find, last + 1);
if (last == -1) return -1;
}
return last;
}
```
You should be able to see this in your debugger however in you situation you have
```
int index = inp.indexOf("A", inp.indexOf("A")+1);
```
Which is the same as
```
int index = inp.indexOf("A", 0+1);
```
or
```
int index = inp.indexOf("A", 1);
```
as `0 + 1` == `1`
If you change the code to
```
int index = inp.indexOf("A", inp.indexOf("A")+2);
```
You get
```
int index = inp.indexOf("A", 0+2);
```
which will only work if there is `AA`
This line
```
int index = inp.indexOf("A", inp.indexOf("A", inp.indexOf("A")+1)+1);
```
evaluates to
```
int index = inp.indexOf("A", inp.indexOf("A", 0+1)+1);
```
or
```
int index = inp.indexOf("A", 3+1);
```
or
```
int index = inp.indexOf("A", 4);
``` | This only works because
```
int index = inp.indexOf("A");
```
returns the index of the first occurrence of A, beginning with the 0th character (inclusive). ([See the documentation here](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(int,%20int)).) If you set a second argument
```
int index = inp.indexOf("A", 5);
```
`indexOf` will only return the first A that it finds at or after index `5`.
---
What you are doing is
```
int index = inp.indexOf("A", inp.indexOf("A")+1);
```
...which finds the first occurrence of "A", then moves to the next character in the String, then looks for the second occurrence of "A". This will only work if there are multiple "A" in the String.
Suppose you have a String like
```
String phil = "ABACAB";`
```
Then `phil.indexOf("A")` returns `0`, and `phil.indexOf("A", phil.indexOf("A")+1)` simplifies to `phil.indexOf("A", 0+1)` or just `phil.indexOf("A", 1)`. So you're looking for the first occurrence of "A" at or after the 1st index (the first "B" in "ABACAB"). This will return `2`.
Doing something like:
```
int index = inp.indexOf("A", inp.indexOf("A")+2);
```
Does the same thing, but moves forward *two* characters, after finding the first occurrence of "A". So for our example, this simplifies to `phil.indexOf("A", 2)`, which will return `2`, finding the same, second "A" that it found in the first case.
To find the third occurrence, you need to chain the calls, as you noted:
```
int index = inp.indexOf("A", inp.indexOf("A", inp.indexOf("A")+1)+1);
```
Or use a third-party library. |
72,406,938 | I have been wrestling with Boost.Spirit for a week. Forgive me for my ignorance about C++'s template metaprogramming, but I can't help to ask: How do you know what can you do with a variable if you don't know its god damn type? For example:
```cpp
namespace qi = boost::spirit::qi;
qi::on_error<qi::fail>(rule,
[](auto& args, auto& context, auto& r) {
// what to do with args, context and r?
}
);
```
It's not like Python, where you can use `dir()` or `help()` to get information about some variable. I know I can use `typeid(..).name()` to find out the type of a variable, but usually it turns out to be some long unreadable text like:
```
struct boost::fusion::vector<class boost::spirit::lex::lexertl::iterator<class boost::spirit::lex::lexertl::functor<struct boost::spirit::lex::lexertl::token<class std::_String_iterator<class std::_String_val<struct std::_Simple_types<char> > >,struct boost::mpl::vector<__int64,struct String,struct Symbol,struct boost::mpl::na,struct boost::mpl::na,struct boost::mpl::na,struct boost::mpl::na,struct boost::mpl::na,struct boost::mpl::na,struct boost::mpl::na,struct boost::mpl::na,struct boost::mpl::na,struct boost::mpl::na,struct boost::mpl::na,struct boost::mpl::na,struct boost::mpl::na,struct boost::mpl::na,struct boost::mpl::na,struct boost::mpl::na,struct boost::mpl::na>,struct boost::mpl::bool_<1>,unsigned __int64>,class boost::spirit::lex::lexertl::detail::data,class std::_String_iterator<class std::_String_val<struct std::_Simple_types<char> > >,struct boost::mpl::bool_<1>,struct boost::mpl::bool_<1> > > & __ptr64,class boost::spirit::lex::lexertl::iterator<class boost::spirit::lex::lexertl::functor<struct boost::spirit::lex::lexertl::token<class std::_String_iterator<class std::_String_val<struct std::_Simple_types<char> > >,struct boost::mpl::vector<__int64,struct String,struct Symbol,struct boost::mpl::na,struct boost::mpl::na,struct boost::mpl::na,struct boost::mpl::na,struct boost::mpl::na,struct boost::mpl::na,struct boost::mpl::na,struct boost::mpl::na,struct boost::mpl::na,struct boost::mpl::na,struct boost::mpl::na,struct boost::mpl::na,struct boost::mpl::na,struct boost::mpl::na,struct boost::mpl::na,struct boost::mpl::na,struct boost::mpl::na>,struct boost::mpl::bool_<1>,unsigned __int64>,class boost::spirit::lex::lexertl::detail::data,class std::_String_iterator<class std::_String_val<struct std::_Simple_types<char> > >,struct boost::mpl::bool_<1>,struct boost::mpl::bool_<1> > > const & __ptr64,class boost::spirit::lex::lexertl::iterator<class boost::spirit::lex::lexertl::functor<struct boost::spirit::lex::lexertl::token<class std::_String_iterator<class std::_String_val<struct std::_Simple_types<char> > >,struct boost::mpl::vector<__int64,struct String,struct Symbol,struct boost::mpl::na,struct boost::mpl::na,struct boost::mpl::na,struct boost::mpl::na,struct boost::mpl::na,struct boost::mpl::na,struct boost::mpl::na,struct boost::mpl::na,struct boost::mpl::na,struct boost::mpl::na,struct boost::mpl::na,struct boost::mpl::na,struct boost::mpl::na,struct boost::mpl::na,struct boost::mpl::na,struct boost::mpl::na,struct boost::mpl::na>,struct boost::mpl::bool_<1>,unsigned __int64>,class boost::spirit::lex::lexertl::detail::data,class std::_String_iterator<class std::_String_val<struct std::_Simple_types<char> > >,struct boost::mpl::bool_<1>,struct boost::mpl::bool_<1> > > const & __ptr64,struct boost::spirit::info const & __ptr64>
```
So there is only one method left: **refer to the documentation**. But here's the problem: Spirit's documentation is incomplete. In this example, It only say a few words about these arguments in the ["Error Handling Tutorial"](https://www.boost.org/doc/libs/1_79_0/libs/spirit/doc/html/spirit/qi/tutorials/mini_xml___error_handling.html):
>
> on\_error declares our error handler:
>
>
> `on_error<Action>(rule, handler)`
>
>
> ...
>
>
> handler is the actual error handling function. It expects 4 arguments:
>
>
>
>
>
> | Arg | Description |
> | --- | --- |
> | first | The position of the iterator when the rule with the handler was entered. |
> | last | The end of input. |
> | error-pos | The actual position of the iterator where the error occurred. |
> | what | What failed: a string describing the failure. |
>
>
>
But as you can see, `on_error`'s second argument is not a 4-arguments function, but a 3-arguments function (args, context and r). Is the documentation wrong? Where can I find out the methods on these arguments? **Does Spirit has a per-funcion API Documentation?** | 2022/05/27 | [
"https://Stackoverflow.com/questions/72406938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13784274/"
] | The simplest way:
```
qi::on_error<qi::fail>(rule,
[](auto& args, auto& context, auto& r) {
std::cerr << __PRETTY_FUNCTION__ << std::endl;
}
);
```
On e.g. GCC this prints the full signature including deduced type arguments.
Is the documentation wrong?
---------------------------
Note that it **DOES** expect 4 arguments:
```
using namespace qi::labels;
qi::on_error<qi::error_handler_result::fail>(rule, f_(_1, _2, _3, _4));
```
When you install a handler like `f_`:
```
struct F {
using result_type = void;
template <typename... Args>
void operator()(Args&&...) const {
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
};
boost::phoenix::function<F> f_{};
```
It prints (**[Live](http://coliru.stacked-crooked.com/a/e07c592c5a41e6e1)**):
```
"expected" -> true
void Parser::F::operator()(Args&& ...) const [with Args = {const char*&, const char* const&, const char* const&, const boost::spirit::info&}]
"unexpected" -> false
```
As you can see, the documentation is not wrong or incomplete. Your expectations were, because you didn't get that `handler` represent a *deferred function* aka. [Phoenix Actor](https://www.boost.org/doc/libs/1_79_0/libs/phoenix/doc/html/phoenix/inside/actor.html). I guess the "devious" thing the documentation did was assume you'd **see** that from the actual example, which immediately precedes the documentation you quoted:
>
>
> ```
> on_error<fail>
> (
> xml
> , std::cout
> << val("Error! Expecting ")
> << _4 // what failed?
> << val(" here: \"")
> << construct<std::string>(_3, _2) // iterators to error-pos, end
> << val("\"")
> << std::endl
> );
>
> ```
>
>
Here, it seems quite obvious that the expression `std::cout << val("Error! Expecting ") << _4 << val(" here: \"") << construct<std::string>(_3, _2) << val("\"") << std::endl` is **not** literally "a function taking 4 arguments". It is a Phoenix expression defining an actor that takes 4 arguments, though.
You **did** find out that an actor is *in fact* still implemented in terms of a callable object. And it "takes" 3 arguments, which are the technical implementation details for Phoenix actors and the Spirit context arguments.
The problem was a disconnect of abstraction levels. The documentation documents the library interface, you accidentally looked at implementation details.
TL;DR
-----
A lambda is not a deferred Phoenix actor.
Learn more about how deferred actors work e.g. with semantic actions:
* <https://www.boost.org/doc/libs/1_79_0/libs/spirit/doc/html/spirit/qi/quick_reference/semantic_actions.html>
Some answers on [SO] that highlight the relation between Actor signature, context and implementation signatures:
* [How to avoid boost::phoenix when generating with boost::spirit::karma](https://stackoverflow.com/questions/16607238/how-to-avoid-boostphoenix-when-generating-with-boostspiritkarma/16609770#16609770)
* [boost spirit semantic action parameters](https://stackoverflow.com/questions/3066701/boost-spirit-semantic-action-parameters/3067881#3067881) | It will generate a compile time error, but if you have a class template declaration like
```
template <typename T> struct get_type;
```
Then trying to create a `get_type` object with a provided type will generate an error and in the error message it will tell you what the type provide to `get_type` is. For example using
```
int main()
{
auto lambda = [](auto first, auto second, auto third)
{
get_type<decltype(first)>{};
get_type<decltype(second)>{};
get_type<decltype(third)>{};
};
lambda(A{}, B{}, int{});
}
```
produces an error message like
```
main.cpp:20:9: error: invalid use of incomplete type 'struct get_type<A>'
20 | get_type<decltype(first)>{};
| ^~~~~~~~
main.cpp:14:30: note: declaration of 'struct get_type<A>'
14 | template <typename T> struct get_type;
| ^~~~~~~~
main.cpp:21:9: error: invalid use of incomplete type 'struct get_type<B>'
21 | get_type<decltype(second)>{};
| ^~~~~~~~
main.cpp:14:30: note: declaration of 'struct get_type<B>'
14 | template <typename T> struct get_type;
| ^~~~~~~~
main.cpp:22:9: error: invalid use of incomplete type 'struct get_type<int>'
22 | get_type<decltype(third)>{};
| ^~~~~~~~
main.cpp:14:30: note: declaration of 'struct get_type<int>'
14 | template <typename T> struct get_type;
| ^~~~~~~~
```
which tells use `first` is an `A`, second is a `B` and `third` is an `int` as seen in this [live example](http://coliru.stacked-crooked.com/a/a6d2d64cfca5b4c7). |
63,917,490 | First want to filter by class and then change class name :
```
<div class="root">
<div class="col-8 catA filter"></div>
<div class="col-4 catB filter"></div>
<div class="col-8 catA filter"></div>
<div class="col-4 catB filter"></div>
<div class="col-8 catA filter"></div>
<div class="col-4 catB filter"></div>
</div>
```
**I want to filter elements by class name "catB" and set condition :**
```
var myFilterData = $('.filter').filter('.catB');
```
**My condition will be like this :**
```
if (myFilterData.index == even) {
//add New class
}
```
>
> **Is it possible using jquery filter() method ?**
>
>
> | 2020/09/16 | [
"https://Stackoverflow.com/questions/63917490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5287215/"
] | Is this what you mean?
```
myFilterData.each(function(index) {
if (! (index % 2)) $(this)
.addClass("newClass")
// .removeClass("catB") // Not sure if you also want this
;
});
``` | Use data id in each div and get data id
```
<div class="root">
<div class="col-8 filter" data-id="catA"></div>
<div class="col-4 filter" data-id="catB"></div>
<div class="col-8 filter" data-id="catA"></div>
<div class="col-4 filter" data-id="catB"></div>
<div class="col-8 filter" data-id="catA"></div>
<div class="col-4 filter" data-id="catB"></div>
</div>
<script>
$('.filter').on('click', function(){
var myFilterData = $(this).data('id')
})
</script>
``` |
63,917,490 | First want to filter by class and then change class name :
```
<div class="root">
<div class="col-8 catA filter"></div>
<div class="col-4 catB filter"></div>
<div class="col-8 catA filter"></div>
<div class="col-4 catB filter"></div>
<div class="col-8 catA filter"></div>
<div class="col-4 catB filter"></div>
</div>
```
**I want to filter elements by class name "catB" and set condition :**
```
var myFilterData = $('.filter').filter('.catB');
```
**My condition will be like this :**
```
if (myFilterData.index == even) {
//add New class
}
```
>
> **Is it possible using jquery filter() method ?**
>
>
> | 2020/09/16 | [
"https://Stackoverflow.com/questions/63917490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5287215/"
] | Please check below solution.You can add or remove the class according to your condition.
```
var myFilterData = $('.filter').filter('.catB');
if (yourcondition == true) {
myFilterData.addClass("newClass");
// myFilterData.removeClass("catB") For removing the class
}
``` | Use data id in each div and get data id
```
<div class="root">
<div class="col-8 filter" data-id="catA"></div>
<div class="col-4 filter" data-id="catB"></div>
<div class="col-8 filter" data-id="catA"></div>
<div class="col-4 filter" data-id="catB"></div>
<div class="col-8 filter" data-id="catA"></div>
<div class="col-4 filter" data-id="catB"></div>
</div>
<script>
$('.filter').on('click', function(){
var myFilterData = $(this).data('id')
})
</script>
``` |
63,917,490 | First want to filter by class and then change class name :
```
<div class="root">
<div class="col-8 catA filter"></div>
<div class="col-4 catB filter"></div>
<div class="col-8 catA filter"></div>
<div class="col-4 catB filter"></div>
<div class="col-8 catA filter"></div>
<div class="col-4 catB filter"></div>
</div>
```
**I want to filter elements by class name "catB" and set condition :**
```
var myFilterData = $('.filter').filter('.catB');
```
**My condition will be like this :**
```
if (myFilterData.index == even) {
//add New class
}
```
>
> **Is it possible using jquery filter() method ?**
>
>
> | 2020/09/16 | [
"https://Stackoverflow.com/questions/63917490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5287215/"
] | Is this what you mean?
```
myFilterData.each(function(index) {
if (! (index % 2)) $(this)
.addClass("newClass")
// .removeClass("catB") // Not sure if you also want this
;
});
``` | I think you need to filter all the divs with catB class evenly and change the class accordingly. Try this in your click handler
$('.filter.catB:even').removeClass('col-4').addClass('col-8'); |
63,917,490 | First want to filter by class and then change class name :
```
<div class="root">
<div class="col-8 catA filter"></div>
<div class="col-4 catB filter"></div>
<div class="col-8 catA filter"></div>
<div class="col-4 catB filter"></div>
<div class="col-8 catA filter"></div>
<div class="col-4 catB filter"></div>
</div>
```
**I want to filter elements by class name "catB" and set condition :**
```
var myFilterData = $('.filter').filter('.catB');
```
**My condition will be like this :**
```
if (myFilterData.index == even) {
//add New class
}
```
>
> **Is it possible using jquery filter() method ?**
>
>
> | 2020/09/16 | [
"https://Stackoverflow.com/questions/63917490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5287215/"
] | Please check below solution.You can add or remove the class according to your condition.
```
var myFilterData = $('.filter').filter('.catB');
if (yourcondition == true) {
myFilterData.addClass("newClass");
// myFilterData.removeClass("catB") For removing the class
}
``` | I think you need to filter all the divs with catB class evenly and change the class accordingly. Try this in your click handler
$('.filter.catB:even').removeClass('col-4').addClass('col-8'); |
63,917,490 | First want to filter by class and then change class name :
```
<div class="root">
<div class="col-8 catA filter"></div>
<div class="col-4 catB filter"></div>
<div class="col-8 catA filter"></div>
<div class="col-4 catB filter"></div>
<div class="col-8 catA filter"></div>
<div class="col-4 catB filter"></div>
</div>
```
**I want to filter elements by class name "catB" and set condition :**
```
var myFilterData = $('.filter').filter('.catB');
```
**My condition will be like this :**
```
if (myFilterData.index == even) {
//add New class
}
```
>
> **Is it possible using jquery filter() method ?**
>
>
> | 2020/09/16 | [
"https://Stackoverflow.com/questions/63917490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5287215/"
] | Is this what you mean?
```
myFilterData.each(function(index) {
if (! (index % 2)) $(this)
.addClass("newClass")
// .removeClass("catB") // Not sure if you also want this
;
});
``` | Please check it, this way you can update classes
```html
<div class="root">
<div class="col-8 catA filter"></div>
<div class="col-4 catB filter"></div>
<div class="col-8 catA filter"></div>
<div class="col-4 catB filter"></div>
<div class="col-8 catA filter"></div>
<div class="col-4 catB filter"></div>
</div>
<script>
document.querySelector('.root').addEventListener('click', function(event){
event.target.classList.remove('col-4');
event.target.classList.add('col-8');
});
</script>
``` |
63,917,490 | First want to filter by class and then change class name :
```
<div class="root">
<div class="col-8 catA filter"></div>
<div class="col-4 catB filter"></div>
<div class="col-8 catA filter"></div>
<div class="col-4 catB filter"></div>
<div class="col-8 catA filter"></div>
<div class="col-4 catB filter"></div>
</div>
```
**I want to filter elements by class name "catB" and set condition :**
```
var myFilterData = $('.filter').filter('.catB');
```
**My condition will be like this :**
```
if (myFilterData.index == even) {
//add New class
}
```
>
> **Is it possible using jquery filter() method ?**
>
>
> | 2020/09/16 | [
"https://Stackoverflow.com/questions/63917490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5287215/"
] | Please check below solution.You can add or remove the class according to your condition.
```
var myFilterData = $('.filter').filter('.catB');
if (yourcondition == true) {
myFilterData.addClass("newClass");
// myFilterData.removeClass("catB") For removing the class
}
``` | Please check it, this way you can update classes
```html
<div class="root">
<div class="col-8 catA filter"></div>
<div class="col-4 catB filter"></div>
<div class="col-8 catA filter"></div>
<div class="col-4 catB filter"></div>
<div class="col-8 catA filter"></div>
<div class="col-4 catB filter"></div>
</div>
<script>
document.querySelector('.root').addEventListener('click', function(event){
event.target.classList.remove('col-4');
event.target.classList.add('col-8');
});
</script>
``` |
63,917,490 | First want to filter by class and then change class name :
```
<div class="root">
<div class="col-8 catA filter"></div>
<div class="col-4 catB filter"></div>
<div class="col-8 catA filter"></div>
<div class="col-4 catB filter"></div>
<div class="col-8 catA filter"></div>
<div class="col-4 catB filter"></div>
</div>
```
**I want to filter elements by class name "catB" and set condition :**
```
var myFilterData = $('.filter').filter('.catB');
```
**My condition will be like this :**
```
if (myFilterData.index == even) {
//add New class
}
```
>
> **Is it possible using jquery filter() method ?**
>
>
> | 2020/09/16 | [
"https://Stackoverflow.com/questions/63917490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5287215/"
] | Is this what you mean?
```
myFilterData.each(function(index) {
if (! (index % 2)) $(this)
.addClass("newClass")
// .removeClass("catB") // Not sure if you also want this
;
});
``` | Please check below solution.You can add or remove the class according to your condition.
```
var myFilterData = $('.filter').filter('.catB');
if (yourcondition == true) {
myFilterData.addClass("newClass");
// myFilterData.removeClass("catB") For removing the class
}
``` |
662,967 | $(2^n+n^2)$ is $O(2^n)$ and $(n^3+3^n)$ is $O(3^n)$, therefore I conclude that $(2^n+n^2)(n^3+3^n)$ is $O(2^n\*3^n)=O(6^n)$ | 2014/02/04 | [
"https://math.stackexchange.com/questions/662967",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/86425/"
] | Your answer is correct, yet if you were not 100% sure you can always check using the definition of "big O":
$$\limsup\_{n\rightarrow\infty}\frac{(2^n+n^2)(n^3+3^n)}{6^n}=\limsup\_{n\rightarrow\infty}\frac{n^5+n^32^n+n^23^n+6^n}{6^n}=\limsup\_{n\rightarrow\infty}(n^5(1/6)^n+n^3(1/3)^n+n^2(1/2)^n+1)=1$$
$$\Rightarrow (2^n+n^2)(n^3+3^n)=\mathcal{O
}(6^n)$$ | Yes ${}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}$ |
5,353,311 | `npm uninstall express` successfully uninstalls express, and when I `ls $NODE_PATH`, it isn't there anymore.
However, if I run `node` and `require('express')`, I get
```
{ version: '1.0.0rc2',
Server: { [Function: Server] super_: { [Function: Server] super_: [Object] } },
createServer: [Function] }
```
Why does this still happen?
The reason I'm playing around with Express is because (apparently) it breaks with a certain version of Connect. Does anyone know what successful combination of Express and Connect will work ?
Thanks! | 2011/03/18 | [
"https://Stackoverflow.com/questions/5353311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/137100/"
] | Output the require paths `console.log(require.paths)`
Those are the paths nodejs is using to resolve the `require('express')` | I currently use latest node, Express@1.0.8, Connect@0.5.10. I've been having some issues with upgrading to the latest connect/express, so I vowed to finish building my app first and then perform a massive upgrade. This combo works well for me though. |
5,353,311 | `npm uninstall express` successfully uninstalls express, and when I `ls $NODE_PATH`, it isn't there anymore.
However, if I run `node` and `require('express')`, I get
```
{ version: '1.0.0rc2',
Server: { [Function: Server] super_: { [Function: Server] super_: [Object] } },
createServer: [Function] }
```
Why does this still happen?
The reason I'm playing around with Express is because (apparently) it breaks with a certain version of Connect. Does anyone know what successful combination of Express and Connect will work ?
Thanks! | 2011/03/18 | [
"https://Stackoverflow.com/questions/5353311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/137100/"
] | Output the require paths `console.log(require.paths)`
Those are the paths nodejs is using to resolve the `require('express')` | Try `npm config get root`—that shows you where npm is installing things. If it's pointing somewhere that doesn't make sense, use `npm config set root [new path]` to change it to something that's in Node's `require.paths`. (Of course, now you'll have to reinstall all of your npm packages.) |
5,353,311 | `npm uninstall express` successfully uninstalls express, and when I `ls $NODE_PATH`, it isn't there anymore.
However, if I run `node` and `require('express')`, I get
```
{ version: '1.0.0rc2',
Server: { [Function: Server] super_: { [Function: Server] super_: [Object] } },
createServer: [Function] }
```
Why does this still happen?
The reason I'm playing around with Express is because (apparently) it breaks with a certain version of Connect. Does anyone know what successful combination of Express and Connect will work ?
Thanks! | 2011/03/18 | [
"https://Stackoverflow.com/questions/5353311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/137100/"
] | Try `npm config get root`—that shows you where npm is installing things. If it's pointing somewhere that doesn't make sense, use `npm config set root [new path]` to change it to something that's in Node's `require.paths`. (Of course, now you'll have to reinstall all of your npm packages.) | I currently use latest node, Express@1.0.8, Connect@0.5.10. I've been having some issues with upgrading to the latest connect/express, so I vowed to finish building my app first and then perform a massive upgrade. This combo works well for me though. |
209,739 | I am trying to display something when click on a link from admin menu. So i created a simple module and when i click from the admin menu it redirect to mydomain/secure-manage/helloworld/index/index/key/... with **status 200** but the **page is blank**.
In devtool i can see the css and js are loaded but nothing inside the body tag.
1.folder structure
```
Inchoo
Helloworld
-Block
-Adminhtml
Helloworld.php
-Controller
-Adminhtml
-Index
Index.php
-etc
-module.xml
-adminhtml
-menu.xml
-routes.xml
-view
adminhtml
layout
-helloworld_index_index.xml
templates
-helloworld.phtml
registration.php
```
2.Block/Adminhtml/Helloworld.php
```
<?php
namespace Inchoo\Helloworld\Block;
class Helloworld extends \Magento\Framework\View\Element\Template
{
public function getHelloWorldTxt()
{
return 'Hello world!';
}
}
```
3.Controller/Adminhtml/Index/Index.php
```
<?php
namespace Inchoo\Helloworld\Controller\Adminhtml\Index;
use Magento\Framework\App\Action\Context;
class Index extends \Magento\Framework\App\Action\Action
{
protected $_resultPageFactory;
public function __construct(Context $context,
\Magento\Framework\View\Result\PageFactory $resultPageFactory)
{
$this->_resultPageFactory = $resultPageFactory;
parent::__construct($context);
}
public function execute()
{
$resultPage = $this->_resultPageFactory->create();
// print_r($resultPage);exit;
return $resultPage;
}
}
```
4.etc/module.xml
```
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/
module.xsd">
<module name="Inchoo_Helloworld" setup_version="1.0.0">
</module>
</config>
```
5.etc/adminhtml/menu.xml
```
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Backend:etc
/menu.xsd">
<menu>
<add id="Inchoo_Helloworld::first_pincollect_pincheck"
title="Greetings"
module="Inchoo_Helloworld"
sortOrder="50"
dependsOnModule="Inchoo_Helloworld"
resource="Magento_Backend::content" />
<add id="Inchoo_Helloworld::second_pincollect_pincheck"
title="Manage Pincodes"
module="Inchoo_Helloworld"
sortOrder="0"
action="helloworld/index"
parent="Inchoo_Helloworld::first_pincollect_pincheck"
resource="Magento_Backend::content" />
</menu>
</config>
```
6.etc/adminhtml/routes.xml
```
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc
/routes.xsd">
<router id="admin">
<route id="helloworld" frontName="helloworld">
<module name="Inchoo_Helloworld" />
</route>
</router>
</config>
```
7.view/adminhtml/layout/helloworld\_index\_index.xml
```
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../../../../../../../lib/
internal/Magento/Framework/View/Layout/etc/page_configuration.xsd"
layout="1column">
<body>
<referenceContainer name="content">
<block class="Inchoo\Helloworld\Block\Adminhtml\Helloworld"
name="helloworld" template="helloworld.phtml" />
</referenceContainer>
</body>
</page>
```
8.view/adminhtml/templates/helloworld.phtml
```
<p>Hello World!</p>
```
how can i debug this, please help me guys.
Thanks in advance. | 2018/01/17 | [
"https://magento.stackexchange.com/questions/209739",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/60575/"
] | I am giving you the exact code and path please copy and paste the below file.
**app/code/Inchoo/Helloworld/registration.php**
```
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Inchoo_Helloworld',
__DIR__
);
```
**app/code/Inchoo/Helloworld/Block/Adminhtml/Index/Index.php**
```
<?php
namespace Inchoo\Helloworld\Block\Adminhtml\Index;
class Index extends \Magento\Backend\Block\Widget\Container
{
public function __construct(\Magento\Backend\Block\Widget\Context $context,array $data = [])
{
parent::__construct($context, $data);
}
}
```
**app/code/Inchoo/Helloworld/Controller/Adminhtml/Index/Index.php**
```
<?php
namespace Inchoo\Helloworld\Controller\Adminhtml\Index;
class Index extends \Magento\Backend\App\Action
{
public function execute()
{
$this->_view->loadLayout();
$this->_view->getLayout()->initMessages();
$this->_view->renderLayout();
}
}
?>
```
**app/code/Inchoo/Helloworld/etc/module.xml**
```
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
<module name="Inchoo_Helloworld" setup_version="1.0.0"></module>
<sequence>
<module name="Magento_Backend"/>
<module name="Magento_Sales"/>
<module name="Magento_Quote"/>
<module name="Magento_Checkout"/>
</sequence>
</config>
```
**app/code/Inchoo/Helloworld/etc/adminhtml/routes.xml**
```
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/App/etc/routes.xsd">
<router id="admin">
<route id="helloworld" frontName="helloworld">
<module name="Inchoo_Helloworld" before="Magento_Adminhtml" />
</route>
</router>
</config>
```
**app/code/Inchoo/Helloworld/etc/adminhtml/menu.xml**
```
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../Magento/Backend/etc/menu.xsd">
<menu>
<add id="Inchoo_Helloworld::parent" title="Helloworld" module="Inchoo_Helloworld" sortOrder="100" resource="Inchoo_Helloworld::parent"/>
<add id="Inchoo_Helloworld::index" title="Helloworld Index" module="Inchoo_Helloworld" sortOrder="10" action="helloworld/index" resource="Inchoo_Helloworld::index" parent="Inchoo_Helloworld::parent"/>
</menu>
</config>
```
**app/code/Inchoo/Helloworld/view/adminhtml/layout/helloworld\_index\_index.xml**
```
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
<head>
<title>Hello World</title>
</head>
<body>
<referenceContainer name="content">
<block class="Inchoo\Helloworld\Block\Adminhtml\Index\Index" name="helloworld_block_adminhtml_index_index" template="Inchoo_Helloworld::helloworld_index_index.phtml" />
</referenceContainer>
</body>
</page>
```
**app/code/Inchoo/Helloworld/view/adminhtml/templates/helloworld\_index\_index.phtml**
```
<?php echo "Hello World template"; ?>
```
**N:B** After put all the files to the specific path don't forget to run this command from CLI -
```
php bin/magento setup:upgrade
php bin/magento cache:flush
``` | First correct your folder structure name, Like
```
Inchoo
Helloworld
-Block
-Adminhtml
Helloworld.php
-Controller
-Adminhtml
-Index
-Index.php
-etc
-module.xml
-adminhtml
-menu.xml
-routes.xml
-view
-adminhtml
-layout
-helloworld_index_index.xml
-templates
-helloworld.phtml
-registration.php
``` |
209,739 | I am trying to display something when click on a link from admin menu. So i created a simple module and when i click from the admin menu it redirect to mydomain/secure-manage/helloworld/index/index/key/... with **status 200** but the **page is blank**.
In devtool i can see the css and js are loaded but nothing inside the body tag.
1.folder structure
```
Inchoo
Helloworld
-Block
-Adminhtml
Helloworld.php
-Controller
-Adminhtml
-Index
Index.php
-etc
-module.xml
-adminhtml
-menu.xml
-routes.xml
-view
adminhtml
layout
-helloworld_index_index.xml
templates
-helloworld.phtml
registration.php
```
2.Block/Adminhtml/Helloworld.php
```
<?php
namespace Inchoo\Helloworld\Block;
class Helloworld extends \Magento\Framework\View\Element\Template
{
public function getHelloWorldTxt()
{
return 'Hello world!';
}
}
```
3.Controller/Adminhtml/Index/Index.php
```
<?php
namespace Inchoo\Helloworld\Controller\Adminhtml\Index;
use Magento\Framework\App\Action\Context;
class Index extends \Magento\Framework\App\Action\Action
{
protected $_resultPageFactory;
public function __construct(Context $context,
\Magento\Framework\View\Result\PageFactory $resultPageFactory)
{
$this->_resultPageFactory = $resultPageFactory;
parent::__construct($context);
}
public function execute()
{
$resultPage = $this->_resultPageFactory->create();
// print_r($resultPage);exit;
return $resultPage;
}
}
```
4.etc/module.xml
```
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/
module.xsd">
<module name="Inchoo_Helloworld" setup_version="1.0.0">
</module>
</config>
```
5.etc/adminhtml/menu.xml
```
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Backend:etc
/menu.xsd">
<menu>
<add id="Inchoo_Helloworld::first_pincollect_pincheck"
title="Greetings"
module="Inchoo_Helloworld"
sortOrder="50"
dependsOnModule="Inchoo_Helloworld"
resource="Magento_Backend::content" />
<add id="Inchoo_Helloworld::second_pincollect_pincheck"
title="Manage Pincodes"
module="Inchoo_Helloworld"
sortOrder="0"
action="helloworld/index"
parent="Inchoo_Helloworld::first_pincollect_pincheck"
resource="Magento_Backend::content" />
</menu>
</config>
```
6.etc/adminhtml/routes.xml
```
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc
/routes.xsd">
<router id="admin">
<route id="helloworld" frontName="helloworld">
<module name="Inchoo_Helloworld" />
</route>
</router>
</config>
```
7.view/adminhtml/layout/helloworld\_index\_index.xml
```
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../../../../../../../lib/
internal/Magento/Framework/View/Layout/etc/page_configuration.xsd"
layout="1column">
<body>
<referenceContainer name="content">
<block class="Inchoo\Helloworld\Block\Adminhtml\Helloworld"
name="helloworld" template="helloworld.phtml" />
</referenceContainer>
</body>
</page>
```
8.view/adminhtml/templates/helloworld.phtml
```
<p>Hello World!</p>
```
how can i debug this, please help me guys.
Thanks in advance. | 2018/01/17 | [
"https://magento.stackexchange.com/questions/209739",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/60575/"
] | I am giving you the exact code and path please copy and paste the below file.
**app/code/Inchoo/Helloworld/registration.php**
```
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Inchoo_Helloworld',
__DIR__
);
```
**app/code/Inchoo/Helloworld/Block/Adminhtml/Index/Index.php**
```
<?php
namespace Inchoo\Helloworld\Block\Adminhtml\Index;
class Index extends \Magento\Backend\Block\Widget\Container
{
public function __construct(\Magento\Backend\Block\Widget\Context $context,array $data = [])
{
parent::__construct($context, $data);
}
}
```
**app/code/Inchoo/Helloworld/Controller/Adminhtml/Index/Index.php**
```
<?php
namespace Inchoo\Helloworld\Controller\Adminhtml\Index;
class Index extends \Magento\Backend\App\Action
{
public function execute()
{
$this->_view->loadLayout();
$this->_view->getLayout()->initMessages();
$this->_view->renderLayout();
}
}
?>
```
**app/code/Inchoo/Helloworld/etc/module.xml**
```
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
<module name="Inchoo_Helloworld" setup_version="1.0.0"></module>
<sequence>
<module name="Magento_Backend"/>
<module name="Magento_Sales"/>
<module name="Magento_Quote"/>
<module name="Magento_Checkout"/>
</sequence>
</config>
```
**app/code/Inchoo/Helloworld/etc/adminhtml/routes.xml**
```
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/App/etc/routes.xsd">
<router id="admin">
<route id="helloworld" frontName="helloworld">
<module name="Inchoo_Helloworld" before="Magento_Adminhtml" />
</route>
</router>
</config>
```
**app/code/Inchoo/Helloworld/etc/adminhtml/menu.xml**
```
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../Magento/Backend/etc/menu.xsd">
<menu>
<add id="Inchoo_Helloworld::parent" title="Helloworld" module="Inchoo_Helloworld" sortOrder="100" resource="Inchoo_Helloworld::parent"/>
<add id="Inchoo_Helloworld::index" title="Helloworld Index" module="Inchoo_Helloworld" sortOrder="10" action="helloworld/index" resource="Inchoo_Helloworld::index" parent="Inchoo_Helloworld::parent"/>
</menu>
</config>
```
**app/code/Inchoo/Helloworld/view/adminhtml/layout/helloworld\_index\_index.xml**
```
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
<head>
<title>Hello World</title>
</head>
<body>
<referenceContainer name="content">
<block class="Inchoo\Helloworld\Block\Adminhtml\Index\Index" name="helloworld_block_adminhtml_index_index" template="Inchoo_Helloworld::helloworld_index_index.phtml" />
</referenceContainer>
</body>
</page>
```
**app/code/Inchoo/Helloworld/view/adminhtml/templates/helloworld\_index\_index.phtml**
```
<?php echo "Hello World template"; ?>
```
**N:B** After put all the files to the specific path don't forget to run this command from CLI -
```
php bin/magento setup:upgrade
php bin/magento cache:flush
``` | i was also facing the same issue Magento 2.3 CE. I gave the proper permissions for var and pub directories and ran the following commands-
* provided file permission for var/ and pub/
* setup:upgrade
* setup:static-content:deploy -f
* cache:flush
and it started to work. |
2,191,015 | I got this question on my homework and completed it, however, I would just like to check if my answer is correct or not. I need to convert it to units of cubic meters.
Density = 0.81 g/mL
1 gram = 0.001 kilograms 1 milliliter = 1e-6 cubic meters
[](https://i.stack.imgur.com/ZxXSq.png)
Thank you in advance! | 2017/03/17 | [
"https://math.stackexchange.com/questions/2191015",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/406344/"
] | Let $$N:=\left\{\left[\begin{matrix}1 & a & b\\0&1&0\\0&0&1\end{matrix}\right]: a,b\in\mathbb{F}\_p\right\}\simeq\mathbb{Z}\_p\times\mathbb{Z}\_p, $$
and let
$$H:=\left\{\left[\begin{matrix}1 & 0 & 0\\0&1&c\\0&0&1\end{matrix}\right]: c\in\mathbb{F}\_p\right\}\simeq\mathbb{Z}\_p;$$
then $N$ is normal and $G$ is the split extension of $N$ by $H$. | This group is the Heisenberg group over $\mathbb{F}\_p$ of order $p^3$. Now *every* non-abelian group of order $p^3$ with a prime $p>2$ is a semidirect product. To see this, we prove it for the case that we have at least two different elements $a,b$ of order $p$. This is the case for the Heisenberg group, for which *all* non-trivial elements have order $p$. Then let $N=\langle a,b\rangle$
be the product of the cyclic groups $\langle a\rangle$ and $\langle b\rangle$. Let $Q=\langle c \rangle$
with another element $c$ of order $p$. Define $\theta\colon Q\rightarrow {\rm Aut}(N)$ to be the homomorphism such that
$$
\theta(c^i)(a)=ab^i,\; \theta(c^i)(b)=b.
$$
The group $G:=N\ltimes\_{\theta}Q$ is of order $p^3$, with generators $a,b,c$ and defining relations
$$
a^p=b^p=c^p=1,\; ab=cac^{-1},\; [b,a]=[b,c]=1,
$$
where $[g,h]:=g^{-1}h^{-1}gh$ denotes the commutator of two elements.
This group is isomorphic to the Heisenberg group over $\mathbb{Z}/(p)$.
So we have
$$
G\cong N\ltimes\_{\theta}Q\cong (\mathbb{Z}/(p)\times \mathbb{Z}/(p)) \ltimes \mathbb{Z}/(p).
$$
When $p=2$, then $G\cong D\_4$, in which case the claim is also true, as we know from the dihedral group $D\_4$. |
17,277,048 | **Edit:**
I changed GLTextureUnitID from a uint to an int, and it caused the error to stop appearing, but instead of the texture, a black square renders. When I comment out the call to SetTexture it still renders fine even though I never set that uniform before that line.
**Edit2:**
It appears GLTextureUnitID has a value of 1, while the texture that is being set has an ID of 0.
**Edit3:**
Changing the SetTexture function to have the following seems to have solved the problem, but it feels like a bit of a dirty solution.
```
GL.BindTexture(TextureTarget.Texture2D, (int)texture.GLTextureUnitID);
GL.Uniform1(GLTextureUnitLocation, 0);
```
**Original Question:**
I started adding support for texture files to my project but whenever I call GL.Uniform1 for my textured shader program, I get an "InvalidOperation" error. Ever stranger, when I comment out the call to the function that causes the error, the texture still gets rendered.
The RenderGUI function in which the quad with a texture is being rendered is:
```
public override void RenderGUI()
{
// Translate Matrix to Position of GUI Element
Matrices.Translate(SetMatrixParam.ModelViewMatrix, Position.X, Position.Y, 0);
// Bind Shaders and Send Matrices
Shader.Bind();
Shader.SendMatrices();
// Set Texture Information
Shader.SetTexture(Texture); // <- This causes the error, it's just a call to Uniform1 using a property from the texture object, if commented out the error doesn't appear.
Shader.SetTextureColor(Color4.White);
GL.Begin(BeginMode.Triangles);
// Render Quad
Vector3 topLeft = new Vector3(0, 0, 0);
Vector3 bottomLeft = new Vector3(0, Size.Y, 0);
Vector3 topRight = new Vector3(Size.X, 0, 0);
Vector3 bottomRight = new Vector3(Size.X, Size.Y, 0);
Shader.SetTextureCoord(0, 0); GL.Vertex3(topLeft); // Top Left
Shader.SetTextureCoord(0, 1); GL.Vertex3(bottomLeft); // Bottom Left
Shader.SetTextureCoord(1, 1); GL.Vertex3(bottomRight); // Bottom Right
Shader.SetTextureCoord(0, 0); GL.Vertex3(topLeft); // Top Left
Shader.SetTextureCoord(1, 1); GL.Vertex3(bottomRight); // Bottom Right
Shader.SetTextureCoord(1, 0); GL.Vertex3(topRight); // Top Right
GL.End();
}
```
And the function that's being called that's causing an error to appear:
```
public void SetTexture(Texture2D texture)
{
if (texture.GLTextureUnitID == null)
throw new ArgumentException();
GL.Uniform1(GLTextureUnitLocation, (uint)texture.GLTextureUnitID);
}
```
[This can also be found at the github for this project.](https://github.com/LaylConway/TrenchWars/blob/master/EngineClient/GUI/Elements/GUITextureRenderer.cs) along with the [Texture2D class](https://github.com/LaylConway/TrenchWars/blob/master/EngineClient/Graphics/Textures/Texture2D.cs) and the [vertex](https://github.com/LaylConway/TrenchWars/blob/master/EngineClient/Graphics/Shaders/Texture2DVertex.glvs) and [fragment](https://github.com/LaylConway/TrenchWars/blob/master/EngineClient/Graphics/Shaders/Texture2DFragment.glfs) shader being used and the [class handling the shader program that uses those shaders](https://github.com/LaylConway/TrenchWars/blob/master/EngineClient/Graphics/ShaderPrograms/Texture2DShaderProgram.cs). | 2013/06/24 | [
"https://Stackoverflow.com/questions/17277048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1273560/"
] | This is what works with Symfony 2.7:
```
$builder->add('license', 'entity', [
'class' => 'CmfcmfMediaModule:License\LicenseEntity',
'preferred_choices' => function (LicenseEntity $license) {
return !$license->isOutdated();
},
// ...
])
```
`preferred_choices` needs an anonymous function which is called for each entity and must return true or false depending on whether it's preferred or not. | I believe you need to pass into your form an `EntityRepository` (or similar) and actually provide a collection of entities to `preferred_choices`. From memory, in previous versions of Symfony it would permit an array of entity IDs, but not now.
Probably `preferred_choices` should also be a callback, like `query_builder`.
The code that actually determines if something from `preferred_choices` matches a particular choices is below. It's just a simple PHP `array_search()`.
**Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceList [#](https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Form/Extension/Core/ChoiceList/ChoiceList.php#L386)**
```
protected function isPreferred($choice, array $preferredChoices)
{
return false !== array_search($choice, $preferredChoices, true);
}
``` |
17,277,048 | **Edit:**
I changed GLTextureUnitID from a uint to an int, and it caused the error to stop appearing, but instead of the texture, a black square renders. When I comment out the call to SetTexture it still renders fine even though I never set that uniform before that line.
**Edit2:**
It appears GLTextureUnitID has a value of 1, while the texture that is being set has an ID of 0.
**Edit3:**
Changing the SetTexture function to have the following seems to have solved the problem, but it feels like a bit of a dirty solution.
```
GL.BindTexture(TextureTarget.Texture2D, (int)texture.GLTextureUnitID);
GL.Uniform1(GLTextureUnitLocation, 0);
```
**Original Question:**
I started adding support for texture files to my project but whenever I call GL.Uniform1 for my textured shader program, I get an "InvalidOperation" error. Ever stranger, when I comment out the call to the function that causes the error, the texture still gets rendered.
The RenderGUI function in which the quad with a texture is being rendered is:
```
public override void RenderGUI()
{
// Translate Matrix to Position of GUI Element
Matrices.Translate(SetMatrixParam.ModelViewMatrix, Position.X, Position.Y, 0);
// Bind Shaders and Send Matrices
Shader.Bind();
Shader.SendMatrices();
// Set Texture Information
Shader.SetTexture(Texture); // <- This causes the error, it's just a call to Uniform1 using a property from the texture object, if commented out the error doesn't appear.
Shader.SetTextureColor(Color4.White);
GL.Begin(BeginMode.Triangles);
// Render Quad
Vector3 topLeft = new Vector3(0, 0, 0);
Vector3 bottomLeft = new Vector3(0, Size.Y, 0);
Vector3 topRight = new Vector3(Size.X, 0, 0);
Vector3 bottomRight = new Vector3(Size.X, Size.Y, 0);
Shader.SetTextureCoord(0, 0); GL.Vertex3(topLeft); // Top Left
Shader.SetTextureCoord(0, 1); GL.Vertex3(bottomLeft); // Bottom Left
Shader.SetTextureCoord(1, 1); GL.Vertex3(bottomRight); // Bottom Right
Shader.SetTextureCoord(0, 0); GL.Vertex3(topLeft); // Top Left
Shader.SetTextureCoord(1, 1); GL.Vertex3(bottomRight); // Bottom Right
Shader.SetTextureCoord(1, 0); GL.Vertex3(topRight); // Top Right
GL.End();
}
```
And the function that's being called that's causing an error to appear:
```
public void SetTexture(Texture2D texture)
{
if (texture.GLTextureUnitID == null)
throw new ArgumentException();
GL.Uniform1(GLTextureUnitLocation, (uint)texture.GLTextureUnitID);
}
```
[This can also be found at the github for this project.](https://github.com/LaylConway/TrenchWars/blob/master/EngineClient/GUI/Elements/GUITextureRenderer.cs) along with the [Texture2D class](https://github.com/LaylConway/TrenchWars/blob/master/EngineClient/Graphics/Textures/Texture2D.cs) and the [vertex](https://github.com/LaylConway/TrenchWars/blob/master/EngineClient/Graphics/Shaders/Texture2DVertex.glvs) and [fragment](https://github.com/LaylConway/TrenchWars/blob/master/EngineClient/Graphics/Shaders/Texture2DFragment.glfs) shader being used and the [class handling the shader program that uses those shaders](https://github.com/LaylConway/TrenchWars/blob/master/EngineClient/Graphics/ShaderPrograms/Texture2DShaderProgram.cs). | 2013/06/24 | [
"https://Stackoverflow.com/questions/17277048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1273560/"
] | I believe you need to pass into your form an `EntityRepository` (or similar) and actually provide a collection of entities to `preferred_choices`. From memory, in previous versions of Symfony it would permit an array of entity IDs, but not now.
Probably `preferred_choices` should also be a callback, like `query_builder`.
The code that actually determines if something from `preferred_choices` matches a particular choices is below. It's just a simple PHP `array_search()`.
**Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceList [#](https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Form/Extension/Core/ChoiceList/ChoiceList.php#L386)**
```
protected function isPreferred($choice, array $preferredChoices)
{
return false !== array_search($choice, $preferredChoices, true);
}
``` | From your example, where you want to get the first result as the prefered choice, you have to return the entity with the first rank and not its index.
To do so, you can retrive it in the controller then pass it as a parameter in `$options`:
```
public function buildForm(FormBuilderInterface $builder, array $options)
{
//prevent error if $options['prefered_choices'] is not set
$prefered_choices = isset($options['prefered_choices']) ? $options['prefered_choices'] : array();
$builder->add('candStatus', 'entity', array(
'label' => 'Candidate Status',
'class' => 'AmberAtsBundle:SelCandStatus',
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('sc')
->orderBy('sc.rank', 'ASC')
;
},
'property' => 'candStatus',
'preferred_choices' => $prefered_choices,
));
//...
}
```
You can also use `getReference`, as j\_goldman noted [in their comment](https://stackoverflow.com/questions/17277046/preferred-choices-for-entity-field-symfony2#comment30671334_17277046), but since your ranks can change (I think), I don't think it fit well for your use case:
```
$builder->add('candStatus', 'entity', array(
'label' => 'Candidate Status',
'class' => 'AmberAtsBundle:SelCandStatus',
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('sc')
->orderBy('sc.rank', 'ASC')
;
},
'property' => 'candStatus',
'prefered_choices' => $this->em->getReference('AmberAtsBundle:SelCandStatus', 1),
));
```
Finally, you can use a callback returning the chosen entity, for example with the same DQL you used with a limit of 1: (It's what I would do)
```
$builder->add('candStatus', 'entity', array(
'label' => 'Candidate Status',
'class' => 'AmberAtsBundle:SelCandStatus',
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('sc')
->orderBy('sc.rank', 'ASC')
;
},
'property' => 'candStatus',
'preferred_choices' => function(EntityRepository $er) {
return $er->createQueryBuilder('sc')
->orderBy('sc.rank', 'ASC')
->setMaxResults(1)
;
},
));
``` |
17,277,048 | **Edit:**
I changed GLTextureUnitID from a uint to an int, and it caused the error to stop appearing, but instead of the texture, a black square renders. When I comment out the call to SetTexture it still renders fine even though I never set that uniform before that line.
**Edit2:**
It appears GLTextureUnitID has a value of 1, while the texture that is being set has an ID of 0.
**Edit3:**
Changing the SetTexture function to have the following seems to have solved the problem, but it feels like a bit of a dirty solution.
```
GL.BindTexture(TextureTarget.Texture2D, (int)texture.GLTextureUnitID);
GL.Uniform1(GLTextureUnitLocation, 0);
```
**Original Question:**
I started adding support for texture files to my project but whenever I call GL.Uniform1 for my textured shader program, I get an "InvalidOperation" error. Ever stranger, when I comment out the call to the function that causes the error, the texture still gets rendered.
The RenderGUI function in which the quad with a texture is being rendered is:
```
public override void RenderGUI()
{
// Translate Matrix to Position of GUI Element
Matrices.Translate(SetMatrixParam.ModelViewMatrix, Position.X, Position.Y, 0);
// Bind Shaders and Send Matrices
Shader.Bind();
Shader.SendMatrices();
// Set Texture Information
Shader.SetTexture(Texture); // <- This causes the error, it's just a call to Uniform1 using a property from the texture object, if commented out the error doesn't appear.
Shader.SetTextureColor(Color4.White);
GL.Begin(BeginMode.Triangles);
// Render Quad
Vector3 topLeft = new Vector3(0, 0, 0);
Vector3 bottomLeft = new Vector3(0, Size.Y, 0);
Vector3 topRight = new Vector3(Size.X, 0, 0);
Vector3 bottomRight = new Vector3(Size.X, Size.Y, 0);
Shader.SetTextureCoord(0, 0); GL.Vertex3(topLeft); // Top Left
Shader.SetTextureCoord(0, 1); GL.Vertex3(bottomLeft); // Bottom Left
Shader.SetTextureCoord(1, 1); GL.Vertex3(bottomRight); // Bottom Right
Shader.SetTextureCoord(0, 0); GL.Vertex3(topLeft); // Top Left
Shader.SetTextureCoord(1, 1); GL.Vertex3(bottomRight); // Bottom Right
Shader.SetTextureCoord(1, 0); GL.Vertex3(topRight); // Top Right
GL.End();
}
```
And the function that's being called that's causing an error to appear:
```
public void SetTexture(Texture2D texture)
{
if (texture.GLTextureUnitID == null)
throw new ArgumentException();
GL.Uniform1(GLTextureUnitLocation, (uint)texture.GLTextureUnitID);
}
```
[This can also be found at the github for this project.](https://github.com/LaylConway/TrenchWars/blob/master/EngineClient/GUI/Elements/GUITextureRenderer.cs) along with the [Texture2D class](https://github.com/LaylConway/TrenchWars/blob/master/EngineClient/Graphics/Textures/Texture2D.cs) and the [vertex](https://github.com/LaylConway/TrenchWars/blob/master/EngineClient/Graphics/Shaders/Texture2DVertex.glvs) and [fragment](https://github.com/LaylConway/TrenchWars/blob/master/EngineClient/Graphics/Shaders/Texture2DFragment.glfs) shader being used and the [class handling the shader program that uses those shaders](https://github.com/LaylConway/TrenchWars/blob/master/EngineClient/Graphics/ShaderPrograms/Texture2DShaderProgram.cs). | 2013/06/24 | [
"https://Stackoverflow.com/questions/17277048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1273560/"
] | I believe you need to pass into your form an `EntityRepository` (or similar) and actually provide a collection of entities to `preferred_choices`. From memory, in previous versions of Symfony it would permit an array of entity IDs, but not now.
Probably `preferred_choices` should also be a callback, like `query_builder`.
The code that actually determines if something from `preferred_choices` matches a particular choices is below. It's just a simple PHP `array_search()`.
**Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceList [#](https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Form/Extension/Core/ChoiceList/ChoiceList.php#L386)**
```
protected function isPreferred($choice, array $preferredChoices)
{
return false !== array_search($choice, $preferredChoices, true);
}
``` | In Symfony3 the following works for me:
```
'preferred_choices' => function($entity) {
$preferred = [1, 2];
$choices = [];
if(in_array($entity->getId(), $preferred)) {
$choices[] = $entity;
}
return $choices;
},
``` |
17,277,048 | **Edit:**
I changed GLTextureUnitID from a uint to an int, and it caused the error to stop appearing, but instead of the texture, a black square renders. When I comment out the call to SetTexture it still renders fine even though I never set that uniform before that line.
**Edit2:**
It appears GLTextureUnitID has a value of 1, while the texture that is being set has an ID of 0.
**Edit3:**
Changing the SetTexture function to have the following seems to have solved the problem, but it feels like a bit of a dirty solution.
```
GL.BindTexture(TextureTarget.Texture2D, (int)texture.GLTextureUnitID);
GL.Uniform1(GLTextureUnitLocation, 0);
```
**Original Question:**
I started adding support for texture files to my project but whenever I call GL.Uniform1 for my textured shader program, I get an "InvalidOperation" error. Ever stranger, when I comment out the call to the function that causes the error, the texture still gets rendered.
The RenderGUI function in which the quad with a texture is being rendered is:
```
public override void RenderGUI()
{
// Translate Matrix to Position of GUI Element
Matrices.Translate(SetMatrixParam.ModelViewMatrix, Position.X, Position.Y, 0);
// Bind Shaders and Send Matrices
Shader.Bind();
Shader.SendMatrices();
// Set Texture Information
Shader.SetTexture(Texture); // <- This causes the error, it's just a call to Uniform1 using a property from the texture object, if commented out the error doesn't appear.
Shader.SetTextureColor(Color4.White);
GL.Begin(BeginMode.Triangles);
// Render Quad
Vector3 topLeft = new Vector3(0, 0, 0);
Vector3 bottomLeft = new Vector3(0, Size.Y, 0);
Vector3 topRight = new Vector3(Size.X, 0, 0);
Vector3 bottomRight = new Vector3(Size.X, Size.Y, 0);
Shader.SetTextureCoord(0, 0); GL.Vertex3(topLeft); // Top Left
Shader.SetTextureCoord(0, 1); GL.Vertex3(bottomLeft); // Bottom Left
Shader.SetTextureCoord(1, 1); GL.Vertex3(bottomRight); // Bottom Right
Shader.SetTextureCoord(0, 0); GL.Vertex3(topLeft); // Top Left
Shader.SetTextureCoord(1, 1); GL.Vertex3(bottomRight); // Bottom Right
Shader.SetTextureCoord(1, 0); GL.Vertex3(topRight); // Top Right
GL.End();
}
```
And the function that's being called that's causing an error to appear:
```
public void SetTexture(Texture2D texture)
{
if (texture.GLTextureUnitID == null)
throw new ArgumentException();
GL.Uniform1(GLTextureUnitLocation, (uint)texture.GLTextureUnitID);
}
```
[This can also be found at the github for this project.](https://github.com/LaylConway/TrenchWars/blob/master/EngineClient/GUI/Elements/GUITextureRenderer.cs) along with the [Texture2D class](https://github.com/LaylConway/TrenchWars/blob/master/EngineClient/Graphics/Textures/Texture2D.cs) and the [vertex](https://github.com/LaylConway/TrenchWars/blob/master/EngineClient/Graphics/Shaders/Texture2DVertex.glvs) and [fragment](https://github.com/LaylConway/TrenchWars/blob/master/EngineClient/Graphics/Shaders/Texture2DFragment.glfs) shader being used and the [class handling the shader program that uses those shaders](https://github.com/LaylConway/TrenchWars/blob/master/EngineClient/Graphics/ShaderPrograms/Texture2DShaderProgram.cs). | 2013/06/24 | [
"https://Stackoverflow.com/questions/17277048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1273560/"
] | This is what works with Symfony 2.7:
```
$builder->add('license', 'entity', [
'class' => 'CmfcmfMediaModule:License\LicenseEntity',
'preferred_choices' => function (LicenseEntity $license) {
return !$license->isOutdated();
},
// ...
])
```
`preferred_choices` needs an anonymous function which is called for each entity and must return true or false depending on whether it's preferred or not. | From your example, where you want to get the first result as the prefered choice, you have to return the entity with the first rank and not its index.
To do so, you can retrive it in the controller then pass it as a parameter in `$options`:
```
public function buildForm(FormBuilderInterface $builder, array $options)
{
//prevent error if $options['prefered_choices'] is not set
$prefered_choices = isset($options['prefered_choices']) ? $options['prefered_choices'] : array();
$builder->add('candStatus', 'entity', array(
'label' => 'Candidate Status',
'class' => 'AmberAtsBundle:SelCandStatus',
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('sc')
->orderBy('sc.rank', 'ASC')
;
},
'property' => 'candStatus',
'preferred_choices' => $prefered_choices,
));
//...
}
```
You can also use `getReference`, as j\_goldman noted [in their comment](https://stackoverflow.com/questions/17277046/preferred-choices-for-entity-field-symfony2#comment30671334_17277046), but since your ranks can change (I think), I don't think it fit well for your use case:
```
$builder->add('candStatus', 'entity', array(
'label' => 'Candidate Status',
'class' => 'AmberAtsBundle:SelCandStatus',
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('sc')
->orderBy('sc.rank', 'ASC')
;
},
'property' => 'candStatus',
'prefered_choices' => $this->em->getReference('AmberAtsBundle:SelCandStatus', 1),
));
```
Finally, you can use a callback returning the chosen entity, for example with the same DQL you used with a limit of 1: (It's what I would do)
```
$builder->add('candStatus', 'entity', array(
'label' => 'Candidate Status',
'class' => 'AmberAtsBundle:SelCandStatus',
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('sc')
->orderBy('sc.rank', 'ASC')
;
},
'property' => 'candStatus',
'preferred_choices' => function(EntityRepository $er) {
return $er->createQueryBuilder('sc')
->orderBy('sc.rank', 'ASC')
->setMaxResults(1)
;
},
));
``` |
17,277,048 | **Edit:**
I changed GLTextureUnitID from a uint to an int, and it caused the error to stop appearing, but instead of the texture, a black square renders. When I comment out the call to SetTexture it still renders fine even though I never set that uniform before that line.
**Edit2:**
It appears GLTextureUnitID has a value of 1, while the texture that is being set has an ID of 0.
**Edit3:**
Changing the SetTexture function to have the following seems to have solved the problem, but it feels like a bit of a dirty solution.
```
GL.BindTexture(TextureTarget.Texture2D, (int)texture.GLTextureUnitID);
GL.Uniform1(GLTextureUnitLocation, 0);
```
**Original Question:**
I started adding support for texture files to my project but whenever I call GL.Uniform1 for my textured shader program, I get an "InvalidOperation" error. Ever stranger, when I comment out the call to the function that causes the error, the texture still gets rendered.
The RenderGUI function in which the quad with a texture is being rendered is:
```
public override void RenderGUI()
{
// Translate Matrix to Position of GUI Element
Matrices.Translate(SetMatrixParam.ModelViewMatrix, Position.X, Position.Y, 0);
// Bind Shaders and Send Matrices
Shader.Bind();
Shader.SendMatrices();
// Set Texture Information
Shader.SetTexture(Texture); // <- This causes the error, it's just a call to Uniform1 using a property from the texture object, if commented out the error doesn't appear.
Shader.SetTextureColor(Color4.White);
GL.Begin(BeginMode.Triangles);
// Render Quad
Vector3 topLeft = new Vector3(0, 0, 0);
Vector3 bottomLeft = new Vector3(0, Size.Y, 0);
Vector3 topRight = new Vector3(Size.X, 0, 0);
Vector3 bottomRight = new Vector3(Size.X, Size.Y, 0);
Shader.SetTextureCoord(0, 0); GL.Vertex3(topLeft); // Top Left
Shader.SetTextureCoord(0, 1); GL.Vertex3(bottomLeft); // Bottom Left
Shader.SetTextureCoord(1, 1); GL.Vertex3(bottomRight); // Bottom Right
Shader.SetTextureCoord(0, 0); GL.Vertex3(topLeft); // Top Left
Shader.SetTextureCoord(1, 1); GL.Vertex3(bottomRight); // Bottom Right
Shader.SetTextureCoord(1, 0); GL.Vertex3(topRight); // Top Right
GL.End();
}
```
And the function that's being called that's causing an error to appear:
```
public void SetTexture(Texture2D texture)
{
if (texture.GLTextureUnitID == null)
throw new ArgumentException();
GL.Uniform1(GLTextureUnitLocation, (uint)texture.GLTextureUnitID);
}
```
[This can also be found at the github for this project.](https://github.com/LaylConway/TrenchWars/blob/master/EngineClient/GUI/Elements/GUITextureRenderer.cs) along with the [Texture2D class](https://github.com/LaylConway/TrenchWars/blob/master/EngineClient/Graphics/Textures/Texture2D.cs) and the [vertex](https://github.com/LaylConway/TrenchWars/blob/master/EngineClient/Graphics/Shaders/Texture2DVertex.glvs) and [fragment](https://github.com/LaylConway/TrenchWars/blob/master/EngineClient/Graphics/Shaders/Texture2DFragment.glfs) shader being used and the [class handling the shader program that uses those shaders](https://github.com/LaylConway/TrenchWars/blob/master/EngineClient/Graphics/ShaderPrograms/Texture2DShaderProgram.cs). | 2013/06/24 | [
"https://Stackoverflow.com/questions/17277048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1273560/"
] | This is what works with Symfony 2.7:
```
$builder->add('license', 'entity', [
'class' => 'CmfcmfMediaModule:License\LicenseEntity',
'preferred_choices' => function (LicenseEntity $license) {
return !$license->isOutdated();
},
// ...
])
```
`preferred_choices` needs an anonymous function which is called for each entity and must return true or false depending on whether it's preferred or not. | In Symfony3 the following works for me:
```
'preferred_choices' => function($entity) {
$preferred = [1, 2];
$choices = [];
if(in_array($entity->getId(), $preferred)) {
$choices[] = $entity;
}
return $choices;
},
``` |
17,277,048 | **Edit:**
I changed GLTextureUnitID from a uint to an int, and it caused the error to stop appearing, but instead of the texture, a black square renders. When I comment out the call to SetTexture it still renders fine even though I never set that uniform before that line.
**Edit2:**
It appears GLTextureUnitID has a value of 1, while the texture that is being set has an ID of 0.
**Edit3:**
Changing the SetTexture function to have the following seems to have solved the problem, but it feels like a bit of a dirty solution.
```
GL.BindTexture(TextureTarget.Texture2D, (int)texture.GLTextureUnitID);
GL.Uniform1(GLTextureUnitLocation, 0);
```
**Original Question:**
I started adding support for texture files to my project but whenever I call GL.Uniform1 for my textured shader program, I get an "InvalidOperation" error. Ever stranger, when I comment out the call to the function that causes the error, the texture still gets rendered.
The RenderGUI function in which the quad with a texture is being rendered is:
```
public override void RenderGUI()
{
// Translate Matrix to Position of GUI Element
Matrices.Translate(SetMatrixParam.ModelViewMatrix, Position.X, Position.Y, 0);
// Bind Shaders and Send Matrices
Shader.Bind();
Shader.SendMatrices();
// Set Texture Information
Shader.SetTexture(Texture); // <- This causes the error, it's just a call to Uniform1 using a property from the texture object, if commented out the error doesn't appear.
Shader.SetTextureColor(Color4.White);
GL.Begin(BeginMode.Triangles);
// Render Quad
Vector3 topLeft = new Vector3(0, 0, 0);
Vector3 bottomLeft = new Vector3(0, Size.Y, 0);
Vector3 topRight = new Vector3(Size.X, 0, 0);
Vector3 bottomRight = new Vector3(Size.X, Size.Y, 0);
Shader.SetTextureCoord(0, 0); GL.Vertex3(topLeft); // Top Left
Shader.SetTextureCoord(0, 1); GL.Vertex3(bottomLeft); // Bottom Left
Shader.SetTextureCoord(1, 1); GL.Vertex3(bottomRight); // Bottom Right
Shader.SetTextureCoord(0, 0); GL.Vertex3(topLeft); // Top Left
Shader.SetTextureCoord(1, 1); GL.Vertex3(bottomRight); // Bottom Right
Shader.SetTextureCoord(1, 0); GL.Vertex3(topRight); // Top Right
GL.End();
}
```
And the function that's being called that's causing an error to appear:
```
public void SetTexture(Texture2D texture)
{
if (texture.GLTextureUnitID == null)
throw new ArgumentException();
GL.Uniform1(GLTextureUnitLocation, (uint)texture.GLTextureUnitID);
}
```
[This can also be found at the github for this project.](https://github.com/LaylConway/TrenchWars/blob/master/EngineClient/GUI/Elements/GUITextureRenderer.cs) along with the [Texture2D class](https://github.com/LaylConway/TrenchWars/blob/master/EngineClient/Graphics/Textures/Texture2D.cs) and the [vertex](https://github.com/LaylConway/TrenchWars/blob/master/EngineClient/Graphics/Shaders/Texture2DVertex.glvs) and [fragment](https://github.com/LaylConway/TrenchWars/blob/master/EngineClient/Graphics/Shaders/Texture2DFragment.glfs) shader being used and the [class handling the shader program that uses those shaders](https://github.com/LaylConway/TrenchWars/blob/master/EngineClient/Graphics/ShaderPrograms/Texture2DShaderProgram.cs). | 2013/06/24 | [
"https://Stackoverflow.com/questions/17277048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1273560/"
] | From your example, where you want to get the first result as the prefered choice, you have to return the entity with the first rank and not its index.
To do so, you can retrive it in the controller then pass it as a parameter in `$options`:
```
public function buildForm(FormBuilderInterface $builder, array $options)
{
//prevent error if $options['prefered_choices'] is not set
$prefered_choices = isset($options['prefered_choices']) ? $options['prefered_choices'] : array();
$builder->add('candStatus', 'entity', array(
'label' => 'Candidate Status',
'class' => 'AmberAtsBundle:SelCandStatus',
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('sc')
->orderBy('sc.rank', 'ASC')
;
},
'property' => 'candStatus',
'preferred_choices' => $prefered_choices,
));
//...
}
```
You can also use `getReference`, as j\_goldman noted [in their comment](https://stackoverflow.com/questions/17277046/preferred-choices-for-entity-field-symfony2#comment30671334_17277046), but since your ranks can change (I think), I don't think it fit well for your use case:
```
$builder->add('candStatus', 'entity', array(
'label' => 'Candidate Status',
'class' => 'AmberAtsBundle:SelCandStatus',
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('sc')
->orderBy('sc.rank', 'ASC')
;
},
'property' => 'candStatus',
'prefered_choices' => $this->em->getReference('AmberAtsBundle:SelCandStatus', 1),
));
```
Finally, you can use a callback returning the chosen entity, for example with the same DQL you used with a limit of 1: (It's what I would do)
```
$builder->add('candStatus', 'entity', array(
'label' => 'Candidate Status',
'class' => 'AmberAtsBundle:SelCandStatus',
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('sc')
->orderBy('sc.rank', 'ASC')
;
},
'property' => 'candStatus',
'preferred_choices' => function(EntityRepository $er) {
return $er->createQueryBuilder('sc')
->orderBy('sc.rank', 'ASC')
->setMaxResults(1)
;
},
));
``` | In Symfony3 the following works for me:
```
'preferred_choices' => function($entity) {
$preferred = [1, 2];
$choices = [];
if(in_array($entity->getId(), $preferred)) {
$choices[] = $entity;
}
return $choices;
},
``` |
13,894,196 | I am trying to draw colored text in my `UIView` subclass. Right now I am using the Single View app template (for testing). There are no modifications except the `drawRect:` method.
The text is drawn but it is always black no matter what I set the color to.
```
- (void)drawRect:(CGRect)rect
{
UIFont* font = [UIFont fontWithName:@"Arial" size:72];
UIColor* textColor = [UIColor redColor];
NSDictionary* stringAttrs = @{ UITextAttributeFont : font, UITextAttributeTextColor : textColor };
NSAttributedString* attrStr = [[NSAttributedString alloc] initWithString:@"Hello" attributes:stringAttrs];
[attrStr drawAtPoint:CGPointMake(10.f, 10.f)];
}
```
I've also tried `[[UIColor redColor] set]` to no avail.
**Answer:**
>
> NSDictionary\* stringAttrs = @{ NSFontAttributeName : font,
> NSForegroundColorAttributeName : textColor };
>
>
> | 2012/12/15 | [
"https://Stackoverflow.com/questions/13894196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1419236/"
] | Instead of `UITextAttributeTextColor` you should use `NSForegroundColorAttributeName`. Hope this helps! | You can try with following methods. It will help you to draw text in UIView at the bottom right corner with the help of following attributes.
* NSFontAttributeName - Font name with size
* NSStrokeWidthAttributeName - Stroke Width
* NSStrokeColorAttributeName - Text Color
**Objective-C** - Draw text in the UIView and return as UIImage.
```
-(UIImage *) imageWithView:(UIView *)view text:(NSString *)text {
UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
// Setup the font specific variables
NSDictionary *attributes = @{
NSFontAttributeName : [UIFont fontWithName:@"Helvetica" size:12],
NSStrokeWidthAttributeName : @(0),
NSStrokeColorAttributeName : [UIColor blackColor]
};
// Draw text with CGPoint and attributes
[text drawAtPoint:CGPointMake(view.frame.origin.x+10 , view.frame.size.height-25) withAttributes:attributes];
UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}`
```
**Swift** - Draw text in the UIView and return as UIImage.
```
func imageWithView(view : UIView, text : NSString) -> UIImage {
UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
view.layer.renderInContext(UIGraphicsGetCurrentContext()!);
// Setup the font specific variables
let attributes :[String:AnyObject] = [
NSFontAttributeName : UIFont(name: "Helvetica", size: 12)!,
NSStrokeWidthAttributeName : 0,
NSForegroundColorAttributeName : UIColor.blackColor()
]
// Draw text with CGPoint and attributes
text.drawAtPoint(CGPointMake(view.frame.origin.x+10, view.frame.size.height-25), withAttributes: attributes);
let img:UIImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}`
``` |
72,688,814 | I'm currently developing a React Native app with Typescript.
I have a massive data download from server and a function for saving all data in it's corresponding table.
```
static insertVariousTable = (table: TypeTables) => {
switch (table) {
case 'clase':
return Clase.insertVarious;
case 'estadoequipo':
return EstadoEquipo.insertVarious;
case 'formapesopatron':
return FormaPesoPatron.insertVarious;
}
};
```
When I call the function the type is: (note that the return types could be any of them, I mean "or" (|) instead of "and" (&) and that's ok for me)
```
let insertVarious: ((rows: ClaseType[]) => Promise<unknown>) | ((rows: TypeEstadoEquipo[]) => Promise<unknown>) | ((rows: FormaPesoPatronType[]) => Promise<...>) | undefined
```
But when I'm trying to call the function with await (inside an async function) it changes the types of the function parameters to "and" (&).
```
async function download(res:IRes){
for (key in res.data) {
if (Object.prototype.hasOwnProperty.call(res.data, key)) {
const tabla = res.data[key];
let insertVarious = DbRequests.insertVariousTable(key);
if (insertVarious) {
await insertVarious(tabla);
}
}
}
}
```
The "await insertVarios(tabla)" parameter type becomes: (with "and" (&))
```
let insertVarious: (rows: ClaseType[] & TypeEstadoEquipo[] & FormaPesoPatronType[]) => Promise<unknown>
```
I need the type to be "or" (|) so I can send any of them, how can I fix this?
Please help....
Thanks in advance | 2022/06/20 | [
"https://Stackoverflow.com/questions/72688814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19375821/"
] | If by "simplify", you mean "shorten", then this is as good as it gets:
```
public get isUsersLimitReached(): boolean {
return !this.isAdmin && usersCount >= this.max_users;
}
```
Other than that, there's really not much to work with here. | A user limit is reached only if the user is not admin and count exceeds.
```
public get isUsersLimitReached(): boolean {
return !this.isAdmin && usersCount >= this.max_users;
}
``` |
35,453 | As the title, how can you determine how much damage a conjured weapon is doing? Is there anyway to view this stat? | 2011/11/12 | [
"https://gaming.stackexchange.com/questions/35453",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/14095/"
] | With the conjured weapon equipped, go into the item menu and select the weapons tab. (Note: you can only see this tab if you actually have some real weapon in your inventory.)
On the bottom of the screen it will show you the damage of your conjured weapon.
It's kind of a roundabout way, but I haven't found another method of seeing the damage of a conjured weapon. | Uh on my character, with 100 conjuring, and 100 archery, and with all the damage boosting perks for bound wepons, my bound bow only does *slightly* better than an un-upgraded daedric bow. Bound weapons do the same damage as their daedric counterparts (with the necessary perks) except for the war axe (for whatever reason, its equivilant is ebony) |
44,737,141 | i'm trying to make a blog using angular 1.6, all works fine except when i created a service and inject into config file. Test directive works fine, only breaks when inject myService service/factory.
app.coffee
```
app = angular.module 'dts',['ngRoute']
app.service 'myService', ->
this.asd = ""
app.directive 'ngHello', ->
return {
restrict:'E'
replace: true
template: "<h1>Hola mundo</h1>"
link: (scope,element,attrs)->
}
```
config.coffee
```
app = angular.module 'dts'
app.config ["$locationProvider","$routeProvider","myService", ($locationProvider,$routeProvider,myService)->
$routeProvider
.when "/",
controller: "mainCtrl"
templateUrl: "/app/views/index.html"
.when "/blog",
controller: "blogCtrl"
templateUrl: "/app/views/blog/index.html"
.when "/blog/post/:id",
controller: "blogCtrl"
templateUrl: "/app/views/blog/single.html"
.when "/contact",
controller: "contactCtrl"
templateUrl: "/app/views/contact.html"
.otherwise '/'
$locationProvider.html5Mode
enabled: true
requireBase: false
]
```
script includes
```
script(src="/js/libs/angular.min.js")
script(src="/app/modules/angular-route.min.js")
script(src="/app/app.js")
script(src="/app/services/slugs.js")
script(src="/app/config.js")
script(src="/app/controllers/main.js")
script(src="/app/controllers/blog.js")
```
What i'm doing wrong?
I searched about problems or deprecating about service or factory on 1.6 version, but i can't find nothing. I downgrade angular to 1.5.6 and does not works too.
I tried to move service/factory to app file, but breaks too (before i create it on services.js) | 2017/06/24 | [
"https://Stackoverflow.com/questions/44737141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6484286/"
] | you have to inject `myServiceProvider` in config , you cannot inject service in config function | From the Docs:
>
> Module Loading & Dependencies
> =============================
>
>
> * **Configuration blocks** - get executed during the provider registrations and configuration phase. **Only providers and constants can be injected into configuration blocks.** This is to prevent accidental instantiation of services before they have been fully configured.
>
>
> [— AngularJS Developer Guide - Modules (Loading & Dependencies)](https://docs.angularjs.org/guide/module#module-loading-dependencies)
>
>
>
Route tables can not be created or changed by services.
On the other hand, services are injectable in the resolve functions of a route table as those functions are invoked during the run phase of an application. |
7,081,098 | I am trying to pull data from table using this select statement..
```
SELECT ID_NO
FROM EMPLOYEE
WHERE trim(SYN_NO) ='21IT';
```
SYN\_NO column hold data in this format
```
21IT / 00065421
```
I want to get just first four characters and drop rest of it.. i tried trim, rtrim but it didnt work. Is there a way to do this.. Thank you | 2011/08/16 | [
"https://Stackoverflow.com/questions/7081098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/839381/"
] | What you are trying to do is generally not possible with regular expressions. To do what you want, you have to be able to count things, which is something regular expressions can't do.
Making the matching greedy will eventually lead to matching too much, especially when you are supporting multiple line input.
To replace every occurence of parent:: you probably don't have to match the method call exactly, maybe it is enough to match something like this:
```
parent::(.*);
```
Then you can replace the parent:: with something else and use the first matching group to put whatever was in the document at this position. | Here is an example which is not really robust, but it would match the case in your question.
```
(parent::)([^\(]*)\(([^\(]*)\(([^()]*)\)
```
Here is a live regex test to experiment around: <http://rubular.com/r/WwRsRTf7E6> (Note: rubular.com is targeted at ruby, but should be similar enough for php).
The matched elements would be in this case:
```
parent::
test
new ReflectionClass
$this
```
If you want something more robust, you might want to look into parsing tools (e.g. write a short grammer, that matches php function definitions) or static code analysis tools, as these often consist of AST generators etc. I have no personal experience with this one, but it sounds quite comprehensive:
* <https://github.com/facebook/pfff>
>
> pfff is a set of tools and APIs to perform some static analysis, dynamic
> analysis, code visualizations, code navigations, or style-preserving
> source-to-source transformations such as refactorings on source code.
> For now the effort is focused on PHP ...
>
>
> |
7,081,098 | I am trying to pull data from table using this select statement..
```
SELECT ID_NO
FROM EMPLOYEE
WHERE trim(SYN_NO) ='21IT';
```
SYN\_NO column hold data in this format
```
21IT / 00065421
```
I want to get just first four characters and drop rest of it.. i tried trim, rtrim but it didnt work. Is there a way to do this.. Thank you | 2011/08/16 | [
"https://Stackoverflow.com/questions/7081098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/839381/"
] | What you are trying to do is generally not possible with regular expressions. To do what you want, you have to be able to count things, which is something regular expressions can't do.
Making the matching greedy will eventually lead to matching too much, especially when you are supporting multiple line input.
To replace every occurence of parent:: you probably don't have to match the method call exactly, maybe it is enough to match something like this:
```
parent::(.*);
```
Then you can replace the parent:: with something else and use the first matching group to put whatever was in the document at this position. | Using regexes to parse code is a REALLY bad idea. Take a look at [PHP's Tokenizer](http://php.net/manual/en/book.tokenizer.php), which you can use to parse PHP code into an array of tokens. You can than use that array to find the information you need.
You can also look at [PHP-Token-Reflection's source code](https://github.com/Andrewsville/PHP-Token-Reflection) as an example of how to get meaningful information from those tokens.
Basically, you would need to find T\_PARENT occurrences T\_STRING occurrences with 'parent' as the string contents, followed by T\_DOUBLE\_COLON, followed with another T\_STRING that contains the method name, than go forward and start counting the depth of the parentheses - whenever you get to an '(', increase the counter by one. Whenever you get to an ')', decrease the counter by one. Keep a record of everything you find in the process until the counter gets back to 0.
Something like that should work (not actually tested):
```
<?php
$tokens = tokens_get_all(...);
for ($i=0, $size = count($tokens); $i < $size; $i++( {
if ($tokens[$i][0] === T_STRING && $tokens[$i][1] === 'parent' && $tokens[++$i][0] === T_DOUBLE_COLON && $tokens[++$i][0] === T_STRING) {
$method = $tokens[$i][1];
$depth = 0;
$contents = array();
do {
$contents[] = $token = $tokens[++$i];
if ($token === '(') {
$depth++;
} elseif ($token === ')') {
$depth--;
}
} while ($depth > 0);
echo "Call to $method with contents:\n";
print_r(array_slice($contents, 1, -1)); // slices off the opening '(' and closing ')'
}
}
``` |
7,081,098 | I am trying to pull data from table using this select statement..
```
SELECT ID_NO
FROM EMPLOYEE
WHERE trim(SYN_NO) ='21IT';
```
SYN\_NO column hold data in this format
```
21IT / 00065421
```
I want to get just first four characters and drop rest of it.. i tried trim, rtrim but it didnt work. Is there a way to do this.. Thank you | 2011/08/16 | [
"https://Stackoverflow.com/questions/7081098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/839381/"
] | What you are trying to do is generally not possible with regular expressions. To do what you want, you have to be able to count things, which is something regular expressions can't do.
Making the matching greedy will eventually lead to matching too much, especially when you are supporting multiple line input.
To replace every occurence of parent:: you probably don't have to match the method call exactly, maybe it is enough to match something like this:
```
parent::(.*);
```
Then you can replace the parent:: with something else and use the first matching group to put whatever was in the document at this position. | If you are only interested in the function and whatever is inside the round brackets,
and most parent:: calls are in a single line only. This may work for you.
```
parent::(.*?)\((.*)\);
```
The first capture should stop after the first encountered `(` as this is not greedy.
The second capture will not stop until it captures the last `);` on the same line.
Note: Do not use `s` modifier as this will result in greedy matching up to the last `);` in multiple lines of your code. |
7,081,098 | I am trying to pull data from table using this select statement..
```
SELECT ID_NO
FROM EMPLOYEE
WHERE trim(SYN_NO) ='21IT';
```
SYN\_NO column hold data in this format
```
21IT / 00065421
```
I want to get just first four characters and drop rest of it.. i tried trim, rtrim but it didnt work. Is there a way to do this.. Thank you | 2011/08/16 | [
"https://Stackoverflow.com/questions/7081098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/839381/"
] | Using regexes to parse code is a REALLY bad idea. Take a look at [PHP's Tokenizer](http://php.net/manual/en/book.tokenizer.php), which you can use to parse PHP code into an array of tokens. You can than use that array to find the information you need.
You can also look at [PHP-Token-Reflection's source code](https://github.com/Andrewsville/PHP-Token-Reflection) as an example of how to get meaningful information from those tokens.
Basically, you would need to find T\_PARENT occurrences T\_STRING occurrences with 'parent' as the string contents, followed by T\_DOUBLE\_COLON, followed with another T\_STRING that contains the method name, than go forward and start counting the depth of the parentheses - whenever you get to an '(', increase the counter by one. Whenever you get to an ')', decrease the counter by one. Keep a record of everything you find in the process until the counter gets back to 0.
Something like that should work (not actually tested):
```
<?php
$tokens = tokens_get_all(...);
for ($i=0, $size = count($tokens); $i < $size; $i++( {
if ($tokens[$i][0] === T_STRING && $tokens[$i][1] === 'parent' && $tokens[++$i][0] === T_DOUBLE_COLON && $tokens[++$i][0] === T_STRING) {
$method = $tokens[$i][1];
$depth = 0;
$contents = array();
do {
$contents[] = $token = $tokens[++$i];
if ($token === '(') {
$depth++;
} elseif ($token === ')') {
$depth--;
}
} while ($depth > 0);
echo "Call to $method with contents:\n";
print_r(array_slice($contents, 1, -1)); // slices off the opening '(' and closing ')'
}
}
``` | Here is an example which is not really robust, but it would match the case in your question.
```
(parent::)([^\(]*)\(([^\(]*)\(([^()]*)\)
```
Here is a live regex test to experiment around: <http://rubular.com/r/WwRsRTf7E6> (Note: rubular.com is targeted at ruby, but should be similar enough for php).
The matched elements would be in this case:
```
parent::
test
new ReflectionClass
$this
```
If you want something more robust, you might want to look into parsing tools (e.g. write a short grammer, that matches php function definitions) or static code analysis tools, as these often consist of AST generators etc. I have no personal experience with this one, but it sounds quite comprehensive:
* <https://github.com/facebook/pfff>
>
> pfff is a set of tools and APIs to perform some static analysis, dynamic
> analysis, code visualizations, code navigations, or style-preserving
> source-to-source transformations such as refactorings on source code.
> For now the effort is focused on PHP ...
>
>
> |
7,081,098 | I am trying to pull data from table using this select statement..
```
SELECT ID_NO
FROM EMPLOYEE
WHERE trim(SYN_NO) ='21IT';
```
SYN\_NO column hold data in this format
```
21IT / 00065421
```
I want to get just first four characters and drop rest of it.. i tried trim, rtrim but it didnt work. Is there a way to do this.. Thank you | 2011/08/16 | [
"https://Stackoverflow.com/questions/7081098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/839381/"
] | Using regexes to parse code is a REALLY bad idea. Take a look at [PHP's Tokenizer](http://php.net/manual/en/book.tokenizer.php), which you can use to parse PHP code into an array of tokens. You can than use that array to find the information you need.
You can also look at [PHP-Token-Reflection's source code](https://github.com/Andrewsville/PHP-Token-Reflection) as an example of how to get meaningful information from those tokens.
Basically, you would need to find T\_PARENT occurrences T\_STRING occurrences with 'parent' as the string contents, followed by T\_DOUBLE\_COLON, followed with another T\_STRING that contains the method name, than go forward and start counting the depth of the parentheses - whenever you get to an '(', increase the counter by one. Whenever you get to an ')', decrease the counter by one. Keep a record of everything you find in the process until the counter gets back to 0.
Something like that should work (not actually tested):
```
<?php
$tokens = tokens_get_all(...);
for ($i=0, $size = count($tokens); $i < $size; $i++( {
if ($tokens[$i][0] === T_STRING && $tokens[$i][1] === 'parent' && $tokens[++$i][0] === T_DOUBLE_COLON && $tokens[++$i][0] === T_STRING) {
$method = $tokens[$i][1];
$depth = 0;
$contents = array();
do {
$contents[] = $token = $tokens[++$i];
if ($token === '(') {
$depth++;
} elseif ($token === ')') {
$depth--;
}
} while ($depth > 0);
echo "Call to $method with contents:\n";
print_r(array_slice($contents, 1, -1)); // slices off the opening '(' and closing ')'
}
}
``` | If you are only interested in the function and whatever is inside the round brackets,
and most parent:: calls are in a single line only. This may work for you.
```
parent::(.*?)\((.*)\);
```
The first capture should stop after the first encountered `(` as this is not greedy.
The second capture will not stop until it captures the last `);` on the same line.
Note: Do not use `s` modifier as this will result in greedy matching up to the last `);` in multiple lines of your code. |
2,534,192 | I'm new to Spring MVC and trying out a simple project.It will contain a simple adding, viewing, updating and deleting user work flows. It will have login page and once authenticated the user will be taken to a welcome screen which will have links to add, view, update and delete users. Clicking on any of the links will take to individual pages where the user can do the specific tasks. What I'm doing here is, I'm using a MultiActionController to group together all requests related to User work flow. So the request from "Add User" link will handled by the addUser method in the UserController which will redirect the user to the "Add User" page, and the user can then fill in the details and save the new user. Now here is where I'm getting confused. Where should I put the save process of the new user, should I put that in new method inside UserController, or use the same "addUser" method. What is the best way to handle this kind of scenario.
I hope I was able to clear my question. | 2010/03/28 | [
"https://Stackoverflow.com/questions/2534192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/177971/"
] | It's not really an answer to your question, as it's not working in Emacs, but PHP can raise notices, when you are trying to read from a variable that's not been initialized.
For more informations, see:
* [`error_reporting`](http://fr2.php.net/manual/en/errorfunc.configuration.php#ini.error-reporting), which should include [`E_NOTICE`](http://fr2.php.net/manual/en/errorfunc.constants.php)
* [`display_errors`](http://fr.php.net/manual/en/errorfunc.configuration.php#ini.display-errors) to have those notices *(and other errors)* displayed
+ which is useful when developing,
+ but it should not be enabled on a production server.
For example, with error\_reporting set to report E\_NOTICE (and others), the following portion of code:
```
$aa = 'glop';
echo strlen($a);
```
Raises this notice:
```none
Notice: Undefined variable: a in /.../temp/temp.php on line 5
```
It's not as simple as getting it in your editor, I admit -- but it will still help finding out why something doesn't work ;-) | Decent IDE's will give you the names of the variables in the current scope when you are typing them via Intellisense.
This should severely cut down on the number of times you misspell a variable name. It also allows your variable names to be more descriptive than `$foo`
---
Furthermore, you should always pay attention to undefined variable warnings, as they immediately tell you when you have made a misspelling. |
2,534,192 | I'm new to Spring MVC and trying out a simple project.It will contain a simple adding, viewing, updating and deleting user work flows. It will have login page and once authenticated the user will be taken to a welcome screen which will have links to add, view, update and delete users. Clicking on any of the links will take to individual pages where the user can do the specific tasks. What I'm doing here is, I'm using a MultiActionController to group together all requests related to User work flow. So the request from "Add User" link will handled by the addUser method in the UserController which will redirect the user to the "Add User" page, and the user can then fill in the details and save the new user. Now here is where I'm getting confused. Where should I put the save process of the new user, should I put that in new method inside UserController, or use the same "addUser" method. What is the best way to handle this kind of scenario.
I hope I was able to clear my question. | 2010/03/28 | [
"https://Stackoverflow.com/questions/2534192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/177971/"
] | Since Flymake uses the `php` binary's syntax check option (`-l`) for highlighting parse errors, there is no obvious way to catch notices and other errors without running or lexical parsing the code. If it's not a problem to not only lint but execute your script, then you can do the following.
Unfortunately, `flymake-php` defines error line patterns as constant (at least in the bundle shipped with Emacs Starter Kit), and even the flymake command is hard-coded. There is a few ways to achieve our goal and each is a pain. May be it's a quick and not so dirty solution to define our `flymake-php-init` function based on the original one.
```
(defun my-flymake-php-init ()
;; add a new error pattern to catch notices
(add-to-list 'flymake-err-line-patterns
'("\\(Notice\\): \\(.*\\) in \\(.*\\) on line \\([0-9]+\\)"
3 4 nil 2))
(let* ((temp-file (flymake-init-create-temp-buffer-copy
'flymake-create-temp-inplace))
(local-file (file-relative-name
temp-file
(file-name-directory buffer-file-name))))
;; here we removed the "-l" switch
(list "php" (list "-f" local-file))))
```
Then customize `flymake-allowed-php-file-name-masks` to use `my-flymake-php-init` function for initializing flymake-php instead of the original one. And so it works:
[](https://i.stack.imgur.com/X3jpG.png)
(source: [flickr.com](https://farm3.static.flickr.com/2736/4472983674_e07529f5ce_o.png)) | Decent IDE's will give you the names of the variables in the current scope when you are typing them via Intellisense.
This should severely cut down on the number of times you misspell a variable name. It also allows your variable names to be more descriptive than `$foo`
---
Furthermore, you should always pay attention to undefined variable warnings, as they immediately tell you when you have made a misspelling. |
44,382,000 | I have issue in Android Studio 2.3.2 when trying to use Kotlin 1.1.2-4 and Data Binding.
Here is my gradle files:
```
buildscript {
ext.kotlin_version = '1.1.2-4'
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
allprojects {
repositories {
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
```
---
```
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
android {
compileSdkVersion 25
buildToolsVersion "25.0.3"
defaultConfig {
applicationId "my.app.kotlin.databinding"
minSdkVersion 16
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
dataBinding {
enabled = true
}
}
dependencies {
// Data binding compiler for kotlin
kapt 'com.android.databinding:compiler:2.3.2'
//support libraries
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
// std lib for Kotlin
compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
testCompile 'junit:junit:4.12'
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
}
repositories {
mavenCentral()
}
```
When I try to compile the project it gives me this error:
```
* Exception is:
org.gradle.api.CircularReferenceException: Circular dependency between the following tasks:
:app:compileReleaseKotlin
\--- :app:kaptReleaseKotlin
\--- :app:compileReleaseKotlin (*)
(*) - details omitted (listed previously)
at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.onOrderingCycle(DefaultTaskExecutionPlan.java:445)
at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.determineExecutionPlan(DefaultTaskExecutionPlan.java:287)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.ensurePopulated(DefaultTaskGraphExecuter.java:202)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:109)
at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.java:23)
at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.java:43)
at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:30)
at org.gradle.initialization.DefaultGradleLauncher$3.execute(DefaultGradleLauncher.java:196)
at org.gradle.initialization.DefaultGradleLauncher$3.execute(DefaultGradleLauncher.java:193)
at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:56)
at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:193)
at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:119)
at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:102)
at org.gradle.launcher.exec.GradleBuildController.run(GradleBuildController.java:71)
at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:41)
at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:26)
at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:75)
at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:49)
at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:44)
at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:29)
at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:47)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
at org.gradle.util.Swapper.swap(Swapper.java:38)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:60)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:72)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:297)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:54)
at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40)
BUILD FAILED
```
If I switch back to version 1.1.2-3 everything works well and compiling without any issue.
What I missed? Why it doesn't work with version 1.1.2-4? | 2017/06/06 | [
"https://Stackoverflow.com/questions/44382000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3278271/"
] | Unfortunately this is a known bug,
<https://youtrack.jetbrains.com/issue/KT-18279>
<https://issuetracker.google.com/issues/62324689>
the work around, as you found out, is to downgrade to kotlin 1.1.2-3 | It is a bug, but you can download Android Studio 3.0 Canary 3 and update your Android Gradle Plugin to `3.0.0-alpha3` and it's fixed. |
44,382,000 | I have issue in Android Studio 2.3.2 when trying to use Kotlin 1.1.2-4 and Data Binding.
Here is my gradle files:
```
buildscript {
ext.kotlin_version = '1.1.2-4'
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
allprojects {
repositories {
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
```
---
```
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
android {
compileSdkVersion 25
buildToolsVersion "25.0.3"
defaultConfig {
applicationId "my.app.kotlin.databinding"
minSdkVersion 16
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
dataBinding {
enabled = true
}
}
dependencies {
// Data binding compiler for kotlin
kapt 'com.android.databinding:compiler:2.3.2'
//support libraries
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
// std lib for Kotlin
compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
testCompile 'junit:junit:4.12'
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
}
repositories {
mavenCentral()
}
```
When I try to compile the project it gives me this error:
```
* Exception is:
org.gradle.api.CircularReferenceException: Circular dependency between the following tasks:
:app:compileReleaseKotlin
\--- :app:kaptReleaseKotlin
\--- :app:compileReleaseKotlin (*)
(*) - details omitted (listed previously)
at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.onOrderingCycle(DefaultTaskExecutionPlan.java:445)
at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.determineExecutionPlan(DefaultTaskExecutionPlan.java:287)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.ensurePopulated(DefaultTaskGraphExecuter.java:202)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:109)
at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.java:23)
at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.java:43)
at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:30)
at org.gradle.initialization.DefaultGradleLauncher$3.execute(DefaultGradleLauncher.java:196)
at org.gradle.initialization.DefaultGradleLauncher$3.execute(DefaultGradleLauncher.java:193)
at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:56)
at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:193)
at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:119)
at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:102)
at org.gradle.launcher.exec.GradleBuildController.run(GradleBuildController.java:71)
at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:41)
at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:26)
at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:75)
at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:49)
at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:44)
at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:29)
at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:47)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
at org.gradle.util.Swapper.swap(Swapper.java:38)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:60)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:72)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:297)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:54)
at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40)
BUILD FAILED
```
If I switch back to version 1.1.2-3 everything works well and compiling without any issue.
What I missed? Why it doesn't work with version 1.1.2-4? | 2017/06/06 | [
"https://Stackoverflow.com/questions/44382000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3278271/"
] | Unfortunately this is a known bug,
<https://youtrack.jetbrains.com/issue/KT-18279>
<https://issuetracker.google.com/issues/62324689>
the work around, as you found out, is to downgrade to kotlin 1.1.2-3 | Finally fixed in version 1.1.2-5 Thanks to JetBrains! |
44,382,000 | I have issue in Android Studio 2.3.2 when trying to use Kotlin 1.1.2-4 and Data Binding.
Here is my gradle files:
```
buildscript {
ext.kotlin_version = '1.1.2-4'
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
allprojects {
repositories {
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
```
---
```
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
android {
compileSdkVersion 25
buildToolsVersion "25.0.3"
defaultConfig {
applicationId "my.app.kotlin.databinding"
minSdkVersion 16
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
dataBinding {
enabled = true
}
}
dependencies {
// Data binding compiler for kotlin
kapt 'com.android.databinding:compiler:2.3.2'
//support libraries
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
// std lib for Kotlin
compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
testCompile 'junit:junit:4.12'
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
}
repositories {
mavenCentral()
}
```
When I try to compile the project it gives me this error:
```
* Exception is:
org.gradle.api.CircularReferenceException: Circular dependency between the following tasks:
:app:compileReleaseKotlin
\--- :app:kaptReleaseKotlin
\--- :app:compileReleaseKotlin (*)
(*) - details omitted (listed previously)
at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.onOrderingCycle(DefaultTaskExecutionPlan.java:445)
at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.determineExecutionPlan(DefaultTaskExecutionPlan.java:287)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.ensurePopulated(DefaultTaskGraphExecuter.java:202)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:109)
at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.java:23)
at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.java:43)
at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:30)
at org.gradle.initialization.DefaultGradleLauncher$3.execute(DefaultGradleLauncher.java:196)
at org.gradle.initialization.DefaultGradleLauncher$3.execute(DefaultGradleLauncher.java:193)
at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:56)
at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:193)
at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:119)
at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:102)
at org.gradle.launcher.exec.GradleBuildController.run(GradleBuildController.java:71)
at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:41)
at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:26)
at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:75)
at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:49)
at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:44)
at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:29)
at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:47)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
at org.gradle.util.Swapper.swap(Swapper.java:38)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:60)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:72)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:297)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:54)
at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40)
BUILD FAILED
```
If I switch back to version 1.1.2-3 everything works well and compiling without any issue.
What I missed? Why it doesn't work with version 1.1.2-4? | 2017/06/06 | [
"https://Stackoverflow.com/questions/44382000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3278271/"
] | Finally fixed in version 1.1.2-5 Thanks to JetBrains! | It is a bug, but you can download Android Studio 3.0 Canary 3 and update your Android Gradle Plugin to `3.0.0-alpha3` and it's fixed. |
77,287 | My sudo file has two commands in it right now that are allowed to run without logging in as root.
It looks like this:
```
user ALL=(root) NOPASSWD: /home/user/prog1.py
user ALL=(root) NOPASSWD: /home/user/prog2.py
```
The `prog1.py` file runs fine without password needed. The `prog2.py` file fails on permissions denied?
The first program is only accessing a file to read that is root protected. The second program is creating a symlink and removing a root-protected file:
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from random import choice
from subprocess import Popen
def back_drop_change():
link = "/usr/share/slim/themes/default/background.jpg"
os.remove(link) # this is the line that returns permission denied
image_selection = list()
for di, _, fi in os.walk("/home/user/pictures/apod"):
for f in fi:
image_selection.append(di + "/" + f)
bck_img = choice(image_selection)
Popen(["ln", "-s", bck_img, link])
if __name__ == "__main__":
back_drop_change()
```
I try adding `/usr/bin/rm /usr/share/slim/themes/default/background.jpg` to the visudo file but, it still fails?
EDIT:
Some extra information --
`sudo -l` returns:
```
Matching Defaults entries for user on this host:
env_reset, editor="/usr/bin/vim -p -X", !env_editor
User user may run the following commands on this host:
(ALL) ALL
(root) NOPASSWD: /home/user/Pidtrk/main.py
(root) NOPASSWD: /home/user/backdrop.py
```
and again, I am able to run `python2 Pidtrk/main.py` without errors but, not
`python2 backdrop.py`.
And both these files are owned by the same `User` and have the same `Permissions`.
EDIT 2:
I have both of `prog1.py` and `prog2.py` running in a `crontab` on `@reboot`.
If I have this line in `crontab`:
```
`python2 /home/user/prog1.py >> err.log 2>&1`
```
without:
```
user ALL=(root) NOPASSWD: /home/user/prog1.py
```
Inside my sudoers file, the err.log shows `it failed with permissions denied`.
Now when I add in this line to sudoers:
```
user ALL=(root) NOPASSWD: /home/user/prog1.py
```
The `prog1.py` runs fine on reboot, why is this any different for the `prog2.py` file? | 2013/05/27 | [
"https://unix.stackexchange.com/questions/77287",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/28470/"
] | As indicated in a clarifying comment, you are attempting to run `python2 /home/user/backdrop.py`. But you have granted yourself permission to run a different command -- viz. `/home/user/backdrop.py` without the `python2` -- which you are not allowed to do. `sudo` is very particular about what it allows; either run exactly the command you have the permissions for, or change `sudoers` to allow exactly the command you actually want to run. | If you are sure that
1. the error is caused within the script
2. the sudo call is correct
then the problem is most probably not sudo. There are several cases in which root is not allowed to remove a file:
1. The file is on a volume which is mounted read-only (see `cat /proc/mounts`).
2. The file is protected by file system attributes (see `lsattr "$path"`).
3. The parent directory is protected by file system attributes.
4. Fancy intervening kernel stuff (SELinux, Apparmor).
It may also be helpful to add a few seconds of waiting time in the script and attach with strace to it (as root): `strace -f -p $PID` |
12,352,048 | How can I create a view that merges different columns with a different table? I have three tables for example: users, items and gifts (in this example it's a system that a user can give a gift to another user)
`users` table has information about users, `items` table has information about items and `gifts` table shows which user sent what gift to which user.
What I want is to create a view like following:
```
user_from | user_to | gift_name | gift_price
sally | john | Teddy Bear | 10
``` | 2012/09/10 | [
"https://Stackoverflow.com/questions/12352048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1168524/"
] | You must join the three tables first. Example
```
CREATE VIEW GiftsList
AS
SELECT b.name user_from,
c.name user_to,
d.name gift_name,
d.price gift_price
FROM gift a
INNER JOIN users b
ON a.user_from = b.id
INNER JOIN users c
ON a.user_from = c.id
INNER JOIN items d
ON a.item = d.id
``` | You can create a view with two tables like:
```
CREATE VIEW giftList AS
SELECT users.user_from,users.user_to,gifts.gift_name,gifts.gift_price FROM users,gifts
WHERE users.user_id = gifts.user_id;
```
The where clause is to make sure the output does not repeat. |
12,352,048 | How can I create a view that merges different columns with a different table? I have three tables for example: users, items and gifts (in this example it's a system that a user can give a gift to another user)
`users` table has information about users, `items` table has information about items and `gifts` table shows which user sent what gift to which user.
What I want is to create a view like following:
```
user_from | user_to | gift_name | gift_price
sally | john | Teddy Bear | 10
``` | 2012/09/10 | [
"https://Stackoverflow.com/questions/12352048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1168524/"
] | You must join the three tables first. Example
```
CREATE VIEW GiftsList
AS
SELECT b.name user_from,
c.name user_to,
d.name gift_name,
d.price gift_price
FROM gift a
INNER JOIN users b
ON a.user_from = b.id
INNER JOIN users c
ON a.user_from = c.id
INNER JOIN items d
ON a.item = d.id
``` | I believe were looking for [data blending](https://support.google.com/datastudio/answer/9061420?hl=en). So basically having google data studio do a JOIN statement on ids from 2 data sets |
12,352,048 | How can I create a view that merges different columns with a different table? I have three tables for example: users, items and gifts (in this example it's a system that a user can give a gift to another user)
`users` table has information about users, `items` table has information about items and `gifts` table shows which user sent what gift to which user.
What I want is to create a view like following:
```
user_from | user_to | gift_name | gift_price
sally | john | Teddy Bear | 10
``` | 2012/09/10 | [
"https://Stackoverflow.com/questions/12352048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1168524/"
] | You can create a view with two tables like:
```
CREATE VIEW giftList AS
SELECT users.user_from,users.user_to,gifts.gift_name,gifts.gift_price FROM users,gifts
WHERE users.user_id = gifts.user_id;
```
The where clause is to make sure the output does not repeat. | I believe were looking for [data blending](https://support.google.com/datastudio/answer/9061420?hl=en). So basically having google data studio do a JOIN statement on ids from 2 data sets |
2,823,880 | >
> I have a question regarding this specific 2-dimensional DE: $$\dot r=-r\log r\\\dot\varphi=2r\sin^2\left(\frac{\varphi}{2}\right)$$ where $r> 0$ and $\varphi\in [0,\infty)$ (yes, $2\pi$ would do it as well).
>
>
>
Now, I want to see how the stationary point $(1,0)$ is attractive. It is easy to see that $\dot\varphi>0$ at all times $t$ so all solutions constantly rotate until hitting a stationary point.
For starting values left of $(1,0)$ (so $r<1$) we also see that $\dot r>0$ and for starting values right of $(1,0)$ we have $\dot r<0$. So let's say we start at some point in the first quadrant left-above of $(1,0)$ (for example $\frac{1}{2}(1,1)$). Then the solution moves into the direction of the unit circle while also doing a spiral since $\dot\varphi >0$. But how does this work? How can $\varphi$ and $r$ both increase at all times when I start left-above the stationary point $(1,0)$? How does it ever hit $(1,0)$ without decreasing again?
I hope, I could make my problem clear enough. If not, I can provide a sketch of what I mean. Maybe also my question can be answered if someone provides a sketch of the trajectory starting at the mentioned point $(\frac{1}{2},\frac{1}{2})$. | 2018/06/18 | [
"https://math.stackexchange.com/questions/2823880",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/465097/"
] | According to [wikipedia](https://en.wikipedia.org/wiki/Arithmetic_progression):
>
> In mathematics, an arithmetic progression (AP) or arithmetic sequence is a sequence of numbers such that the difference between the consecutive terms is constant. For instance, the sequence 5, 7, 9, 11, 13, 15, . . . is an arithmetic progression with common difference of 2.
>
>
>
So an argument could be made that, technically, a null sequence (no numbers at all), as well as a single number or two numbers, would be a arithmetic progression, but they would be trivial examples that don't exhibit what people typically think of as an "arithmetic progression". There are probably cases where a definition is used that excludes these types, but this would not be a consistent situation. | Any two numbers are technically in an trivial AP because there is only one difference of numbers to consider. However, when there are three or more numbers, there are two or more differences that need to be held constant. This means that some actual pattern is being upheld. |
19,732,194 | I need to download a datastore from my appengine application. The application itself is written in JAVA and I've already activated remote API according to [this instruction](https://developers.google.com/appengine/docs/java/tools/remoteapi?hl=pl&csw=1). Then I run `appcfg.py` and it asks me for log in details and I get the following result:
```
06:18 PM Downloading data records.
[INFO ] Logging to bulkloader-log-20131101.181851
[INFO ] Throttling transfers:
[INFO ] Bandwidth: 250000 bytes/second
[INFO ] HTTP connections: 8/second
[INFO ] Entities inserted/fetched/modified: 20/second
[INFO ] Batch Size: 10
Please enter login credentials for [_app_address_]
Email: [_My_Google_Mail_]
Password for [_My_Google_Mail_]:
Error 302: --- begin server output ---
--- end server output ---
```
Obviously I've hidden app and my mail but they are correct (I use the same credentials when use appcfg.sh to deploy new version).
If it helps the app configuration is:
Authentication Type: (Experimental) Federated Login
Datastore Replication Options: High Replication
What can I do about it?? I really need to get local copy of the production data... | 2013/11/01 | [
"https://Stackoverflow.com/questions/19732194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/401499/"
] | Alfresco has [REST API](http://wiki.alfresco.com/wiki/Repository_RESTful_API_Reference), so you can use it in your Spring + Vaadin application. Spring has [RestTemplate](http://spring.io/blog/2009/03/27/rest-in-spring-3-resttemplate/) based on Jackson who will help you with REST client implementation. | There are several ways to integrate with alfresco. My two favorite ways to integrate with Alfresco are:
1. Using the CMIS api
<http://wiki.alfresco.com/wiki/CMIS>
2. Using your own custom webscripts or java back end webscripts. These allow you to quickly develop your own rest api with alfresco.
<http://docs.alfresco.com/4.0/index.jsp?topic=%2Fcom.alfresco.enterprise.doc%2Fconcepts%2Fws-architecture.html>
There are many different ways to integrate. They have webdav, cifs, ftp, and several other ways to integrate. Here is some documentation from alfresco about it
<http://docs.alfresco.com/4.2/index.jsp?topic=%2Fcom.alfresco.enterprise.doc%2Fconcepts%2Fintegration-options.html> |
11,462,980 | In JFrame i want to draw a canvas on a canvas and on requirement basis i want to keep either canvas1 set visible or canvas2 set visible. Can i do that? | 2012/07/13 | [
"https://Stackoverflow.com/questions/11462980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1519904/"
] | Don't mix Swing (JFrame) with AWT (Canvas) components unless you have a compelling reason to do so, otherwise you're just asking for unusual hard to debug trouble. Instead draw on a JPanel in its paintComponent method as has been described on this site many times, and swap JPanels via [CardLayout](http://docs.oracle.com/javase/tutorial/uiswing/layout/card.html). Also, it's "Java Swing", not "java swings". | Since Canvas is just a subclass of Component (and sometimes of JPanel), then you can simply create two canvas boxes with absolute positioning where one is larger and behind the other. The you can use the .setVisibile(Boolean) to show/hind any one of the two.
see this link for java absolute layout
<http://docs.oracle.com/javase/tutorial/uiswing/layout/none.html> |
11,462,980 | In JFrame i want to draw a canvas on a canvas and on requirement basis i want to keep either canvas1 set visible or canvas2 set visible. Can i do that? | 2012/07/13 | [
"https://Stackoverflow.com/questions/11462980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1519904/"
] | [`OverlayLayout`](http://docs.oracle.com/javase/7/docs/api/javax/swing/OverlayLayout.html), shown [here](http://www.java2s.com/Tutorial/Java/0240__Swing/1401__OverlayLayout.htm), may meet your needs. | Since Canvas is just a subclass of Component (and sometimes of JPanel), then you can simply create two canvas boxes with absolute positioning where one is larger and behind the other. The you can use the .setVisibile(Boolean) to show/hind any one of the two.
see this link for java absolute layout
<http://docs.oracle.com/javase/tutorial/uiswing/layout/none.html> |
50,809 | J'ai précédemment lu Man's Search for Meaning de Viktor E. Frankl et cette question m'est restée en tête assez longtemps avant que je la pose.
Comment traduiriez-vous en français : "He who has a why to live can bear almost any how"
Ma tentative est : « Celui qui a une raison de vivre peut presque tout endurer ». Qu'en pensez-vous ? | 2022/07/16 | [
"https://french.stackexchange.com/questions/50809",
"https://french.stackexchange.com",
"https://french.stackexchange.com/users/17415/"
] | La traduction rend très bien le sens mais on perd l'effet de style mettant en parallèle *why* et *how*.
Voici ce que je peux proposer :
>
> **Qu'importe le comment à qui sait le pourquoi de sa vie.**
>
>
> | J'aime bien sous forme d'adage comme on a formulé dans une [autre réponse](https://french.stackexchange.com/a/50810). En complément, ça semble provenir de Nietzsche dans le *Crépuscule des idoles*, 1888 ([texte](https://books.google.com/books?id=LhLlcQ-6dIEC&newbks=1&newbks_redir=0&dq=%E2%80%9CGo%CC%88tzen-Da%CC%88mmerung%3B%20oder%2C%20Wie%20man%20mit%20dem%20Hammer%20philosophirt%E2%80%9D&pg=PP1#v=onepage&q=%22Hat%20man%20sein%20warum%22&f=false) ; [trad. anglaises](https://quoteinvestigator.com/2019/10/09/why-how/) ; « — Hat man sein warum? des Lebens, so verträgt man sich fast mit jedem wie? »). Dans une [traduction](https://books.google.com/books?id=9BX9DwAAQBAJ&newbks=1&newbks_redir=0&lpg=PA8&dq=Cr%C3%A9puscule%20des%20idoles%2C%20%22son%20pourquoi%22&pg=PA8#v=onepage&q=Cr%C3%A9puscule%20des%20idoles,%20%22son%20pourquoi%22&f=false) en français on trouve :
>
> Si l'on possède son pourquoi ? de la vie, on s'accommode de presque
> tous les comment ?
>
>
>
Ça semble très littéral mais on le trouve ainsi dans plusieurs éditions... |
50,809 | J'ai précédemment lu Man's Search for Meaning de Viktor E. Frankl et cette question m'est restée en tête assez longtemps avant que je la pose.
Comment traduiriez-vous en français : "He who has a why to live can bear almost any how"
Ma tentative est : « Celui qui a une raison de vivre peut presque tout endurer ». Qu'en pensez-vous ? | 2022/07/16 | [
"https://french.stackexchange.com/questions/50809",
"https://french.stackexchange.com",
"https://french.stackexchange.com/users/17415/"
] | La traduction rend très bien le sens mais on perd l'effet de style mettant en parallèle *why* et *how*.
Voici ce que je peux proposer :
>
> **Qu'importe le comment à qui sait le pourquoi de sa vie.**
>
>
> | C'est une tentative qui serait selon mon point de vue presque le dernier mot sur la question de la traduction de cet adage ; je ne conteste qu'un terme, « endurer ». Il me semble que « how » ne soulève pas particulièrement la question de ce qui est douloureux ou pénible dans la vie, mais au lieu de cela ce qui représente un challenge ( \tʃa.lɛndʒ\ ou \ʃa.lɑ̃ʒ, [Wiktionnaire](https://fr.wiktionary.org/wiki/challenge)) ou un défi, pour employer le meilleur mot français qui approche ce terme en tant qu'équivalent. C'est pour cette raison que je crois le verbe « surmonter » plus exact que le verbe « endurer ».
* Celui qui a une raison de vivre peut presque tout surmonter.
Si on recherche plutôt une traduction près du langage d'origine la forme suivante me semble plus appropriée.
* Qui sait pour quoi il vit n'est pas arrêté par les comment. |
50,809 | J'ai précédemment lu Man's Search for Meaning de Viktor E. Frankl et cette question m'est restée en tête assez longtemps avant que je la pose.
Comment traduiriez-vous en français : "He who has a why to live can bear almost any how"
Ma tentative est : « Celui qui a une raison de vivre peut presque tout endurer ». Qu'en pensez-vous ? | 2022/07/16 | [
"https://french.stackexchange.com/questions/50809",
"https://french.stackexchange.com",
"https://french.stackexchange.com/users/17415/"
] | La traduction rend très bien le sens mais on perd l'effet de style mettant en parallèle *why* et *how*.
Voici ce que je peux proposer :
>
> **Qu'importe le comment à qui sait le pourquoi de sa vie.**
>
>
> | Celui qui a un « pourquoi » dans la vie, trouve toujours un « comment ». |
50,809 | J'ai précédemment lu Man's Search for Meaning de Viktor E. Frankl et cette question m'est restée en tête assez longtemps avant que je la pose.
Comment traduiriez-vous en français : "He who has a why to live can bear almost any how"
Ma tentative est : « Celui qui a une raison de vivre peut presque tout endurer ». Qu'en pensez-vous ? | 2022/07/16 | [
"https://french.stackexchange.com/questions/50809",
"https://french.stackexchange.com",
"https://french.stackexchange.com/users/17415/"
] | La traduction rend très bien le sens mais on perd l'effet de style mettant en parallèle *why* et *how*.
Voici ce que je peux proposer :
>
> **Qu'importe le comment à qui sait le pourquoi de sa vie.**
>
>
> | He who has a why to live can bear almost any how.
Avec un but, on vit, par tous les moyens. |
50,809 | J'ai précédemment lu Man's Search for Meaning de Viktor E. Frankl et cette question m'est restée en tête assez longtemps avant que je la pose.
Comment traduiriez-vous en français : "He who has a why to live can bear almost any how"
Ma tentative est : « Celui qui a une raison de vivre peut presque tout endurer ». Qu'en pensez-vous ? | 2022/07/16 | [
"https://french.stackexchange.com/questions/50809",
"https://french.stackexchange.com",
"https://french.stackexchange.com/users/17415/"
] | J'aime bien sous forme d'adage comme on a formulé dans une [autre réponse](https://french.stackexchange.com/a/50810). En complément, ça semble provenir de Nietzsche dans le *Crépuscule des idoles*, 1888 ([texte](https://books.google.com/books?id=LhLlcQ-6dIEC&newbks=1&newbks_redir=0&dq=%E2%80%9CGo%CC%88tzen-Da%CC%88mmerung%3B%20oder%2C%20Wie%20man%20mit%20dem%20Hammer%20philosophirt%E2%80%9D&pg=PP1#v=onepage&q=%22Hat%20man%20sein%20warum%22&f=false) ; [trad. anglaises](https://quoteinvestigator.com/2019/10/09/why-how/) ; « — Hat man sein warum? des Lebens, so verträgt man sich fast mit jedem wie? »). Dans une [traduction](https://books.google.com/books?id=9BX9DwAAQBAJ&newbks=1&newbks_redir=0&lpg=PA8&dq=Cr%C3%A9puscule%20des%20idoles%2C%20%22son%20pourquoi%22&pg=PA8#v=onepage&q=Cr%C3%A9puscule%20des%20idoles,%20%22son%20pourquoi%22&f=false) en français on trouve :
>
> Si l'on possède son pourquoi ? de la vie, on s'accommode de presque
> tous les comment ?
>
>
>
Ça semble très littéral mais on le trouve ainsi dans plusieurs éditions... | C'est une tentative qui serait selon mon point de vue presque le dernier mot sur la question de la traduction de cet adage ; je ne conteste qu'un terme, « endurer ». Il me semble que « how » ne soulève pas particulièrement la question de ce qui est douloureux ou pénible dans la vie, mais au lieu de cela ce qui représente un challenge ( \tʃa.lɛndʒ\ ou \ʃa.lɑ̃ʒ, [Wiktionnaire](https://fr.wiktionary.org/wiki/challenge)) ou un défi, pour employer le meilleur mot français qui approche ce terme en tant qu'équivalent. C'est pour cette raison que je crois le verbe « surmonter » plus exact que le verbe « endurer ».
* Celui qui a une raison de vivre peut presque tout surmonter.
Si on recherche plutôt une traduction près du langage d'origine la forme suivante me semble plus appropriée.
* Qui sait pour quoi il vit n'est pas arrêté par les comment. |
50,809 | J'ai précédemment lu Man's Search for Meaning de Viktor E. Frankl et cette question m'est restée en tête assez longtemps avant que je la pose.
Comment traduiriez-vous en français : "He who has a why to live can bear almost any how"
Ma tentative est : « Celui qui a une raison de vivre peut presque tout endurer ». Qu'en pensez-vous ? | 2022/07/16 | [
"https://french.stackexchange.com/questions/50809",
"https://french.stackexchange.com",
"https://french.stackexchange.com/users/17415/"
] | J'aime bien sous forme d'adage comme on a formulé dans une [autre réponse](https://french.stackexchange.com/a/50810). En complément, ça semble provenir de Nietzsche dans le *Crépuscule des idoles*, 1888 ([texte](https://books.google.com/books?id=LhLlcQ-6dIEC&newbks=1&newbks_redir=0&dq=%E2%80%9CGo%CC%88tzen-Da%CC%88mmerung%3B%20oder%2C%20Wie%20man%20mit%20dem%20Hammer%20philosophirt%E2%80%9D&pg=PP1#v=onepage&q=%22Hat%20man%20sein%20warum%22&f=false) ; [trad. anglaises](https://quoteinvestigator.com/2019/10/09/why-how/) ; « — Hat man sein warum? des Lebens, so verträgt man sich fast mit jedem wie? »). Dans une [traduction](https://books.google.com/books?id=9BX9DwAAQBAJ&newbks=1&newbks_redir=0&lpg=PA8&dq=Cr%C3%A9puscule%20des%20idoles%2C%20%22son%20pourquoi%22&pg=PA8#v=onepage&q=Cr%C3%A9puscule%20des%20idoles,%20%22son%20pourquoi%22&f=false) en français on trouve :
>
> Si l'on possède son pourquoi ? de la vie, on s'accommode de presque
> tous les comment ?
>
>
>
Ça semble très littéral mais on le trouve ainsi dans plusieurs éditions... | Celui qui a un « pourquoi » dans la vie, trouve toujours un « comment ». |
50,809 | J'ai précédemment lu Man's Search for Meaning de Viktor E. Frankl et cette question m'est restée en tête assez longtemps avant que je la pose.
Comment traduiriez-vous en français : "He who has a why to live can bear almost any how"
Ma tentative est : « Celui qui a une raison de vivre peut presque tout endurer ». Qu'en pensez-vous ? | 2022/07/16 | [
"https://french.stackexchange.com/questions/50809",
"https://french.stackexchange.com",
"https://french.stackexchange.com/users/17415/"
] | J'aime bien sous forme d'adage comme on a formulé dans une [autre réponse](https://french.stackexchange.com/a/50810). En complément, ça semble provenir de Nietzsche dans le *Crépuscule des idoles*, 1888 ([texte](https://books.google.com/books?id=LhLlcQ-6dIEC&newbks=1&newbks_redir=0&dq=%E2%80%9CGo%CC%88tzen-Da%CC%88mmerung%3B%20oder%2C%20Wie%20man%20mit%20dem%20Hammer%20philosophirt%E2%80%9D&pg=PP1#v=onepage&q=%22Hat%20man%20sein%20warum%22&f=false) ; [trad. anglaises](https://quoteinvestigator.com/2019/10/09/why-how/) ; « — Hat man sein warum? des Lebens, so verträgt man sich fast mit jedem wie? »). Dans une [traduction](https://books.google.com/books?id=9BX9DwAAQBAJ&newbks=1&newbks_redir=0&lpg=PA8&dq=Cr%C3%A9puscule%20des%20idoles%2C%20%22son%20pourquoi%22&pg=PA8#v=onepage&q=Cr%C3%A9puscule%20des%20idoles,%20%22son%20pourquoi%22&f=false) en français on trouve :
>
> Si l'on possède son pourquoi ? de la vie, on s'accommode de presque
> tous les comment ?
>
>
>
Ça semble très littéral mais on le trouve ainsi dans plusieurs éditions... | He who has a why to live can bear almost any how.
Avec un but, on vit, par tous les moyens. |
50,809 | J'ai précédemment lu Man's Search for Meaning de Viktor E. Frankl et cette question m'est restée en tête assez longtemps avant que je la pose.
Comment traduiriez-vous en français : "He who has a why to live can bear almost any how"
Ma tentative est : « Celui qui a une raison de vivre peut presque tout endurer ». Qu'en pensez-vous ? | 2022/07/16 | [
"https://french.stackexchange.com/questions/50809",
"https://french.stackexchange.com",
"https://french.stackexchange.com/users/17415/"
] | He who has a why to live can bear almost any how.
Avec un but, on vit, par tous les moyens. | C'est une tentative qui serait selon mon point de vue presque le dernier mot sur la question de la traduction de cet adage ; je ne conteste qu'un terme, « endurer ». Il me semble que « how » ne soulève pas particulièrement la question de ce qui est douloureux ou pénible dans la vie, mais au lieu de cela ce qui représente un challenge ( \tʃa.lɛndʒ\ ou \ʃa.lɑ̃ʒ, [Wiktionnaire](https://fr.wiktionary.org/wiki/challenge)) ou un défi, pour employer le meilleur mot français qui approche ce terme en tant qu'équivalent. C'est pour cette raison que je crois le verbe « surmonter » plus exact que le verbe « endurer ».
* Celui qui a une raison de vivre peut presque tout surmonter.
Si on recherche plutôt une traduction près du langage d'origine la forme suivante me semble plus appropriée.
* Qui sait pour quoi il vit n'est pas arrêté par les comment. |
50,809 | J'ai précédemment lu Man's Search for Meaning de Viktor E. Frankl et cette question m'est restée en tête assez longtemps avant que je la pose.
Comment traduiriez-vous en français : "He who has a why to live can bear almost any how"
Ma tentative est : « Celui qui a une raison de vivre peut presque tout endurer ». Qu'en pensez-vous ? | 2022/07/16 | [
"https://french.stackexchange.com/questions/50809",
"https://french.stackexchange.com",
"https://french.stackexchange.com/users/17415/"
] | He who has a why to live can bear almost any how.
Avec un but, on vit, par tous les moyens. | Celui qui a un « pourquoi » dans la vie, trouve toujours un « comment ». |
20,649,532 | So, I'm localizing an app from japanese to english.
In japanese, there is no distinction between (say) "Mr." and "Ms."(/"Mrs."), so I need to do something like this:
```
/* Salutation format for user (male) */
"%@様" = "Mr. %@";
/* Salutation format for user (female) */
"%@様" = "Ms. %@";
```
As you can see, the Japanese localization uses the same string in both cases. I was under the impression that, when the strings file contains more than one entry with the same 'source' (i.e., left side) string, the 'comment' was used to determine which one was employed. **It turns out I was wrong, and the comment parameter is just an aid for human translators, totally ignored by `NSLocalizedString()`**.
So if I run the app, both of the code paths below produce the same string, regardless of the user's gender:
```
NSString* userName;
BOOL userIsMale;
/* userName and userIsMale are set... */
NSString* format;
if(userIsMale){
// MALE
format = NSLocalizedString(@"%@様",
@"Salutation format for user (male)");
}
else{
// FEMALE
format = NSLocalizedString(@"%@様",
@"Salutation format for user (female)");
}
NSString* salutation = [NSString stringWithFormat:format, userName];
```
So, how should I deal with a case like this? | 2013/12/18 | [
"https://Stackoverflow.com/questions/20649532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/433373/"
] | Well, actually “left side” of the `NSLocalizedString` is a key. So you could do something like:
```
NSLocalizedString(@"SalutForUserMale", @"Salutation format for user (male)");
NSLocalizedString(@"SalutForUserFemale", @"Salutation format for user (female)");
```
Then in your base `*.strings` file (Japanese I presume) you would have:
```
"SalutForUserMale" = "%@様";
"SalutForUserFemale" = "%@様";
```
And in your English `*.strings` file you would have:
```
"SalutForUserMale" = "Mr. %@";
"SalutForUserFemale" = "Ms. %@";
``` | The Localizable.strings files are nothing more than key value lists. You are using the Japanese phrases as keys which is unusual but I guess it works. I assume this is because the original app was developed in Japanese(?). I usually use English phrases keys, but whatever.
The point is that **if you want two different phrases in even just one translation you have to have two different keys in all your translations**. If there is something in your base language that is not distinguished but in the translations it is, then you can just "split" an existing key in two new ones. Just change it slightly or add a number, see below:
```
/* english .strings file */
"hello_world_key" = "Hello World";
"Yes1" = "Yes"; // same in english but different values in german
"Yes2" = "Yes";
/* german .strings file */
"hello_world_key" = "Hallo Welt";
"Yes1" = "Ja";
"Yes2" = "Jawohl";
``` |
13,555,856 | For an assignment of a course called High Performance Computing, I required to optimize the following code fragment:
```
int foobar(int a, int b, int N)
{
int i, j, k, x, y;
x = 0;
y = 0;
k = 256;
for (i = 0; i <= N; i++) {
for (j = i + 1; j <= N; j++) {
x = x + 4*(2*i+j)*(i+2*k);
if (i > j){
y = y + 8*(i-j);
}else{
y = y + 8*(j-i);
}
}
}
return x;
}
```
Using some recommendations, I managed to optimize the code (or at least I think so), such as:
1. Constant Propagation
2. Algebraic Simplification
3. Copy Propagation
4. Common Subexpression Elimination
5. Dead Code Elimination
6. Loop Invariant Removal
7. bitwise shifts instead of multiplication as they are less expensive.
Here's my code:
```
int foobar(int a, int b, int N) {
int i, j, x, y, t;
x = 0;
y = 0;
for (i = 0; i <= N; i++) {
t = i + 512;
for (j = i + 1; j <= N; j++) {
x = x + ((i<<3) + (j<<2))*t;
}
}
return x;
}
```
According to my instructor, a well optimized code instructions should have fewer or less costly instructions in assembly language level.And therefore must be run, the instructions in less time than the original code, ie calculations are made with::
>
> execution time = instruction count \* cycles per instruction
>
>
>
When I generate assembly code using the command: `gcc -o code_opt.s -S foobar.c`,
the generated code has many more lines than the original despite having made some optimizations, and run-time is lower, but not as much as in the original code. What am I doing wrong?
Do not paste the assembly code as both are very extensive. So I'm calling the function "foobar" in the main and I am measuring the execution time using the time command in linux
```
int main () {
int a,b,N;
scanf ("%d %d %d",&a,&b,&N);
printf ("%d\n",foobar (a,b,N));
return 0;
}
``` | 2012/11/25 | [
"https://Stackoverflow.com/questions/13555856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/59468/"
] | `y` does not affect the final result of the code - removed:
```
int foobar(int a, int b, int N)
{
int i, j, k, x, y;
x = 0;
//y = 0;
k = 256;
for (i = 0; i <= N; i++) {
for (j = i + 1; j <= N; j++) {
x = x + 4*(2*i+j)*(i+2*k);
//if (i > j){
// y = y + 8*(i-j);
//}else{
// y = y + 8*(j-i);
//}
}
}
return x;
}
```
`k` is simply a constant:
```
int foobar(int a, int b, int N)
{
int i, j, x;
x = 0;
for (i = 0; i <= N; i++) {
for (j = i + 1; j <= N; j++) {
x = x + 4*(2*i+j)*(i+2*256);
}
}
return x;
}
```
The inner expression can be transformed to: `x += 8*i*i + 4096*i + 4*i*j + 2048*j`. Use math to push all of them to the outer loop: `x += 8*i*i*(N-i) + 4096*i*(N-i) + 2*i*(N-i)*(N+i+1) + 1024*(N-i)*(N+i+1)`.
You can expand the above expression, and apply [sum of squares and sum of cubes formula](http://library.thinkquest.org/20991/gather/formula/data/209.html) to obtain a close form expression, which should run faster than the doubly nested loop. I leave it as an exercise to you. As a result, `i` and `j` will also be removed.
`a` and `b` should also be removed if possible - since `a` and `b` are supplied as argument but never used in your code.
Sum of squares and sum of cubes formula:
* Sum(x2, x = 1..n) = n(n + 1)(2n + 1)/6
* Sum(x3, x = 1..n) = n2(n + 1)2/4 | int foobar(int N) //To avoid unuse passing argument
{
```
int i, j, x=0; //Remove unuseful variable, operation so save stack and Machine cycle
for (i = N; i--; ) //Don't check unnecessary comparison condition
for (j = N+1; --j>i; )
x += (((i<<1)+j)*(i+512)<<2); //Save Machine cycle ,Use shift instead of Multiply
return x;
```
} |
13,555,856 | For an assignment of a course called High Performance Computing, I required to optimize the following code fragment:
```
int foobar(int a, int b, int N)
{
int i, j, k, x, y;
x = 0;
y = 0;
k = 256;
for (i = 0; i <= N; i++) {
for (j = i + 1; j <= N; j++) {
x = x + 4*(2*i+j)*(i+2*k);
if (i > j){
y = y + 8*(i-j);
}else{
y = y + 8*(j-i);
}
}
}
return x;
}
```
Using some recommendations, I managed to optimize the code (or at least I think so), such as:
1. Constant Propagation
2. Algebraic Simplification
3. Copy Propagation
4. Common Subexpression Elimination
5. Dead Code Elimination
6. Loop Invariant Removal
7. bitwise shifts instead of multiplication as they are less expensive.
Here's my code:
```
int foobar(int a, int b, int N) {
int i, j, x, y, t;
x = 0;
y = 0;
for (i = 0; i <= N; i++) {
t = i + 512;
for (j = i + 1; j <= N; j++) {
x = x + ((i<<3) + (j<<2))*t;
}
}
return x;
}
```
According to my instructor, a well optimized code instructions should have fewer or less costly instructions in assembly language level.And therefore must be run, the instructions in less time than the original code, ie calculations are made with::
>
> execution time = instruction count \* cycles per instruction
>
>
>
When I generate assembly code using the command: `gcc -o code_opt.s -S foobar.c`,
the generated code has many more lines than the original despite having made some optimizations, and run-time is lower, but not as much as in the original code. What am I doing wrong?
Do not paste the assembly code as both are very extensive. So I'm calling the function "foobar" in the main and I am measuring the execution time using the time command in linux
```
int main () {
int a,b,N;
scanf ("%d %d %d",&a,&b,&N);
printf ("%d\n",foobar (a,b,N));
return 0;
}
``` | 2012/11/25 | [
"https://Stackoverflow.com/questions/13555856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/59468/"
] | Initially:
```
for (i = 0; i <= N; i++) {
for (j = i + 1; j <= N; j++) {
x = x + 4*(2*i+j)*(i+2*k);
if (i > j){
y = y + 8*(i-j);
}else{
y = y + 8*(j-i);
}
}
}
```
Removing `y` calculations:
```
for (i = 0; i <= N; i++) {
for (j = i + 1; j <= N; j++) {
x = x + 4*(2*i+j)*(i+2*k);
}
}
```
Splitting `i`, `j`, `k`:
```
for (i = 0; i <= N; i++) {
for (j = i + 1; j <= N; j++) {
x = x + 8*i*i + 16*i*k ; // multiple of 1 (no j)
x = x + (4*i + 8*k)*j ; // multiple of j
}
}
```
Moving them externally (and removing the loop that runs `N-i` times):
```
for (i = 0; i <= N; i++) {
x = x + (8*i*i + 16*i*k) * (N-i) ;
x = x + (4*i + 8*k) * ((N*N+N)/2 - (i*i+i)/2) ;
}
```
Rewritting:
```
for (i = 0; i <= N; i++) {
x = x + ( 8*k*(N*N+N)/2 ) ;
x = x + i * ( 16*k*N + 4*(N*N+N)/2 + 8*k*(-1/2) ) ;
x = x + i*i * ( 8*N + 16*k*(-1) + 4*(-1/2) + 8*k*(-1/2) );
x = x + i*i*i * ( 8*(-1) + 4*(-1/2) ) ;
}
```
Rewritting - recalculating:
```
for (i = 0; i <= N; i++) {
x = x + 4*k*(N*N+N) ; // multiple of 1
x = x + i * ( 16*k*N + 2*(N*N+N) - 4*k ) ; // multiple of i
x = x + i*i * ( 8*N - 20*k - 2 ) ; // multiple of i^2
x = x + i*i*i * ( -10 ) ; // multiple of i^3
}
```
Another move to external (and removal of the i loop):
```
x = x + ( 4*k*(N*N+N) ) * (N+1) ;
x = x + ( 16*k*N + 2*(N*N+N) - 4*k ) * ((N*(N+1))/2) ;
x = x + ( 8*N - 20*k - 2 ) * ((N*(N+1)*(2*N+1))/6);
x = x + (-10) * ((N*N*(N+1)*(N+1))/4) ;
```
Both the above loop removals use the **[summation](http://en.wikipedia.org/wiki/Summation)** formulas:
>
> Sum(1, i = 0..n) = n+1
>
> Sum(i1, i = 0..n) = n(n + 1)/2
>
> Sum(i2, i = 0..n) = n(n + 1)(2n + 1)/6
>
> Sum(i3, i = 0..n) = n2(n + 1)2/4
>
>
> | This function is equivalent with the following formula, which contains only **4 integer multiplications**, and **1 integer division**:
```
x = N * (N + 1) * (N * (7 * N + 8187) - 2050) / 6;
```
To get this, I simply typed the sum calculated by your nested loops into [Wolfram Alpha](http://www.wolframalpha.com):
```
sum (sum (8*i*i+4096*i+4*i*j+2048*j), j=i+1..N), i=0..N
```
[Here](http://www.wolframalpha.com/input/?i=sum%20%28sum%20%288%2ai%2ai%2b4096%2ai%2b4%2ai%2aj%2b2048%2aj%29,%20j=i%2b1..N%29,%20i=0..N) is the direct link to the solution. Think before coding. Sometimes your brain can optimize code better than any compiler. |
13,555,856 | For an assignment of a course called High Performance Computing, I required to optimize the following code fragment:
```
int foobar(int a, int b, int N)
{
int i, j, k, x, y;
x = 0;
y = 0;
k = 256;
for (i = 0; i <= N; i++) {
for (j = i + 1; j <= N; j++) {
x = x + 4*(2*i+j)*(i+2*k);
if (i > j){
y = y + 8*(i-j);
}else{
y = y + 8*(j-i);
}
}
}
return x;
}
```
Using some recommendations, I managed to optimize the code (or at least I think so), such as:
1. Constant Propagation
2. Algebraic Simplification
3. Copy Propagation
4. Common Subexpression Elimination
5. Dead Code Elimination
6. Loop Invariant Removal
7. bitwise shifts instead of multiplication as they are less expensive.
Here's my code:
```
int foobar(int a, int b, int N) {
int i, j, x, y, t;
x = 0;
y = 0;
for (i = 0; i <= N; i++) {
t = i + 512;
for (j = i + 1; j <= N; j++) {
x = x + ((i<<3) + (j<<2))*t;
}
}
return x;
}
```
According to my instructor, a well optimized code instructions should have fewer or less costly instructions in assembly language level.And therefore must be run, the instructions in less time than the original code, ie calculations are made with::
>
> execution time = instruction count \* cycles per instruction
>
>
>
When I generate assembly code using the command: `gcc -o code_opt.s -S foobar.c`,
the generated code has many more lines than the original despite having made some optimizations, and run-time is lower, but not as much as in the original code. What am I doing wrong?
Do not paste the assembly code as both are very extensive. So I'm calling the function "foobar" in the main and I am measuring the execution time using the time command in linux
```
int main () {
int a,b,N;
scanf ("%d %d %d",&a,&b,&N);
printf ("%d\n",foobar (a,b,N));
return 0;
}
``` | 2012/11/25 | [
"https://Stackoverflow.com/questions/13555856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/59468/"
] | Initially:
```
for (i = 0; i <= N; i++) {
for (j = i + 1; j <= N; j++) {
x = x + 4*(2*i+j)*(i+2*k);
if (i > j){
y = y + 8*(i-j);
}else{
y = y + 8*(j-i);
}
}
}
```
Removing `y` calculations:
```
for (i = 0; i <= N; i++) {
for (j = i + 1; j <= N; j++) {
x = x + 4*(2*i+j)*(i+2*k);
}
}
```
Splitting `i`, `j`, `k`:
```
for (i = 0; i <= N; i++) {
for (j = i + 1; j <= N; j++) {
x = x + 8*i*i + 16*i*k ; // multiple of 1 (no j)
x = x + (4*i + 8*k)*j ; // multiple of j
}
}
```
Moving them externally (and removing the loop that runs `N-i` times):
```
for (i = 0; i <= N; i++) {
x = x + (8*i*i + 16*i*k) * (N-i) ;
x = x + (4*i + 8*k) * ((N*N+N)/2 - (i*i+i)/2) ;
}
```
Rewritting:
```
for (i = 0; i <= N; i++) {
x = x + ( 8*k*(N*N+N)/2 ) ;
x = x + i * ( 16*k*N + 4*(N*N+N)/2 + 8*k*(-1/2) ) ;
x = x + i*i * ( 8*N + 16*k*(-1) + 4*(-1/2) + 8*k*(-1/2) );
x = x + i*i*i * ( 8*(-1) + 4*(-1/2) ) ;
}
```
Rewritting - recalculating:
```
for (i = 0; i <= N; i++) {
x = x + 4*k*(N*N+N) ; // multiple of 1
x = x + i * ( 16*k*N + 2*(N*N+N) - 4*k ) ; // multiple of i
x = x + i*i * ( 8*N - 20*k - 2 ) ; // multiple of i^2
x = x + i*i*i * ( -10 ) ; // multiple of i^3
}
```
Another move to external (and removal of the i loop):
```
x = x + ( 4*k*(N*N+N) ) * (N+1) ;
x = x + ( 16*k*N + 2*(N*N+N) - 4*k ) * ((N*(N+1))/2) ;
x = x + ( 8*N - 20*k - 2 ) * ((N*(N+1)*(2*N+1))/6);
x = x + (-10) * ((N*N*(N+1)*(N+1))/4) ;
```
Both the above loop removals use the **[summation](http://en.wikipedia.org/wiki/Summation)** formulas:
>
> Sum(1, i = 0..n) = n+1
>
> Sum(i1, i = 0..n) = n(n + 1)/2
>
> Sum(i2, i = 0..n) = n(n + 1)(2n + 1)/6
>
> Sum(i3, i = 0..n) = n2(n + 1)2/4
>
>
> | int foobar(int N) //To avoid unuse passing argument
{
```
int i, j, x=0; //Remove unuseful variable, operation so save stack and Machine cycle
for (i = N; i--; ) //Don't check unnecessary comparison condition
for (j = N+1; --j>i; )
x += (((i<<1)+j)*(i+512)<<2); //Save Machine cycle ,Use shift instead of Multiply
return x;
```
} |
13,555,856 | For an assignment of a course called High Performance Computing, I required to optimize the following code fragment:
```
int foobar(int a, int b, int N)
{
int i, j, k, x, y;
x = 0;
y = 0;
k = 256;
for (i = 0; i <= N; i++) {
for (j = i + 1; j <= N; j++) {
x = x + 4*(2*i+j)*(i+2*k);
if (i > j){
y = y + 8*(i-j);
}else{
y = y + 8*(j-i);
}
}
}
return x;
}
```
Using some recommendations, I managed to optimize the code (or at least I think so), such as:
1. Constant Propagation
2. Algebraic Simplification
3. Copy Propagation
4. Common Subexpression Elimination
5. Dead Code Elimination
6. Loop Invariant Removal
7. bitwise shifts instead of multiplication as they are less expensive.
Here's my code:
```
int foobar(int a, int b, int N) {
int i, j, x, y, t;
x = 0;
y = 0;
for (i = 0; i <= N; i++) {
t = i + 512;
for (j = i + 1; j <= N; j++) {
x = x + ((i<<3) + (j<<2))*t;
}
}
return x;
}
```
According to my instructor, a well optimized code instructions should have fewer or less costly instructions in assembly language level.And therefore must be run, the instructions in less time than the original code, ie calculations are made with::
>
> execution time = instruction count \* cycles per instruction
>
>
>
When I generate assembly code using the command: `gcc -o code_opt.s -S foobar.c`,
the generated code has many more lines than the original despite having made some optimizations, and run-time is lower, but not as much as in the original code. What am I doing wrong?
Do not paste the assembly code as both are very extensive. So I'm calling the function "foobar" in the main and I am measuring the execution time using the time command in linux
```
int main () {
int a,b,N;
scanf ("%d %d %d",&a,&b,&N);
printf ("%d\n",foobar (a,b,N));
return 0;
}
``` | 2012/11/25 | [
"https://Stackoverflow.com/questions/13555856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/59468/"
] | OK... so here is my solution, along with inline comments to explain what I did and how.
```
int foobar(int N)
{ // We eliminate unused arguments
int x = 0, i = 0, i2 = 0, j, k, z;
// We only iterate up to N on the outer loop, since the
// last iteration doesn't do anything useful. Also we keep
// track of '2*i' (which is used throughout the code) by a
// second variable 'i2' which we increment by two in every
// iteration, essentially converting multiplication into addition.
while(i < N)
{
// We hoist the calculation '4 * (i+2*k)' out of the loop
// since k is a literal constant and 'i' is a constant during
// the inner loop. We could convert the multiplication by 2
// into a left shift, but hey, let's not go *crazy*!
//
// (4 * (i+2*k)) <=>
// (4 * i) + (4 * 2 * k) <=>
// (2 * i2) + (8 * k) <=>
// (2 * i2) + (8 * 512) <=>
// (2 * i2) + 2048
k = (2 * i2) + 2048;
// We have now converted the expression:
// x = x + 4*(2*i+j)*(i+2*k);
//
// into the expression:
// x = x + (i2 + j) * k;
//
// Counterintuively we now *expand* the formula into:
// x = x + (i2 * k) + (j * k);
//
// Now observe that (i2 * k) is a constant inside the inner
// loop which we can calculate only once here. Also observe
// that is simply added into x a total (N - i) times, so
// we take advantange of the abelian nature of addition
// to hoist it completely out of the loop
x = x + (i2 * k) * (N - i);
// Observe that inside this loop we calculate (j * k) repeatedly,
// and that j is just an increasing counter. So now instead of
// doing numerous multiplications, let's break the operation into
// two parts: a multiplication, which we hoist out of the inner
// loop and additions which we continue performing in the inner
// loop.
z = i * k;
for (j = i + 1; j <= N; j++)
{
z = z + k;
x = x + z;
}
i++;
i2 += 2;
}
return x;
}
```
The code, without any of the explanations boils down to this:
```
int foobar(int N)
{
int x = 0, i = 0, i2 = 0, j, k, z;
while(i < N)
{
k = (2 * i2) + 2048;
x = x + (i2 * k) * (N - i);
z = i * k;
for (j = i + 1; j <= N; j++)
{
z = z + k;
x = x + z;
}
i++;
i2 += 2;
}
return x;
}
```
I hope this helps. | int foobar(int N) //To avoid unuse passing argument
{
```
int i, j, x=0; //Remove unuseful variable, operation so save stack and Machine cycle
for (i = N; i--; ) //Don't check unnecessary comparison condition
for (j = N+1; --j>i; )
x += (((i<<1)+j)*(i+512)<<2); //Save Machine cycle ,Use shift instead of Multiply
return x;
```
} |
13,555,856 | For an assignment of a course called High Performance Computing, I required to optimize the following code fragment:
```
int foobar(int a, int b, int N)
{
int i, j, k, x, y;
x = 0;
y = 0;
k = 256;
for (i = 0; i <= N; i++) {
for (j = i + 1; j <= N; j++) {
x = x + 4*(2*i+j)*(i+2*k);
if (i > j){
y = y + 8*(i-j);
}else{
y = y + 8*(j-i);
}
}
}
return x;
}
```
Using some recommendations, I managed to optimize the code (or at least I think so), such as:
1. Constant Propagation
2. Algebraic Simplification
3. Copy Propagation
4. Common Subexpression Elimination
5. Dead Code Elimination
6. Loop Invariant Removal
7. bitwise shifts instead of multiplication as they are less expensive.
Here's my code:
```
int foobar(int a, int b, int N) {
int i, j, x, y, t;
x = 0;
y = 0;
for (i = 0; i <= N; i++) {
t = i + 512;
for (j = i + 1; j <= N; j++) {
x = x + ((i<<3) + (j<<2))*t;
}
}
return x;
}
```
According to my instructor, a well optimized code instructions should have fewer or less costly instructions in assembly language level.And therefore must be run, the instructions in less time than the original code, ie calculations are made with::
>
> execution time = instruction count \* cycles per instruction
>
>
>
When I generate assembly code using the command: `gcc -o code_opt.s -S foobar.c`,
the generated code has many more lines than the original despite having made some optimizations, and run-time is lower, but not as much as in the original code. What am I doing wrong?
Do not paste the assembly code as both are very extensive. So I'm calling the function "foobar" in the main and I am measuring the execution time using the time command in linux
```
int main () {
int a,b,N;
scanf ("%d %d %d",&a,&b,&N);
printf ("%d\n",foobar (a,b,N));
return 0;
}
``` | 2012/11/25 | [
"https://Stackoverflow.com/questions/13555856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/59468/"
] | Briefly scanning the first routine, the first thing you notice is that expressions involving "y" are completely unused and can be eliminated (as you did). This further permits eliminating the if/else (as you did).
What remains is the two `for` loops and the messy expression. Factoring out the pieces of that expression that do not depend on `j` is the next step. You removed one such expression, but `(i<<3)` (ie, i \* 8) remains in the inner loop, and can be removed.
Pascal's answer reminded me that you can use a loop stride optimization. First move `(i<<3) * t` out of the inner loop (call it `i1`), then calculate, when initializing the loop, a value `j1` that equals `(i<<2) * t`. On each iteration increment `j1` by `4 * t` (which is a pre-calculated constant). Replace your inner expression with `x = x + i1 + j1;`.
One suspects that there may be some way to combine the two loops into one, with a stride, but I'm not seeing it offhand. | A few other things I can see. You don't need `y`, so you can remove its declaration and initialisation.
Also, the values passed in for `a` and `b` aren't actually used, so you could use these as local variables instead of `x` and `t`.
Also, rather than adding `i` to 512 each time through you can note that `t` starts at 512 and increments by 1 each iteration.
```
int foobar(int a, int b, int N) {
int i, j;
a = 0;
b = 512;
for (i = 0; i <= N; i++, b++) {
for (j = i + 1; j <= N; j++) {
a = a + ((i<<3) + (j<<2))*b;
}
}
return a;
}
```
Once you get to this point you can also observe that, aside from initialising `j`, `i` and `j` are only used in a single mutiple each - `i<<3` and `j<<2`. We can code this directly in the loop logic, thus:
```
int foobar(int a, int b, int N) {
int i, j, iLimit, jLimit;
a = 0;
b = 512;
iLimit = N << 3;
jLimit = N << 2;
for (i = 0; i <= iLimit; i+=8) {
for (j = i >> 1 + 4; j <= jLimit; j+=4) {
a = a + (i + j)*b;
}
b++;
}
return a;
}
``` |
13,555,856 | For an assignment of a course called High Performance Computing, I required to optimize the following code fragment:
```
int foobar(int a, int b, int N)
{
int i, j, k, x, y;
x = 0;
y = 0;
k = 256;
for (i = 0; i <= N; i++) {
for (j = i + 1; j <= N; j++) {
x = x + 4*(2*i+j)*(i+2*k);
if (i > j){
y = y + 8*(i-j);
}else{
y = y + 8*(j-i);
}
}
}
return x;
}
```
Using some recommendations, I managed to optimize the code (or at least I think so), such as:
1. Constant Propagation
2. Algebraic Simplification
3. Copy Propagation
4. Common Subexpression Elimination
5. Dead Code Elimination
6. Loop Invariant Removal
7. bitwise shifts instead of multiplication as they are less expensive.
Here's my code:
```
int foobar(int a, int b, int N) {
int i, j, x, y, t;
x = 0;
y = 0;
for (i = 0; i <= N; i++) {
t = i + 512;
for (j = i + 1; j <= N; j++) {
x = x + ((i<<3) + (j<<2))*t;
}
}
return x;
}
```
According to my instructor, a well optimized code instructions should have fewer or less costly instructions in assembly language level.And therefore must be run, the instructions in less time than the original code, ie calculations are made with::
>
> execution time = instruction count \* cycles per instruction
>
>
>
When I generate assembly code using the command: `gcc -o code_opt.s -S foobar.c`,
the generated code has many more lines than the original despite having made some optimizations, and run-time is lower, but not as much as in the original code. What am I doing wrong?
Do not paste the assembly code as both are very extensive. So I'm calling the function "foobar" in the main and I am measuring the execution time using the time command in linux
```
int main () {
int a,b,N;
scanf ("%d %d %d",&a,&b,&N);
printf ("%d\n",foobar (a,b,N));
return 0;
}
``` | 2012/11/25 | [
"https://Stackoverflow.com/questions/13555856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/59468/"
] | This function is equivalent with the following formula, which contains only **4 integer multiplications**, and **1 integer division**:
```
x = N * (N + 1) * (N * (7 * N + 8187) - 2050) / 6;
```
To get this, I simply typed the sum calculated by your nested loops into [Wolfram Alpha](http://www.wolframalpha.com):
```
sum (sum (8*i*i+4096*i+4*i*j+2048*j), j=i+1..N), i=0..N
```
[Here](http://www.wolframalpha.com/input/?i=sum%20%28sum%20%288%2ai%2ai%2b4096%2ai%2b4%2ai%2aj%2b2048%2aj%29,%20j=i%2b1..N%29,%20i=0..N) is the direct link to the solution. Think before coding. Sometimes your brain can optimize code better than any compiler. | Briefly scanning the first routine, the first thing you notice is that expressions involving "y" are completely unused and can be eliminated (as you did). This further permits eliminating the if/else (as you did).
What remains is the two `for` loops and the messy expression. Factoring out the pieces of that expression that do not depend on `j` is the next step. You removed one such expression, but `(i<<3)` (ie, i \* 8) remains in the inner loop, and can be removed.
Pascal's answer reminded me that you can use a loop stride optimization. First move `(i<<3) * t` out of the inner loop (call it `i1`), then calculate, when initializing the loop, a value `j1` that equals `(i<<2) * t`. On each iteration increment `j1` by `4 * t` (which is a pre-calculated constant). Replace your inner expression with `x = x + i1 + j1;`.
One suspects that there may be some way to combine the two loops into one, with a stride, but I'm not seeing it offhand. |
13,555,856 | For an assignment of a course called High Performance Computing, I required to optimize the following code fragment:
```
int foobar(int a, int b, int N)
{
int i, j, k, x, y;
x = 0;
y = 0;
k = 256;
for (i = 0; i <= N; i++) {
for (j = i + 1; j <= N; j++) {
x = x + 4*(2*i+j)*(i+2*k);
if (i > j){
y = y + 8*(i-j);
}else{
y = y + 8*(j-i);
}
}
}
return x;
}
```
Using some recommendations, I managed to optimize the code (or at least I think so), such as:
1. Constant Propagation
2. Algebraic Simplification
3. Copy Propagation
4. Common Subexpression Elimination
5. Dead Code Elimination
6. Loop Invariant Removal
7. bitwise shifts instead of multiplication as they are less expensive.
Here's my code:
```
int foobar(int a, int b, int N) {
int i, j, x, y, t;
x = 0;
y = 0;
for (i = 0; i <= N; i++) {
t = i + 512;
for (j = i + 1; j <= N; j++) {
x = x + ((i<<3) + (j<<2))*t;
}
}
return x;
}
```
According to my instructor, a well optimized code instructions should have fewer or less costly instructions in assembly language level.And therefore must be run, the instructions in less time than the original code, ie calculations are made with::
>
> execution time = instruction count \* cycles per instruction
>
>
>
When I generate assembly code using the command: `gcc -o code_opt.s -S foobar.c`,
the generated code has many more lines than the original despite having made some optimizations, and run-time is lower, but not as much as in the original code. What am I doing wrong?
Do not paste the assembly code as both are very extensive. So I'm calling the function "foobar" in the main and I am measuring the execution time using the time command in linux
```
int main () {
int a,b,N;
scanf ("%d %d %d",&a,&b,&N);
printf ("%d\n",foobar (a,b,N));
return 0;
}
``` | 2012/11/25 | [
"https://Stackoverflow.com/questions/13555856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/59468/"
] | Initially:
```
for (i = 0; i <= N; i++) {
for (j = i + 1; j <= N; j++) {
x = x + 4*(2*i+j)*(i+2*k);
if (i > j){
y = y + 8*(i-j);
}else{
y = y + 8*(j-i);
}
}
}
```
Removing `y` calculations:
```
for (i = 0; i <= N; i++) {
for (j = i + 1; j <= N; j++) {
x = x + 4*(2*i+j)*(i+2*k);
}
}
```
Splitting `i`, `j`, `k`:
```
for (i = 0; i <= N; i++) {
for (j = i + 1; j <= N; j++) {
x = x + 8*i*i + 16*i*k ; // multiple of 1 (no j)
x = x + (4*i + 8*k)*j ; // multiple of j
}
}
```
Moving them externally (and removing the loop that runs `N-i` times):
```
for (i = 0; i <= N; i++) {
x = x + (8*i*i + 16*i*k) * (N-i) ;
x = x + (4*i + 8*k) * ((N*N+N)/2 - (i*i+i)/2) ;
}
```
Rewritting:
```
for (i = 0; i <= N; i++) {
x = x + ( 8*k*(N*N+N)/2 ) ;
x = x + i * ( 16*k*N + 4*(N*N+N)/2 + 8*k*(-1/2) ) ;
x = x + i*i * ( 8*N + 16*k*(-1) + 4*(-1/2) + 8*k*(-1/2) );
x = x + i*i*i * ( 8*(-1) + 4*(-1/2) ) ;
}
```
Rewritting - recalculating:
```
for (i = 0; i <= N; i++) {
x = x + 4*k*(N*N+N) ; // multiple of 1
x = x + i * ( 16*k*N + 2*(N*N+N) - 4*k ) ; // multiple of i
x = x + i*i * ( 8*N - 20*k - 2 ) ; // multiple of i^2
x = x + i*i*i * ( -10 ) ; // multiple of i^3
}
```
Another move to external (and removal of the i loop):
```
x = x + ( 4*k*(N*N+N) ) * (N+1) ;
x = x + ( 16*k*N + 2*(N*N+N) - 4*k ) * ((N*(N+1))/2) ;
x = x + ( 8*N - 20*k - 2 ) * ((N*(N+1)*(2*N+1))/6);
x = x + (-10) * ((N*N*(N+1)*(N+1))/4) ;
```
Both the above loop removals use the **[summation](http://en.wikipedia.org/wiki/Summation)** formulas:
>
> Sum(1, i = 0..n) = n+1
>
> Sum(i1, i = 0..n) = n(n + 1)/2
>
> Sum(i2, i = 0..n) = n(n + 1)(2n + 1)/6
>
> Sum(i3, i = 0..n) = n2(n + 1)2/4
>
>
> | A few other things I can see. You don't need `y`, so you can remove its declaration and initialisation.
Also, the values passed in for `a` and `b` aren't actually used, so you could use these as local variables instead of `x` and `t`.
Also, rather than adding `i` to 512 each time through you can note that `t` starts at 512 and increments by 1 each iteration.
```
int foobar(int a, int b, int N) {
int i, j;
a = 0;
b = 512;
for (i = 0; i <= N; i++, b++) {
for (j = i + 1; j <= N; j++) {
a = a + ((i<<3) + (j<<2))*b;
}
}
return a;
}
```
Once you get to this point you can also observe that, aside from initialising `j`, `i` and `j` are only used in a single mutiple each - `i<<3` and `j<<2`. We can code this directly in the loop logic, thus:
```
int foobar(int a, int b, int N) {
int i, j, iLimit, jLimit;
a = 0;
b = 512;
iLimit = N << 3;
jLimit = N << 2;
for (i = 0; i <= iLimit; i+=8) {
for (j = i >> 1 + 4; j <= jLimit; j+=4) {
a = a + (i + j)*b;
}
b++;
}
return a;
}
``` |
13,555,856 | For an assignment of a course called High Performance Computing, I required to optimize the following code fragment:
```
int foobar(int a, int b, int N)
{
int i, j, k, x, y;
x = 0;
y = 0;
k = 256;
for (i = 0; i <= N; i++) {
for (j = i + 1; j <= N; j++) {
x = x + 4*(2*i+j)*(i+2*k);
if (i > j){
y = y + 8*(i-j);
}else{
y = y + 8*(j-i);
}
}
}
return x;
}
```
Using some recommendations, I managed to optimize the code (or at least I think so), such as:
1. Constant Propagation
2. Algebraic Simplification
3. Copy Propagation
4. Common Subexpression Elimination
5. Dead Code Elimination
6. Loop Invariant Removal
7. bitwise shifts instead of multiplication as they are less expensive.
Here's my code:
```
int foobar(int a, int b, int N) {
int i, j, x, y, t;
x = 0;
y = 0;
for (i = 0; i <= N; i++) {
t = i + 512;
for (j = i + 1; j <= N; j++) {
x = x + ((i<<3) + (j<<2))*t;
}
}
return x;
}
```
According to my instructor, a well optimized code instructions should have fewer or less costly instructions in assembly language level.And therefore must be run, the instructions in less time than the original code, ie calculations are made with::
>
> execution time = instruction count \* cycles per instruction
>
>
>
When I generate assembly code using the command: `gcc -o code_opt.s -S foobar.c`,
the generated code has many more lines than the original despite having made some optimizations, and run-time is lower, but not as much as in the original code. What am I doing wrong?
Do not paste the assembly code as both are very extensive. So I'm calling the function "foobar" in the main and I am measuring the execution time using the time command in linux
```
int main () {
int a,b,N;
scanf ("%d %d %d",&a,&b,&N);
printf ("%d\n",foobar (a,b,N));
return 0;
}
``` | 2012/11/25 | [
"https://Stackoverflow.com/questions/13555856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/59468/"
] | Initially:
```
for (i = 0; i <= N; i++) {
for (j = i + 1; j <= N; j++) {
x = x + 4*(2*i+j)*(i+2*k);
if (i > j){
y = y + 8*(i-j);
}else{
y = y + 8*(j-i);
}
}
}
```
Removing `y` calculations:
```
for (i = 0; i <= N; i++) {
for (j = i + 1; j <= N; j++) {
x = x + 4*(2*i+j)*(i+2*k);
}
}
```
Splitting `i`, `j`, `k`:
```
for (i = 0; i <= N; i++) {
for (j = i + 1; j <= N; j++) {
x = x + 8*i*i + 16*i*k ; // multiple of 1 (no j)
x = x + (4*i + 8*k)*j ; // multiple of j
}
}
```
Moving them externally (and removing the loop that runs `N-i` times):
```
for (i = 0; i <= N; i++) {
x = x + (8*i*i + 16*i*k) * (N-i) ;
x = x + (4*i + 8*k) * ((N*N+N)/2 - (i*i+i)/2) ;
}
```
Rewritting:
```
for (i = 0; i <= N; i++) {
x = x + ( 8*k*(N*N+N)/2 ) ;
x = x + i * ( 16*k*N + 4*(N*N+N)/2 + 8*k*(-1/2) ) ;
x = x + i*i * ( 8*N + 16*k*(-1) + 4*(-1/2) + 8*k*(-1/2) );
x = x + i*i*i * ( 8*(-1) + 4*(-1/2) ) ;
}
```
Rewritting - recalculating:
```
for (i = 0; i <= N; i++) {
x = x + 4*k*(N*N+N) ; // multiple of 1
x = x + i * ( 16*k*N + 2*(N*N+N) - 4*k ) ; // multiple of i
x = x + i*i * ( 8*N - 20*k - 2 ) ; // multiple of i^2
x = x + i*i*i * ( -10 ) ; // multiple of i^3
}
```
Another move to external (and removal of the i loop):
```
x = x + ( 4*k*(N*N+N) ) * (N+1) ;
x = x + ( 16*k*N + 2*(N*N+N) - 4*k ) * ((N*(N+1))/2) ;
x = x + ( 8*N - 20*k - 2 ) * ((N*(N+1)*(2*N+1))/6);
x = x + (-10) * ((N*N*(N+1)*(N+1))/4) ;
```
Both the above loop removals use the **[summation](http://en.wikipedia.org/wiki/Summation)** formulas:
>
> Sum(1, i = 0..n) = n+1
>
> Sum(i1, i = 0..n) = n(n + 1)/2
>
> Sum(i2, i = 0..n) = n(n + 1)(2n + 1)/6
>
> Sum(i3, i = 0..n) = n2(n + 1)2/4
>
>
> | `y` does not affect the final result of the code - removed:
```
int foobar(int a, int b, int N)
{
int i, j, k, x, y;
x = 0;
//y = 0;
k = 256;
for (i = 0; i <= N; i++) {
for (j = i + 1; j <= N; j++) {
x = x + 4*(2*i+j)*(i+2*k);
//if (i > j){
// y = y + 8*(i-j);
//}else{
// y = y + 8*(j-i);
//}
}
}
return x;
}
```
`k` is simply a constant:
```
int foobar(int a, int b, int N)
{
int i, j, x;
x = 0;
for (i = 0; i <= N; i++) {
for (j = i + 1; j <= N; j++) {
x = x + 4*(2*i+j)*(i+2*256);
}
}
return x;
}
```
The inner expression can be transformed to: `x += 8*i*i + 4096*i + 4*i*j + 2048*j`. Use math to push all of them to the outer loop: `x += 8*i*i*(N-i) + 4096*i*(N-i) + 2*i*(N-i)*(N+i+1) + 1024*(N-i)*(N+i+1)`.
You can expand the above expression, and apply [sum of squares and sum of cubes formula](http://library.thinkquest.org/20991/gather/formula/data/209.html) to obtain a close form expression, which should run faster than the doubly nested loop. I leave it as an exercise to you. As a result, `i` and `j` will also be removed.
`a` and `b` should also be removed if possible - since `a` and `b` are supplied as argument but never used in your code.
Sum of squares and sum of cubes formula:
* Sum(x2, x = 1..n) = n(n + 1)(2n + 1)/6
* Sum(x3, x = 1..n) = n2(n + 1)2/4 |
13,555,856 | For an assignment of a course called High Performance Computing, I required to optimize the following code fragment:
```
int foobar(int a, int b, int N)
{
int i, j, k, x, y;
x = 0;
y = 0;
k = 256;
for (i = 0; i <= N; i++) {
for (j = i + 1; j <= N; j++) {
x = x + 4*(2*i+j)*(i+2*k);
if (i > j){
y = y + 8*(i-j);
}else{
y = y + 8*(j-i);
}
}
}
return x;
}
```
Using some recommendations, I managed to optimize the code (or at least I think so), such as:
1. Constant Propagation
2. Algebraic Simplification
3. Copy Propagation
4. Common Subexpression Elimination
5. Dead Code Elimination
6. Loop Invariant Removal
7. bitwise shifts instead of multiplication as they are less expensive.
Here's my code:
```
int foobar(int a, int b, int N) {
int i, j, x, y, t;
x = 0;
y = 0;
for (i = 0; i <= N; i++) {
t = i + 512;
for (j = i + 1; j <= N; j++) {
x = x + ((i<<3) + (j<<2))*t;
}
}
return x;
}
```
According to my instructor, a well optimized code instructions should have fewer or less costly instructions in assembly language level.And therefore must be run, the instructions in less time than the original code, ie calculations are made with::
>
> execution time = instruction count \* cycles per instruction
>
>
>
When I generate assembly code using the command: `gcc -o code_opt.s -S foobar.c`,
the generated code has many more lines than the original despite having made some optimizations, and run-time is lower, but not as much as in the original code. What am I doing wrong?
Do not paste the assembly code as both are very extensive. So I'm calling the function "foobar" in the main and I am measuring the execution time using the time command in linux
```
int main () {
int a,b,N;
scanf ("%d %d %d",&a,&b,&N);
printf ("%d\n",foobar (a,b,N));
return 0;
}
``` | 2012/11/25 | [
"https://Stackoverflow.com/questions/13555856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/59468/"
] | Briefly scanning the first routine, the first thing you notice is that expressions involving "y" are completely unused and can be eliminated (as you did). This further permits eliminating the if/else (as you did).
What remains is the two `for` loops and the messy expression. Factoring out the pieces of that expression that do not depend on `j` is the next step. You removed one such expression, but `(i<<3)` (ie, i \* 8) remains in the inner loop, and can be removed.
Pascal's answer reminded me that you can use a loop stride optimization. First move `(i<<3) * t` out of the inner loop (call it `i1`), then calculate, when initializing the loop, a value `j1` that equals `(i<<2) * t`. On each iteration increment `j1` by `4 * t` (which is a pre-calculated constant). Replace your inner expression with `x = x + i1 + j1;`.
One suspects that there may be some way to combine the two loops into one, with a stride, but I'm not seeing it offhand. | OK... so here is my solution, along with inline comments to explain what I did and how.
```
int foobar(int N)
{ // We eliminate unused arguments
int x = 0, i = 0, i2 = 0, j, k, z;
// We only iterate up to N on the outer loop, since the
// last iteration doesn't do anything useful. Also we keep
// track of '2*i' (which is used throughout the code) by a
// second variable 'i2' which we increment by two in every
// iteration, essentially converting multiplication into addition.
while(i < N)
{
// We hoist the calculation '4 * (i+2*k)' out of the loop
// since k is a literal constant and 'i' is a constant during
// the inner loop. We could convert the multiplication by 2
// into a left shift, but hey, let's not go *crazy*!
//
// (4 * (i+2*k)) <=>
// (4 * i) + (4 * 2 * k) <=>
// (2 * i2) + (8 * k) <=>
// (2 * i2) + (8 * 512) <=>
// (2 * i2) + 2048
k = (2 * i2) + 2048;
// We have now converted the expression:
// x = x + 4*(2*i+j)*(i+2*k);
//
// into the expression:
// x = x + (i2 + j) * k;
//
// Counterintuively we now *expand* the formula into:
// x = x + (i2 * k) + (j * k);
//
// Now observe that (i2 * k) is a constant inside the inner
// loop which we can calculate only once here. Also observe
// that is simply added into x a total (N - i) times, so
// we take advantange of the abelian nature of addition
// to hoist it completely out of the loop
x = x + (i2 * k) * (N - i);
// Observe that inside this loop we calculate (j * k) repeatedly,
// and that j is just an increasing counter. So now instead of
// doing numerous multiplications, let's break the operation into
// two parts: a multiplication, which we hoist out of the inner
// loop and additions which we continue performing in the inner
// loop.
z = i * k;
for (j = i + 1; j <= N; j++)
{
z = z + k;
x = x + z;
}
i++;
i2 += 2;
}
return x;
}
```
The code, without any of the explanations boils down to this:
```
int foobar(int N)
{
int x = 0, i = 0, i2 = 0, j, k, z;
while(i < N)
{
k = (2 * i2) + 2048;
x = x + (i2 * k) * (N - i);
z = i * k;
for (j = i + 1; j <= N; j++)
{
z = z + k;
x = x + z;
}
i++;
i2 += 2;
}
return x;
}
```
I hope this helps. |
13,555,856 | For an assignment of a course called High Performance Computing, I required to optimize the following code fragment:
```
int foobar(int a, int b, int N)
{
int i, j, k, x, y;
x = 0;
y = 0;
k = 256;
for (i = 0; i <= N; i++) {
for (j = i + 1; j <= N; j++) {
x = x + 4*(2*i+j)*(i+2*k);
if (i > j){
y = y + 8*(i-j);
}else{
y = y + 8*(j-i);
}
}
}
return x;
}
```
Using some recommendations, I managed to optimize the code (or at least I think so), such as:
1. Constant Propagation
2. Algebraic Simplification
3. Copy Propagation
4. Common Subexpression Elimination
5. Dead Code Elimination
6. Loop Invariant Removal
7. bitwise shifts instead of multiplication as they are less expensive.
Here's my code:
```
int foobar(int a, int b, int N) {
int i, j, x, y, t;
x = 0;
y = 0;
for (i = 0; i <= N; i++) {
t = i + 512;
for (j = i + 1; j <= N; j++) {
x = x + ((i<<3) + (j<<2))*t;
}
}
return x;
}
```
According to my instructor, a well optimized code instructions should have fewer or less costly instructions in assembly language level.And therefore must be run, the instructions in less time than the original code, ie calculations are made with::
>
> execution time = instruction count \* cycles per instruction
>
>
>
When I generate assembly code using the command: `gcc -o code_opt.s -S foobar.c`,
the generated code has many more lines than the original despite having made some optimizations, and run-time is lower, but not as much as in the original code. What am I doing wrong?
Do not paste the assembly code as both are very extensive. So I'm calling the function "foobar" in the main and I am measuring the execution time using the time command in linux
```
int main () {
int a,b,N;
scanf ("%d %d %d",&a,&b,&N);
printf ("%d\n",foobar (a,b,N));
return 0;
}
``` | 2012/11/25 | [
"https://Stackoverflow.com/questions/13555856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/59468/"
] | `y` does not affect the final result of the code - removed:
```
int foobar(int a, int b, int N)
{
int i, j, k, x, y;
x = 0;
//y = 0;
k = 256;
for (i = 0; i <= N; i++) {
for (j = i + 1; j <= N; j++) {
x = x + 4*(2*i+j)*(i+2*k);
//if (i > j){
// y = y + 8*(i-j);
//}else{
// y = y + 8*(j-i);
//}
}
}
return x;
}
```
`k` is simply a constant:
```
int foobar(int a, int b, int N)
{
int i, j, x;
x = 0;
for (i = 0; i <= N; i++) {
for (j = i + 1; j <= N; j++) {
x = x + 4*(2*i+j)*(i+2*256);
}
}
return x;
}
```
The inner expression can be transformed to: `x += 8*i*i + 4096*i + 4*i*j + 2048*j`. Use math to push all of them to the outer loop: `x += 8*i*i*(N-i) + 4096*i*(N-i) + 2*i*(N-i)*(N+i+1) + 1024*(N-i)*(N+i+1)`.
You can expand the above expression, and apply [sum of squares and sum of cubes formula](http://library.thinkquest.org/20991/gather/formula/data/209.html) to obtain a close form expression, which should run faster than the doubly nested loop. I leave it as an exercise to you. As a result, `i` and `j` will also be removed.
`a` and `b` should also be removed if possible - since `a` and `b` are supplied as argument but never used in your code.
Sum of squares and sum of cubes formula:
* Sum(x2, x = 1..n) = n(n + 1)(2n + 1)/6
* Sum(x3, x = 1..n) = n2(n + 1)2/4 | OK... so here is my solution, along with inline comments to explain what I did and how.
```
int foobar(int N)
{ // We eliminate unused arguments
int x = 0, i = 0, i2 = 0, j, k, z;
// We only iterate up to N on the outer loop, since the
// last iteration doesn't do anything useful. Also we keep
// track of '2*i' (which is used throughout the code) by a
// second variable 'i2' which we increment by two in every
// iteration, essentially converting multiplication into addition.
while(i < N)
{
// We hoist the calculation '4 * (i+2*k)' out of the loop
// since k is a literal constant and 'i' is a constant during
// the inner loop. We could convert the multiplication by 2
// into a left shift, but hey, let's not go *crazy*!
//
// (4 * (i+2*k)) <=>
// (4 * i) + (4 * 2 * k) <=>
// (2 * i2) + (8 * k) <=>
// (2 * i2) + (8 * 512) <=>
// (2 * i2) + 2048
k = (2 * i2) + 2048;
// We have now converted the expression:
// x = x + 4*(2*i+j)*(i+2*k);
//
// into the expression:
// x = x + (i2 + j) * k;
//
// Counterintuively we now *expand* the formula into:
// x = x + (i2 * k) + (j * k);
//
// Now observe that (i2 * k) is a constant inside the inner
// loop which we can calculate only once here. Also observe
// that is simply added into x a total (N - i) times, so
// we take advantange of the abelian nature of addition
// to hoist it completely out of the loop
x = x + (i2 * k) * (N - i);
// Observe that inside this loop we calculate (j * k) repeatedly,
// and that j is just an increasing counter. So now instead of
// doing numerous multiplications, let's break the operation into
// two parts: a multiplication, which we hoist out of the inner
// loop and additions which we continue performing in the inner
// loop.
z = i * k;
for (j = i + 1; j <= N; j++)
{
z = z + k;
x = x + z;
}
i++;
i2 += 2;
}
return x;
}
```
The code, without any of the explanations boils down to this:
```
int foobar(int N)
{
int x = 0, i = 0, i2 = 0, j, k, z;
while(i < N)
{
k = (2 * i2) + 2048;
x = x + (i2 * k) * (N - i);
z = i * k;
for (j = i + 1; j <= N; j++)
{
z = z + k;
x = x + z;
}
i++;
i2 += 2;
}
return x;
}
```
I hope this helps. |
34,134 | 1. Came across an article on the web on "evaluation of training effectiveness". The author suggests that the "t-value" obtained from a "Paired t-test" conducted using pre-test and post test scores can be used to quantify the effectiveness of training.
2. The t-value was termed as the "Index of Learning" and the author claimed the following:
a. An "Index of learning" (t-value) between 0 to 1.5 indicates no evidence of learning.
b. A t-value between 1.5 to 2.0 indicates some evidence of learning.
c. A t-value between 2 to 3 indicates strong evidence of learning.
d. A t-value above 3 indicates very strong strong evidence of learning.
3. In my limited understanding of the subject, the t-value, critical t-value and p-value of a t-test would depend on the significance level and degrees of freedom of the associated data. I have thus not understood the rationale behind the generalization made by the author (Para 2 (a) to 2 (c) above). I would be extremely grateful for any explanations. Thanks. | 2012/08/11 | [
"https://stats.stackexchange.com/questions/34134",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/13226/"
] | The difficulty here appears to stem from terminology and convention.
First let's just define terms in terms of statistical theory. We observe a **data** $X\_1 ... X\_n$, each a random variable. We define a **statistic** as a function of that data, $S(X\_1...X\_n)$. As a function of random variables, the statistic is also a random variable. So far this constitutes the **estimation** part of statistics.
Certain statistic functions are better suited for detecting certain characteristics. In the case of the paired t-value, a *statistic*, it is designed to detect differences in the mean between 2 populations. But how do we know when $S$ is "abnormal", or "substantially different"? Here like most other things in like we go to some well-defined set of reference values, and compare our obtained statistic with the critical statistic. This part constitutes the **inference** part of statistics.
In this case, if we make the assumption that the data is independent, normally distributed, then we can go to the t-value table to look up the corresponding critical t-value. If the t-value is more extreme than the critical value then we can call it statistically significant, and vice versa.
This division between **estimation** and **inference** is the difference.
The paper you referred to appeared more interested in the **estimation** of differences in learning. It may be of interest to make the determination--the **inference**--of whether of not the learning was statistically significant. But that means you end up with a binary determination of "yes, significant" or "no, not significant". Letting the estimation--the t-values--be the measurement allows the user to quantitatively compare paired units.
The same thing is done for estimating, for example, bone density. The measured bone density (DEXA), a number, is converted into a t-value based on age- and ethnicity-controlled reference population. [Wikipedia article](http://en.wikipedia.org/wiki/Bone_density). The t-value is then used to make the diagnosis of osteoporosis (t<-2.5) versus osteopenia (t between -2.5 and -1) | I don't think this is an issue of estimation versus inference. I think the author of the article is being a little oversimplistic. He is trying to put meaning to specific values of a t statistic as those it is a fixed measure rather than a random qusntity. If the idea is to identify what is a high value versus an intermediate or low value then you should consider the distribtuion of the t when there is no true difference. Then a large value would indicate that the difference is more likely real than a chance event. This is like doing statistical inference.
So I think ignoring the sample size and the dependence of the t statistic on degrees of freedom is as you point out a flaw in the author's argument. |
45,205,278 | I am developing an list app with FirebaseListAdapter. I'm having problem with the getKey() value. I want to access the data under the listitem that is been clicked and display it in the textview from another activity. But ican't figure out what to do ?
Here's what my code looks like now
```
myList.setAdapter(myAdapter);
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Story st = (Story)parent.getItemAtPosition(position);
String stry = st.Story;
Toast.makeText(MainActivity.this, ""+stry,Toast.LENGTH_LONG).show();
Intent intent = new Intent(context, MyStoryActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Bundle bundle = new Bundle();
bundle.putString("Story", stry);
intent.putExtras(bundle);
context.startActivity(intent);
}
});
}
```
I'm getting the story value of the last added story when I clicked on any of the list item.
Here's the code of another activity where I want to display the value of the Story.
```
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.story_view);
database = FirebaseDatabase.getInstance();
ref = database.getReference("Stories");
ttl = (TextView) findViewById(R.id.title);
stry = (TextView) findViewById(R.id.story);
Bundle bundle = getIntent().getExtras();
stry1 = bundle.getString("Story");
ref.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Story ad = dataSnapshot.getValue(Story.class);
ttl.setText(ad.Title);
stry.setText(stry1);
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
```
This is what my database looks like
[](https://i.stack.imgur.com/cxBFn.jpg)
Here is the Story.class
```
public class Story {
public String Title;
public String Story;
// Default constructor required for calls to
// DataSnapshot.getValue(User.class)
public Story() {
}
public Story(String ttl, String stry) {
this.Title = ttl;
this.Story = stry;
}}
``` | 2017/07/20 | [
"https://Stackoverflow.com/questions/45205278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6040573/"
] | In my case the problem was with repositry name e.g I mistakenly added one extra `.` to the end of repositry name while creating repositry. The name was like CRUD-With-GraphQL..git. So the `.` before `.git` was the actual issue. I renamed my repositry, removed the extra `.` and the problem was resolved. | As a workaround, try, in a regular `CMD` with [git in your `%PATH%`](https://stackoverflow.com/a/44878018/6309):
```
cd H:\GIT\astranauta\5etools
git clone -v --recurse-submodules --progress https://github.com/astranauta/5etools.git
```
No need for double-quotes around git.
If you were in a git bash, I would have tried
```
git clone -v --recurse-submodules --progress https://github.com/astranauta/5etools.git /H/GIT/astranauta/5etools/5etools
```
Again, there shouldn't be any double-quotes, unless you have spaces in the path. |
45,205,278 | I am developing an list app with FirebaseListAdapter. I'm having problem with the getKey() value. I want to access the data under the listitem that is been clicked and display it in the textview from another activity. But ican't figure out what to do ?
Here's what my code looks like now
```
myList.setAdapter(myAdapter);
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Story st = (Story)parent.getItemAtPosition(position);
String stry = st.Story;
Toast.makeText(MainActivity.this, ""+stry,Toast.LENGTH_LONG).show();
Intent intent = new Intent(context, MyStoryActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Bundle bundle = new Bundle();
bundle.putString("Story", stry);
intent.putExtras(bundle);
context.startActivity(intent);
}
});
}
```
I'm getting the story value of the last added story when I clicked on any of the list item.
Here's the code of another activity where I want to display the value of the Story.
```
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.story_view);
database = FirebaseDatabase.getInstance();
ref = database.getReference("Stories");
ttl = (TextView) findViewById(R.id.title);
stry = (TextView) findViewById(R.id.story);
Bundle bundle = getIntent().getExtras();
stry1 = bundle.getString("Story");
ref.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Story ad = dataSnapshot.getValue(Story.class);
ttl.setText(ad.Title);
stry.setText(stry1);
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
```
This is what my database looks like
[](https://i.stack.imgur.com/cxBFn.jpg)
Here is the Story.class
```
public class Story {
public String Title;
public String Story;
// Default constructor required for calls to
// DataSnapshot.getValue(User.class)
public Story() {
}
public Story(String ttl, String stry) {
this.Title = ttl;
this.Story = stry;
}}
``` | 2017/07/20 | [
"https://Stackoverflow.com/questions/45205278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6040573/"
] | In my case the problem was with repositry name e.g I mistakenly added one extra `.` to the end of repositry name while creating repositry. The name was like CRUD-With-GraphQL..git. So the `.` before `.git` was the actual issue. I renamed my repositry, removed the extra `.` and the problem was resolved. | I think that the problem come from an optional component of GitExtensions called "Conemu".
It perhaps will fail at other moments...
Could you try to disable it using this documentation :
<https://git-extensions-documentation.readthedocs.io/en/latest/settings.html#advanced-general-use-console-emulator-for-console-output-in-command-dialogs> |
13,478,784 | I'm trying to copy an existing mongo database "test" on a remote server to the same remote server but it should get a different name "test2".
Mongodb is password protected on this server.
Is there any easy way to do this? ( I want to create a shell script out of this)
What I tried is to connect to mongo by using
```
mongo "IP"
```
Then I tried to use the db copy
```
db.copyDatabase( "test", "test2", "localhost", "<username>", "<password>");
```
But that didn't work out... even when I authenticate myself before doing the copy gives an error... any suggestions anybody how to do this the easiest?
Thanks in advance | 2012/11/20 | [
"https://Stackoverflow.com/questions/13478784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1312315/"
] | You may want to look into PECL extension. It may do what you need, docs on PHP.NET.
runkit\_function\_redefine
(PECL runkit >= 0.7.0) | I don't know this plugin very well but probably this is what you Need [Theming with Jigoshop](http://forum.jigoshop.com/kb/customize-jigoshop/theming-with-jigoshop)
Override some functions in php(also in common..) is never a good idea. If the plugin doesn't provide a way to hook into it's functionality is sometimes better to use an alternative plugin or rewrite the core code.. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.