qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
21,971,036 | I tried to export a settings.json as documented in the meteor.js documentation in order to connect my Meteor.js app with an external MongoHQ database :
```
{
"env": {
"MONGO_URL" : "mongodb://xxx:[email protected]:10037/xxx"
}
}
```
with the command :
```
mrt deploy myapp.meteor.com --settings settings.json
```
It doesn't even work, My app continue to connect the local database provided with the Meteor.app !
My MONGO\_URL env variable didnt changed.
Is there any solution to export my MONGO\_URL env variable to connect an external MongoDB database ?
I saw that is possible to change it while using heroku or modulus, what about the standard deploying meteor.com solution ? | 2014/02/23 | [
"https://Stackoverflow.com/questions/21971036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2917448/"
] | Create a `lib` folder under the `server` folder and write:
```
Meteor.settings = { //your settings };
```
According to documentation everything inside a folder named `lib` will be executed before anything, so this way we ensure that no code will be execute before this, preventing errors from accessing Metrics that don't exist.
If you're already using the `lib` folder you've to named right to run before anything else that might conflict, check the docs about it.
Enjoy. | Regarded to the Unoficial Meteor.js FAQ, thats not possible to do it easily, that might be tricky.
So i signed up for a modulus Account, with MongoHQ Database.
It works right now. |
21,971,036 | I tried to export a settings.json as documented in the meteor.js documentation in order to connect my Meteor.js app with an external MongoHQ database :
```
{
"env": {
"MONGO_URL" : "mongodb://xxx:[email protected]:10037/xxx"
}
}
```
with the command :
```
mrt deploy myapp.meteor.com --settings settings.json
```
It doesn't even work, My app continue to connect the local database provided with the Meteor.app !
My MONGO\_URL env variable didnt changed.
Is there any solution to export my MONGO\_URL env variable to connect an external MongoDB database ?
I saw that is possible to change it while using heroku or modulus, what about the standard deploying meteor.com solution ? | 2014/02/23 | [
"https://Stackoverflow.com/questions/21971036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2917448/"
] | The application-configuration package (built in meteor package) contains the code to set mongo\_url. See my answer here <https://stackoverflow.com/a/23485319/2391620> | having a settings.json file is not enough you need to run with
```
meteor --settings settings.json
```
which is you cant do with meteor.com deploy. |
21,971,036 | I tried to export a settings.json as documented in the meteor.js documentation in order to connect my Meteor.js app with an external MongoHQ database :
```
{
"env": {
"MONGO_URL" : "mongodb://xxx:[email protected]:10037/xxx"
}
}
```
with the command :
```
mrt deploy myapp.meteor.com --settings settings.json
```
It doesn't even work, My app continue to connect the local database provided with the Meteor.app !
My MONGO\_URL env variable didnt changed.
Is there any solution to export my MONGO\_URL env variable to connect an external MongoDB database ?
I saw that is possible to change it while using heroku or modulus, what about the standard deploying meteor.com solution ? | 2014/02/23 | [
"https://Stackoverflow.com/questions/21971036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2917448/"
] | Create a `lib` folder under the `server` folder and write:
```
Meteor.settings = { //your settings };
```
According to documentation everything inside a folder named `lib` will be executed before anything, so this way we ensure that no code will be execute before this, preventing errors from accessing Metrics that don't exist.
If you're already using the `lib` folder you've to named right to run before anything else that might conflict, check the docs about it.
Enjoy. | having a settings.json file is not enough you need to run with
```
meteor --settings settings.json
```
which is you cant do with meteor.com deploy. |
21,971,036 | I tried to export a settings.json as documented in the meteor.js documentation in order to connect my Meteor.js app with an external MongoHQ database :
```
{
"env": {
"MONGO_URL" : "mongodb://xxx:[email protected]:10037/xxx"
}
}
```
with the command :
```
mrt deploy myapp.meteor.com --settings settings.json
```
It doesn't even work, My app continue to connect the local database provided with the Meteor.app !
My MONGO\_URL env variable didnt changed.
Is there any solution to export my MONGO\_URL env variable to connect an external MongoDB database ?
I saw that is possible to change it while using heroku or modulus, what about the standard deploying meteor.com solution ? | 2014/02/23 | [
"https://Stackoverflow.com/questions/21971036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2917448/"
] | Create a `lib` folder under the `server` folder and write:
```
Meteor.settings = { //your settings };
```
According to documentation everything inside a folder named `lib` will be executed before anything, so this way we ensure that no code will be execute before this, preventing errors from accessing Metrics that don't exist.
If you're already using the `lib` folder you've to named right to run before anything else that might conflict, check the docs about it.
Enjoy. | The application-configuration package (built in meteor package) contains the code to set mongo\_url. See my answer here <https://stackoverflow.com/a/23485319/2391620> |
15,679,498 | When I'm using Kunena on my site I have problems on the navigation bar.
Whenever I'm in a Kunena "page" the navigation is not showing the FORUM as active. | 2013/03/28 | [
"https://Stackoverflow.com/questions/15679498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2112678/"
] | A work around will be to change the active with java script or jquery
add this script to your index template
```
<script>
var j = jQuery.noConflict();
var isForumActive = <?php if (strpos($_SERVER['REQUEST_URI'], "/forum") !== false){ echo "true"; } else echo "false";?>;
if(isForumActive){
j(".item120").addClass("active");
}
</script>
```
You will need to change the id (120) with your menu id and be sure that the alias is the correct.
you need jquery as well.... | I solved this problem by creating all Kunena menu items as sub-menu items of the Forum menu item in the main menu and using [split menus](http://docs.joomla.org/Split_menus). |
29,313,546 | Can anyone help me use a message box to display the random number and the square in two columns with a label for each?
```
const int NUM_ROWS = 10;
const int NUM_COLS = 2;
int[,] randint = new int [NUM_ROWS,NUM_COLS];
Random randNum = new Random();
for (int row = 0; row < randint.GetLength(0); row++)
{
randint[row,0] = randNum.Next(1,100);
randint[row,1] = randint[row,0]*randint[row,0];
Console.Write(string.Format("{0,5:d} {1,5:d}\n", randint[row,0], randint[row,1]));
``` | 2015/03/28 | [
"https://Stackoverflow.com/questions/29313546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4722898/"
] | You can do it like this.
```
MessageBox.Show(string.Format("{0,5:d} {1,5:d}\n", randint[row, 0], randint[row, 1]), "Message Box",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
```
If you place this line inside the `for` loop a message box will be displayed for every iteration. If you click Yes each time, a new message box with the old and new values will be displayed.
If you want to display the entire array then it will be something like this.
```
string data = "";
for (int row = 0; row < randint.GetLength(0); row++)
{
randint[row, 0] = randNum.Next(1, 100);
randint[row, 1] = randint[row, 0] * randint[row, 0];
data += string.Format("{0,5:d} {1,5:d}\n", randint[row, 0], randint[row, 1]);
}
MessageBox.Show(data, "Data", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
``` | Start you project in :
```
Windows Forms Application -> C#
```
You can use `MessageBox` to help you solve your display content. |
29,313,546 | Can anyone help me use a message box to display the random number and the square in two columns with a label for each?
```
const int NUM_ROWS = 10;
const int NUM_COLS = 2;
int[,] randint = new int [NUM_ROWS,NUM_COLS];
Random randNum = new Random();
for (int row = 0; row < randint.GetLength(0); row++)
{
randint[row,0] = randNum.Next(1,100);
randint[row,1] = randint[row,0]*randint[row,0];
Console.Write(string.Format("{0,5:d} {1,5:d}\n", randint[row,0], randint[row,1]));
``` | 2015/03/28 | [
"https://Stackoverflow.com/questions/29313546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4722898/"
] | I have achieved it by adding reference of System.Windows.Forms to my console application and got the result you desired. Here is my code:
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ConsoleApplication6
{
class Program
{
static void Main(string[] args)
{
const int NUM_ROWS = 10;
const int NUM_COLS = 2;
int[,] randint = new int[NUM_ROWS, NUM_COLS];
Random randNum = new Random();
for (int row = 0; row < randint.GetLength(0); row++)
{
randint[row, 0] = randNum.Next(1, 100);
randint[row, 1] = randint[row, 0] * randint[row, 0];
Console.Write(string.Format("{0,5:d} {1,5:d}\n", randint[row, 0], randint[row, 1]));
MessageBox.Show(string.Format("{0,5:d} {1,5:d}\n", randint[row, 0], randint[row, 1]));
Console.ReadKey();
}
}
}
}
```
**My output:**

Also though this is not asked but just in case to add reference to System.Windows.Form look right click on the references in your solution explorer and select .Net tab and then press ok after selecting the desired dll. Cheers!

 | You can do it like this.
```
MessageBox.Show(string.Format("{0,5:d} {1,5:d}\n", randint[row, 0], randint[row, 1]), "Message Box",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
```
If you place this line inside the `for` loop a message box will be displayed for every iteration. If you click Yes each time, a new message box with the old and new values will be displayed.
If you want to display the entire array then it will be something like this.
```
string data = "";
for (int row = 0; row < randint.GetLength(0); row++)
{
randint[row, 0] = randNum.Next(1, 100);
randint[row, 1] = randint[row, 0] * randint[row, 0];
data += string.Format("{0,5:d} {1,5:d}\n", randint[row, 0], randint[row, 1]);
}
MessageBox.Show(data, "Data", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
``` |
29,313,546 | Can anyone help me use a message box to display the random number and the square in two columns with a label for each?
```
const int NUM_ROWS = 10;
const int NUM_COLS = 2;
int[,] randint = new int [NUM_ROWS,NUM_COLS];
Random randNum = new Random();
for (int row = 0; row < randint.GetLength(0); row++)
{
randint[row,0] = randNum.Next(1,100);
randint[row,1] = randint[row,0]*randint[row,0];
Console.Write(string.Format("{0,5:d} {1,5:d}\n", randint[row,0], randint[row,1]));
``` | 2015/03/28 | [
"https://Stackoverflow.com/questions/29313546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4722898/"
] | I have achieved it by adding reference of System.Windows.Forms to my console application and got the result you desired. Here is my code:
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ConsoleApplication6
{
class Program
{
static void Main(string[] args)
{
const int NUM_ROWS = 10;
const int NUM_COLS = 2;
int[,] randint = new int[NUM_ROWS, NUM_COLS];
Random randNum = new Random();
for (int row = 0; row < randint.GetLength(0); row++)
{
randint[row, 0] = randNum.Next(1, 100);
randint[row, 1] = randint[row, 0] * randint[row, 0];
Console.Write(string.Format("{0,5:d} {1,5:d}\n", randint[row, 0], randint[row, 1]));
MessageBox.Show(string.Format("{0,5:d} {1,5:d}\n", randint[row, 0], randint[row, 1]));
Console.ReadKey();
}
}
}
}
```
**My output:**

Also though this is not asked but just in case to add reference to System.Windows.Form look right click on the references in your solution explorer and select .Net tab and then press ok after selecting the desired dll. Cheers!

 | Start you project in :
```
Windows Forms Application -> C#
```
You can use `MessageBox` to help you solve your display content. |
28,641,948 | This addresses "a specific programming problem" from [On-Topic](https://stackoverflow.com/help/on-topic)
I am working on an interview question from [Amazon Software Interview](http://www.glassdoor.com/Interview/Given-a-triangle-of-integers-find-the-path-of-the-largest-sum-without-skipping-QTN_623875.htm)
The question is " Given a triangle of integers, find the path of the largest sum without skipping. "
My question is how would you represent a triangle of integers?
I looked this up on [Triangle of Integers](https://stackoverflow.com/questions/25143410/how-to-print-a-triangle-of-integers-with-number-of-lines-specified-by-the-user) and saw that a triangle of integers looked something like
```
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
```
What is the best way(data structure) to represent something like this? My idea was having something like
```
int[] r1 = {1};
int[] r2 = {2, 3};
int[] r3 = {4, 5, 6};
int[] r4 = {7, 8, 9, 10};
int[] r5 = {11, 12, 13, 14, 15};
```
Is this the best way to represent this triangle integer structure? I thought about using a 2 dimensional matrix structure but those have to have arrays of the same size. | 2015/02/21 | [
"https://Stackoverflow.com/questions/28641948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3761297/"
] | You should put them in linear memory and access them as:
```
int triangular(int row){
return row * (row + 1) / 2 + 1;
}
int[] r = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
for(int i=0; i<n_rows; i++){
for(int j=0; j<=i; j++){
System.out.print(r[triangular(i)+j]+" ");
}System.out.println("");
}
row, column
if row>column:
index=triangular(row)+column
```
Since it's a predictable structure there's an expression for the offset of the beginning of each row. This will be the most efficient way. | You don't need to represent it at all! The starting number of row `r` (starting at 0) is given by the expression:
```
r * (r + 1) / 2 + 1
``` |
28,641,948 | This addresses "a specific programming problem" from [On-Topic](https://stackoverflow.com/help/on-topic)
I am working on an interview question from [Amazon Software Interview](http://www.glassdoor.com/Interview/Given-a-triangle-of-integers-find-the-path-of-the-largest-sum-without-skipping-QTN_623875.htm)
The question is " Given a triangle of integers, find the path of the largest sum without skipping. "
My question is how would you represent a triangle of integers?
I looked this up on [Triangle of Integers](https://stackoverflow.com/questions/25143410/how-to-print-a-triangle-of-integers-with-number-of-lines-specified-by-the-user) and saw that a triangle of integers looked something like
```
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
```
What is the best way(data structure) to represent something like this? My idea was having something like
```
int[] r1 = {1};
int[] r2 = {2, 3};
int[] r3 = {4, 5, 6};
int[] r4 = {7, 8, 9, 10};
int[] r5 = {11, 12, 13, 14, 15};
```
Is this the best way to represent this triangle integer structure? I thought about using a 2 dimensional matrix structure but those have to have arrays of the same size. | 2015/02/21 | [
"https://Stackoverflow.com/questions/28641948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3761297/"
] | You should put them in linear memory and access them as:
```
int triangular(int row){
return row * (row + 1) / 2 + 1;
}
int[] r = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
for(int i=0; i<n_rows; i++){
for(int j=0; j<=i; j++){
System.out.print(r[triangular(i)+j]+" ");
}System.out.println("");
}
row, column
if row>column:
index=triangular(row)+column
```
Since it's a predictable structure there's an expression for the offset of the beginning of each row. This will be the most efficient way. | >
> I thought about using a 2 dimensional matrix structure but those have to have arrays of the same size.
>
>
>
Not correct.
In Java you can use arrays to represent non-rectangular data structures; e.g.
```
int[][] triangle = {{1},
{2, 3},
{4, 5, 6},
{7, 8, 9, 10},
{11, 12, 13, 14, 15}};
```
It is an option, though not necessarily the most convenient option. |
28,641,948 | This addresses "a specific programming problem" from [On-Topic](https://stackoverflow.com/help/on-topic)
I am working on an interview question from [Amazon Software Interview](http://www.glassdoor.com/Interview/Given-a-triangle-of-integers-find-the-path-of-the-largest-sum-without-skipping-QTN_623875.htm)
The question is " Given a triangle of integers, find the path of the largest sum without skipping. "
My question is how would you represent a triangle of integers?
I looked this up on [Triangle of Integers](https://stackoverflow.com/questions/25143410/how-to-print-a-triangle-of-integers-with-number-of-lines-specified-by-the-user) and saw that a triangle of integers looked something like
```
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
```
What is the best way(data structure) to represent something like this? My idea was having something like
```
int[] r1 = {1};
int[] r2 = {2, 3};
int[] r3 = {4, 5, 6};
int[] r4 = {7, 8, 9, 10};
int[] r5 = {11, 12, 13, 14, 15};
```
Is this the best way to represent this triangle integer structure? I thought about using a 2 dimensional matrix structure but those have to have arrays of the same size. | 2015/02/21 | [
"https://Stackoverflow.com/questions/28641948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3761297/"
] | You should put them in linear memory and access them as:
```
int triangular(int row){
return row * (row + 1) / 2 + 1;
}
int[] r = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
for(int i=0; i<n_rows; i++){
for(int j=0; j<=i; j++){
System.out.print(r[triangular(i)+j]+" ");
}System.out.println("");
}
row, column
if row>column:
index=triangular(row)+column
```
Since it's a predictable structure there's an expression for the offset of the beginning of each row. This will be the most efficient way. | I'd use a 2D array with guard-bands. In the example below, the 0's represent invalid entries in the array. The top and bottom rows, as well as the leftmost and rightmost columns are the guard-bands. The advantage is that your pathfinding algorithm can wander around the array without having to constantly check for out-of-bounds array indices.
```
int[][] array =
{
{ 0, 0, 0, 0, 0, 0, 0 },
{ 0, 1, 0, 0, 0, 0, 0 },
{ 0, 2, 3, 0, 0, 0, 0 },
{ 0, 4, 5, 6, 0, 0, 0 },
{ 0, 7, 8, 9,10, 0, 0 },
{ 0,11,12,13,14,15, 0 },
{ 0, 0, 0, 0, 0, 0, 0 }
};
``` |
28,641,948 | This addresses "a specific programming problem" from [On-Topic](https://stackoverflow.com/help/on-topic)
I am working on an interview question from [Amazon Software Interview](http://www.glassdoor.com/Interview/Given-a-triangle-of-integers-find-the-path-of-the-largest-sum-without-skipping-QTN_623875.htm)
The question is " Given a triangle of integers, find the path of the largest sum without skipping. "
My question is how would you represent a triangle of integers?
I looked this up on [Triangle of Integers](https://stackoverflow.com/questions/25143410/how-to-print-a-triangle-of-integers-with-number-of-lines-specified-by-the-user) and saw that a triangle of integers looked something like
```
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
```
What is the best way(data structure) to represent something like this? My idea was having something like
```
int[] r1 = {1};
int[] r2 = {2, 3};
int[] r3 = {4, 5, 6};
int[] r4 = {7, 8, 9, 10};
int[] r5 = {11, 12, 13, 14, 15};
```
Is this the best way to represent this triangle integer structure? I thought about using a 2 dimensional matrix structure but those have to have arrays of the same size. | 2015/02/21 | [
"https://Stackoverflow.com/questions/28641948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3761297/"
] | >
> I thought about using a 2 dimensional matrix structure but those have to have arrays of the same size.
>
>
>
Not correct.
In Java you can use arrays to represent non-rectangular data structures; e.g.
```
int[][] triangle = {{1},
{2, 3},
{4, 5, 6},
{7, 8, 9, 10},
{11, 12, 13, 14, 15}};
```
It is an option, though not necessarily the most convenient option. | You don't need to represent it at all! The starting number of row `r` (starting at 0) is given by the expression:
```
r * (r + 1) / 2 + 1
``` |
28,641,948 | This addresses "a specific programming problem" from [On-Topic](https://stackoverflow.com/help/on-topic)
I am working on an interview question from [Amazon Software Interview](http://www.glassdoor.com/Interview/Given-a-triangle-of-integers-find-the-path-of-the-largest-sum-without-skipping-QTN_623875.htm)
The question is " Given a triangle of integers, find the path of the largest sum without skipping. "
My question is how would you represent a triangle of integers?
I looked this up on [Triangle of Integers](https://stackoverflow.com/questions/25143410/how-to-print-a-triangle-of-integers-with-number-of-lines-specified-by-the-user) and saw that a triangle of integers looked something like
```
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
```
What is the best way(data structure) to represent something like this? My idea was having something like
```
int[] r1 = {1};
int[] r2 = {2, 3};
int[] r3 = {4, 5, 6};
int[] r4 = {7, 8, 9, 10};
int[] r5 = {11, 12, 13, 14, 15};
```
Is this the best way to represent this triangle integer structure? I thought about using a 2 dimensional matrix structure but those have to have arrays of the same size. | 2015/02/21 | [
"https://Stackoverflow.com/questions/28641948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3761297/"
] | I'd use a 2D array with guard-bands. In the example below, the 0's represent invalid entries in the array. The top and bottom rows, as well as the leftmost and rightmost columns are the guard-bands. The advantage is that your pathfinding algorithm can wander around the array without having to constantly check for out-of-bounds array indices.
```
int[][] array =
{
{ 0, 0, 0, 0, 0, 0, 0 },
{ 0, 1, 0, 0, 0, 0, 0 },
{ 0, 2, 3, 0, 0, 0, 0 },
{ 0, 4, 5, 6, 0, 0, 0 },
{ 0, 7, 8, 9,10, 0, 0 },
{ 0,11,12,13,14,15, 0 },
{ 0, 0, 0, 0, 0, 0, 0 }
};
``` | You don't need to represent it at all! The starting number of row `r` (starting at 0) is given by the expression:
```
r * (r + 1) / 2 + 1
``` |
28,641,948 | This addresses "a specific programming problem" from [On-Topic](https://stackoverflow.com/help/on-topic)
I am working on an interview question from [Amazon Software Interview](http://www.glassdoor.com/Interview/Given-a-triangle-of-integers-find-the-path-of-the-largest-sum-without-skipping-QTN_623875.htm)
The question is " Given a triangle of integers, find the path of the largest sum without skipping. "
My question is how would you represent a triangle of integers?
I looked this up on [Triangle of Integers](https://stackoverflow.com/questions/25143410/how-to-print-a-triangle-of-integers-with-number-of-lines-specified-by-the-user) and saw that a triangle of integers looked something like
```
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
```
What is the best way(data structure) to represent something like this? My idea was having something like
```
int[] r1 = {1};
int[] r2 = {2, 3};
int[] r3 = {4, 5, 6};
int[] r4 = {7, 8, 9, 10};
int[] r5 = {11, 12, 13, 14, 15};
```
Is this the best way to represent this triangle integer structure? I thought about using a 2 dimensional matrix structure but those have to have arrays of the same size. | 2015/02/21 | [
"https://Stackoverflow.com/questions/28641948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3761297/"
] | >
> I thought about using a 2 dimensional matrix structure but those have to have arrays of the same size.
>
>
>
Not correct.
In Java you can use arrays to represent non-rectangular data structures; e.g.
```
int[][] triangle = {{1},
{2, 3},
{4, 5, 6},
{7, 8, 9, 10},
{11, 12, 13, 14, 15}};
```
It is an option, though not necessarily the most convenient option. | I'd use a 2D array with guard-bands. In the example below, the 0's represent invalid entries in the array. The top and bottom rows, as well as the leftmost and rightmost columns are the guard-bands. The advantage is that your pathfinding algorithm can wander around the array without having to constantly check for out-of-bounds array indices.
```
int[][] array =
{
{ 0, 0, 0, 0, 0, 0, 0 },
{ 0, 1, 0, 0, 0, 0, 0 },
{ 0, 2, 3, 0, 0, 0, 0 },
{ 0, 4, 5, 6, 0, 0, 0 },
{ 0, 7, 8, 9,10, 0, 0 },
{ 0,11,12,13,14,15, 0 },
{ 0, 0, 0, 0, 0, 0, 0 }
};
``` |
14,029,038 | I am developing a registration system that lists events and the users will be able to register in these events. Each event has a specific number of seats. The problem that I am facing now is even when the number of registration reaches the number of seats, the event is still avaiable and I cannot stop the booking process by disabling booking button.
For your information, I have the following database design:
```
Event Table: ID, Title, NumberOfSeats
BookingDetails Table: BookingID, EventID, Username
User Table: Username, Name
```
The events will be listed in a GridView control and there is LinkButton inside the GridView for booking in the event. I am using a ModalPopUp Extender control and this is why I am using a LinkButton as shown in the ASP.NET code below. In the code-behind, inside the GrivView\_RowDataBound, I compared between the number of seats and the number of bookings for each event. If the number of bookings greater than or equal to the number of seats. Booking button should be disabled. I wrote the code but I don't know why it is not working with me and why I am getting the following error:
***Unable to cast object of type 'System.Web.UI.WebControls.GridView' to type 'System.Web.UI.WebControls.LinkButton'.***
***ASP.NET code:***
```
<asp:GridView ID="ListOfAvailableEvents_GrivView" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" CellPadding="4" DataSourceID="SqlDataSource1" ForeColor="#333333"
GridLines="None" AllowPaging="True" PageSize="10"
onrowdatabound="ListOfAvailableEvents_GrivView_RowDataBound">
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" CssClass="generaltext" />
<Columns>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:LinkButton ID="lnkTitle" runat="server" CssClass="button" Text="Book →" OnClick="lnkTitle_Click"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
<asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
<asp:BoundField DataField="Location" HeaderText="Location" SortExpression="Location" />
<asp:BoundField DataField="StartDateTime" HeaderText="Start Date & Time" SortExpression="StartDateTime" />
<asp:BoundField DataField="EndDateTime" HeaderText="End Date & Time" SortExpression="EndDateTime" />
</Columns>
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle Font-Bold="True" CssClass="complete" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<EmptyDataTemplate><h2>No Events Available</h2></EmptyDataTemplate>
</asp:GridView>
```
***Code-Behind (C#) code:***
```
protected void ListOfAvailableEvents_GrivView_RowDataBound(object sender, GridViewRowEventArgs e)
{
int numberOfBookings = 0;
int numberOfAvailableSeats = 0;
string connString = "..........."
string selectCommand = @"SELECT COUNT(*) AS UserBookingsCount, dbo.Events.NumberOfSeats
FROM dbo.BookingDetails INNER JOIN
dbo.Events ON dbo.BookingDetails.EventID = dbo.Events.ID
GROUP BY dbo.Events.NumberOfSeats";
using (SqlConnection conn = new SqlConnection(connString))
{
//Open DB Connection
conn.Open();
using (SqlCommand cmd = new SqlCommand(selectCommand, conn))
{
SqlDataReader reader = cmd.ExecuteReader();
if (reader != null)
if (reader.Read())
{
numberOfBookings = Int32.Parse(reader["UserBookingsCount"].ToString());
numberOfAvailableSeats = Int32.Parse(reader["NumberOfSeats"].ToString());
}
}
//Close the connection
conn.Close();
}
if (numberOfBookings >= numberOfAvailableSeats)
{
LinkButton bookButton = (LinkButton)(sender);
bookButton.Enabled = false;
}
}
```
**So could you please tell me how to fix this problem?**
**UPDATE:**
The GridView lists many different events. Let us take one of them. If event A has 3 available seats and the number of bookings reaches 3, the 'Book' button should be disabled only for this event not for all of them. So the button will be disabled for this event when the number of bookings reaches the number of available seats. | 2012/12/25 | [
"https://Stackoverflow.com/questions/14029038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1897016/"
] | Try :
```
LinkButtton lbtn = new LinkButtton();
lbtn = (LinkButton)e.Row.FindControl("ButtonId");
```
Then use `lbtn` for further operations.
Thanks | The RowDataBound event is for the GridView so the sender parameter cannot be cast into a LinkButton.
Modify you code to include the following.
```
if(numberOfBookings >= numberOfAvailableSeats)
{
if (e.Row.Cells[0].HasControls())
{
var button = e.Row.Cells[0].Controls[1] as LinkButton;
button.Enabled = false;
}
}
```
I worry about how you are approaching this though.
The RowDataBound event triggers for EVERY row in the datasource it is bound to and you are doing a database query each time.
You could try to include numberOfBookings and numberOfAvailableSeats in your initial query and those will be available to you and you can check them each time (per row) without having to go to the database each time. |
14,029,038 | I am developing a registration system that lists events and the users will be able to register in these events. Each event has a specific number of seats. The problem that I am facing now is even when the number of registration reaches the number of seats, the event is still avaiable and I cannot stop the booking process by disabling booking button.
For your information, I have the following database design:
```
Event Table: ID, Title, NumberOfSeats
BookingDetails Table: BookingID, EventID, Username
User Table: Username, Name
```
The events will be listed in a GridView control and there is LinkButton inside the GridView for booking in the event. I am using a ModalPopUp Extender control and this is why I am using a LinkButton as shown in the ASP.NET code below. In the code-behind, inside the GrivView\_RowDataBound, I compared between the number of seats and the number of bookings for each event. If the number of bookings greater than or equal to the number of seats. Booking button should be disabled. I wrote the code but I don't know why it is not working with me and why I am getting the following error:
***Unable to cast object of type 'System.Web.UI.WebControls.GridView' to type 'System.Web.UI.WebControls.LinkButton'.***
***ASP.NET code:***
```
<asp:GridView ID="ListOfAvailableEvents_GrivView" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" CellPadding="4" DataSourceID="SqlDataSource1" ForeColor="#333333"
GridLines="None" AllowPaging="True" PageSize="10"
onrowdatabound="ListOfAvailableEvents_GrivView_RowDataBound">
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" CssClass="generaltext" />
<Columns>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:LinkButton ID="lnkTitle" runat="server" CssClass="button" Text="Book →" OnClick="lnkTitle_Click"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
<asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
<asp:BoundField DataField="Location" HeaderText="Location" SortExpression="Location" />
<asp:BoundField DataField="StartDateTime" HeaderText="Start Date & Time" SortExpression="StartDateTime" />
<asp:BoundField DataField="EndDateTime" HeaderText="End Date & Time" SortExpression="EndDateTime" />
</Columns>
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle Font-Bold="True" CssClass="complete" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<EmptyDataTemplate><h2>No Events Available</h2></EmptyDataTemplate>
</asp:GridView>
```
***Code-Behind (C#) code:***
```
protected void ListOfAvailableEvents_GrivView_RowDataBound(object sender, GridViewRowEventArgs e)
{
int numberOfBookings = 0;
int numberOfAvailableSeats = 0;
string connString = "..........."
string selectCommand = @"SELECT COUNT(*) AS UserBookingsCount, dbo.Events.NumberOfSeats
FROM dbo.BookingDetails INNER JOIN
dbo.Events ON dbo.BookingDetails.EventID = dbo.Events.ID
GROUP BY dbo.Events.NumberOfSeats";
using (SqlConnection conn = new SqlConnection(connString))
{
//Open DB Connection
conn.Open();
using (SqlCommand cmd = new SqlCommand(selectCommand, conn))
{
SqlDataReader reader = cmd.ExecuteReader();
if (reader != null)
if (reader.Read())
{
numberOfBookings = Int32.Parse(reader["UserBookingsCount"].ToString());
numberOfAvailableSeats = Int32.Parse(reader["NumberOfSeats"].ToString());
}
}
//Close the connection
conn.Close();
}
if (numberOfBookings >= numberOfAvailableSeats)
{
LinkButton bookButton = (LinkButton)(sender);
bookButton.Enabled = false;
}
}
```
**So could you please tell me how to fix this problem?**
**UPDATE:**
The GridView lists many different events. Let us take one of them. If event A has 3 available seats and the number of bookings reaches 3, the 'Book' button should be disabled only for this event not for all of them. So the button will be disabled for this event when the number of bookings reaches the number of available seats. | 2012/12/25 | [
"https://Stackoverflow.com/questions/14029038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1897016/"
] | Please use below code to hide the LinkButton, i.e. `lnkTitle`.
The code is as follows:
```
protected void ListOfAvailableEvents_GrivView_RowDataBound(object sender, GridViewRowEventArgs e)
{
int numberOfBookings = 0;
int numberOfAvailableSeats = 0;
string connString = "Data Source=appServer\\sqlexpress;Initial Catalog=EventRegMgnSysDB;Integrated Security=True;";
string selectCommand = @"SELECT COUNT(*) AS UserBookingsCount, dbo.Events.NumberOfSeats
FROM dbo.BookingDetails INNER JOIN
dbo.Events ON dbo.BookingDetails.EventID = dbo.Events.ID
GROUP BY dbo.Events.NumberOfSeats";
using (SqlConnection conn = new SqlConnection(connString))
{
//Open DB Connection
conn.Open();
using (SqlCommand cmd = new SqlCommand(selectCommand, conn))
{
SqlDataReader reader = cmd.ExecuteReader();
if (reader != null)
if (reader.Read())
{
numberOfBookings = Int32.Parse(reader["UserBookingsCount"].ToString());
numberOfAvailableSeats = Int32.Parse(reader["NumberOfSeats"].ToString());
}
}
//Close the connection
conn.Close();
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton lnkTitle = (LinkButton )e.Row.FindControl("lnkTitle");
if (numberOfBookings >= numberOfAvailableSeats)
{
lnkTitle.Visible = false;
}
else
{
lnkTitle.Visible = true;
}
}
}
```
Please mark it if you will get your answer. | The RowDataBound event is for the GridView so the sender parameter cannot be cast into a LinkButton.
Modify you code to include the following.
```
if(numberOfBookings >= numberOfAvailableSeats)
{
if (e.Row.Cells[0].HasControls())
{
var button = e.Row.Cells[0].Controls[1] as LinkButton;
button.Enabled = false;
}
}
```
I worry about how you are approaching this though.
The RowDataBound event triggers for EVERY row in the datasource it is bound to and you are doing a database query each time.
You could try to include numberOfBookings and numberOfAvailableSeats in your initial query and those will be available to you and you can check them each time (per row) without having to go to the database each time. |
8,688,185 | How I can find in XPath 1.0 all rows with empty `col name="POW"`?
```
<row>
<col name="WOJ">02</col>
<col name="POW"/>
<col name="GMI"/>
<col name="RODZ"/>
<col name="NAZWA">DOLNOŚLĄSKIE</col>
<col name="NAZDOD">województwo</col>
<col name="STAN_NA">2011-01-01</col>
</row>
```
I tried many solutions. Few times in Firefox extension XPath Checker selection was ok, but `lxml.xpath()` says that expression is invalid or just returns no rows.
My Python code:
```
from lxml import html
f = open('TERC.xml', 'r')
page = html.fromstring(f.read())
for r in page.xpath("//row[col[@name = 'POW' and not(text())]]"):
print r.text_content()
print "-------------------------"
``` | 2011/12/31 | [
"https://Stackoverflow.com/questions/8688185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/499768/"
] | ```
//row[col[@name='POW' and not(normalize-space())]]
```
To ensure that the POW column also doesn't have any child elements(even if they don't contain any text), then add an additional predicate filter:
```
//row[col[@name='POW' and not(normalize-space()) and not(*)]]
``` | Use this:
```
//row[col[@name = 'POW' and not(text())]]
``` |
8,688,185 | How I can find in XPath 1.0 all rows with empty `col name="POW"`?
```
<row>
<col name="WOJ">02</col>
<col name="POW"/>
<col name="GMI"/>
<col name="RODZ"/>
<col name="NAZWA">DOLNOŚLĄSKIE</col>
<col name="NAZDOD">województwo</col>
<col name="STAN_NA">2011-01-01</col>
</row>
```
I tried many solutions. Few times in Firefox extension XPath Checker selection was ok, but `lxml.xpath()` says that expression is invalid or just returns no rows.
My Python code:
```
from lxml import html
f = open('TERC.xml', 'r')
page = html.fromstring(f.read())
for r in page.xpath("//row[col[@name = 'POW' and not(text())]]"):
print r.text_content()
print "-------------------------"
``` | 2011/12/31 | [
"https://Stackoverflow.com/questions/8688185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/499768/"
] | >
> How I can find in XPath 1.0 all rows with empty `col name="POW"`?
>
>
>
There are many possible definitions of "empty" and for each one of them there is a different XPath expression selecting "empty" elements.
A reasonable definition for an empty element is: an element that has no children elements and no text-node children, or an element that has a single text-node child, whose string value contains only whitespace characters.
**This XPath expression**:
```
//row[col[@name = 'POW']
[not(*)]
[not(normalize-space())]
]
```
selects all `row` elements in the XML document, that have a `col` child, that has an attribute `name` with string value `"POW"` and that has no children - elements and whose string value consists either entirely of whitespace characters, or is the empty string.
**In case by "empty" you understand "having no children at all"**, which means no children elements and no children PI nodes and no children comment nodes, then use:
```
//row[col[@name = 'POW']
[not(node())]
]
``` | Use this:
```
//row[col[@name = 'POW' and not(text())]]
``` |
8,688,185 | How I can find in XPath 1.0 all rows with empty `col name="POW"`?
```
<row>
<col name="WOJ">02</col>
<col name="POW"/>
<col name="GMI"/>
<col name="RODZ"/>
<col name="NAZWA">DOLNOŚLĄSKIE</col>
<col name="NAZDOD">województwo</col>
<col name="STAN_NA">2011-01-01</col>
</row>
```
I tried many solutions. Few times in Firefox extension XPath Checker selection was ok, but `lxml.xpath()` says that expression is invalid or just returns no rows.
My Python code:
```
from lxml import html
f = open('TERC.xml', 'r')
page = html.fromstring(f.read())
for r in page.xpath("//row[col[@name = 'POW' and not(text())]]"):
print r.text_content()
print "-------------------------"
``` | 2011/12/31 | [
"https://Stackoverflow.com/questions/8688185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/499768/"
] | >
> How I can find in XPath 1.0 all rows with empty `col name="POW"`?
>
>
>
There are many possible definitions of "empty" and for each one of them there is a different XPath expression selecting "empty" elements.
A reasonable definition for an empty element is: an element that has no children elements and no text-node children, or an element that has a single text-node child, whose string value contains only whitespace characters.
**This XPath expression**:
```
//row[col[@name = 'POW']
[not(*)]
[not(normalize-space())]
]
```
selects all `row` elements in the XML document, that have a `col` child, that has an attribute `name` with string value `"POW"` and that has no children - elements and whose string value consists either entirely of whitespace characters, or is the empty string.
**In case by "empty" you understand "having no children at all"**, which means no children elements and no children PI nodes and no children comment nodes, then use:
```
//row[col[@name = 'POW']
[not(node())]
]
``` | ```
//row[col[@name='POW' and not(normalize-space())]]
```
To ensure that the POW column also doesn't have any child elements(even if they don't contain any text), then add an additional predicate filter:
```
//row[col[@name='POW' and not(normalize-space()) and not(*)]]
``` |
52,269,829 | I am having trouble finding a way to authenticate an user.
When you start the Node JS Server manually this worked fine (and yeah its ugly code):
```
if (data.URL.includes("https://share.url.com")) {
await page.type('#userNameInput', 'user');
await page.type('#passwordInput', 'pass');
await page.click('#submitButton');
await page.waitForNavigation({waitUntil: 'load'});
await page.waitFor(6000);
}
```
Sharepoint didnt know my user data so they navigated me to a login page where I could fill in the Login Information and then move to my requested site. But in the meantime there were 2 changed made: 1. This Login Page doesnt exist anymore, if the login information isnt found I just get linked to a page where it says "Sorry you don't have access to this page". The 2nd problem or change is that the node server is started by a service.
At the end I just need to somehow access the page and then take a screenshot of it. But the auth is making me trouble. I now need a workaround to this problem, but I cant think about other solutions.
**Puppeteer authenticate:**
```
await page.authenticate({
username: "user",
password: "pass"
});
```
This doesnt work or using this with an auth header doesnt work either.
**Saving user cred. in browser (chrom(ium)):**
I tried to save the user cred. for the page inside the browser, but this didnt have any affect.
**URL Auth:**
I tried to auth inside the URL like (<https://user:[email protected]/bla/site.aspx>) but it doesnt work.
I am out of ideas how to approach this problem, have you got any suggestions how I could try this in an other way or did you see errors in my code or in my thoughts?
Thanks go to Bill Gates | 2018/09/11 | [
"https://Stackoverflow.com/questions/52269829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7156350/"
] | About
>
> Saving user cred. in browser (chrom(ium)):
>
>
>
I had similar situation - I wanted to do screenshot from facebook when I'm logged in. To achieve it I did steps like:
1) Created temp user data dir
```
mkdir /tmp/puppeteer_test
```
2) Run Chrome with these arguments
```
/usr/bin/google-chrome --user-data-dir=/tmp/puppeteer_test --password-store=basic
```
3) Go to facebook.com, log into and then close the browser
4) Run puppeteer with appropriate arguments:
```
const browser = await puppeteer.launch({
headless: false,
executablePath: '/usr/bin/google-chrome',
args: ['--user-data-dir=/tmp/puppeteer_test']
});
const page = await browser.newPage();
await page.goto('https://facebook.com', { waitUntil: 'networkidle2' });
await page.screenshot({path: 'facebook.png'});
await browser.close();
``` | I am doing following for SharePoint
```
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setViewport({width: 1920, height: 1080});
// Open SharePoint page
console.log("Opening page");
await page.goto('https://mytenant.sharepoint.com/sites/mysite');
await page.waitForNavigation({ waitUntil: 'networkidle0' });
console.log("Page opened");
// Input username
console.log("Inputting username");
await page.type('#i0116', '[email protected]');
await page.click('#idSIButton9');
await page.waitForNavigation({ waitUntil: 'networkidle0' });
console.log("Username input completed");
// Input password
console.log("Inputting password");
await page.type('#i0118', 'password123');
await page.click('#idSIButton9');
await page.waitForNavigation({ waitUntil: 'networkidle0' });
console.log("Password input completed");
// Stay signed in
console.log("staying signed in");
await page.keyboard.press('Enter');
await page.waitForNavigation({ waitUntil: 'networkidle0' });
console.log("staying signed in completed");
// Wait, because rendering is picky
await page.waitFor(6000);
``` |
33,581,329 | How I can pass a Map parameter as a GET param in url to Spring REST controller ? | 2015/11/07 | [
"https://Stackoverflow.com/questions/33581329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1219755/"
] | There are different ways (*but a simple `@RequestParam('myMap')Map<String,String>` does not work - maybe not true anymore!*)
The (IMHO) easiest solution is to use a command object then you could use `[key]` in the url to specifiy the map key:
@Controller
```
@RequestMapping("/demo")
public class DemoController {
public static class Command{
private Map<String, String> myMap;
public Map<String, String> getMyMap() {return myMap;}
public void setMyMap(Map<String, String> myMap) {this.myMap = myMap;}
@Override
public String toString() {
return "Command [myMap=" + myMap + "]";
}
}
@RequestMapping(method=RequestMethod.GET)
public ModelAndView helloWorld(Command command) {
System.out.println(command);
return null;
}
}
```
* Request: http://localhost:8080/demo?myMap[line1]=hello&myMap[line2]=world
* Output: `Command [myMap={line1=hello, line2=world}]`
*Tested with Spring Boot 1.2.7* | It’s possible to bind all request parameters in a Map just by adding a Map object after the annotation:
```
@RequestMapping("/demo")
public String example(@RequestParam Map<String, String> map){
String apple = map.get("APPLE");//apple
String banana = map.get("BANANA");//banana
return apple + banana;
}
```
Request
>
> /demo?APPLE=apple&BANANA=banana
>
>
>
Source -- <https://reversecoding.net/spring-mvc-requestparam-binding-request-parameters/> |
12,124,297 | I need a scheduler (for one time only actions) for a site I'm coding (in php), and I had two ideas:
1- Run a php script with crontab and verify against a database of scheduled actions and execute ones that are older than current time.
2- Schedule various tasks with the "at" command.
The second option seems much better and simpler, so that's what I'm trying to do. However, I haven't found a way to tell "at" to run a command using the PHP interpreter, and so far I've been creating a .sh script, which contains a single command, which is to run a file through the php interpreter. That is far from the optimal setting, and I wish I could just execute the php code directly through "at", something like:
```
at -e php -f /path/to/phpscript time
```
Is it possible? I haven't found anything about using environments other than bash in either the man or online. | 2012/08/25 | [
"https://Stackoverflow.com/questions/12124297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1445420/"
] | You can prepend `phpscript` with a `#!/usr/bin/php` (or wherever your php script is stored) and make `/path/to/phpscript` executable. This is exactly what the `#!` syntax is for.
Just so it's clear, your `phpscript` would look like this:
```
#!/usr/bin/php
...your code goes here
``` | The command you specify to `at` is executed by `/bin/sh`, but sh can invoke any command, executed directly or by any specified interpreter.
The following works on my Ubuntu 12.04 system with the bash shell:
```
$ cat hello.php
#!/usr/bin/php
<?php
echo "Hello, PHP\n";
?>
$ echo "$PWD/hello.php > hello.php.out" | at 16:11
warning: commands will be executed using /bin/sh
job 4 at Sat Aug 25 16:11:00 2012
$ date
Sat Aug 25 16:11:05 PDT 2012
$ cat hello.php.out
Hello, PHP
$
```
In some cases, you'll have to do some extra work to set environment variables correctly (it's not necessary for this simple case). Quoting the man page:
>
> For both **at** and **batch**, commands are read from standard input or the
> file specified with the **-f** option and executed. The working directory,
> the environment (except for the variables **BASH\_VERSINFO**, **DISPLAY**,
> **EUID**, **GROUPS**, **SHELLOPTS**, **TERM**, **UID**, and **\_**) and the umask are retained
> from the time of invocation.
>
>
> As **at** is currently implemented as a setuid program, other environment
> variables (e.g. **LD\_LIBRARY\_PATH** or **LD\_PRELOAD**) are also not exported.
> This may change in the future. As a workaround, set these variables
> explicitly in your job.
>
>
> |
55,690,637 | I have some data files with around 10k records; each record containing a value plus the standard deviation for it.
I'm plotting the standard deviation as a slightly transparent `filledcurve`. However, since there were some weird artifacts with painting so many points, I've resorted to using the `every` command to plot every 99 points.
```
'$1' using 1:(\$3-\$5):(\$3+\$5) every 99::0 with filledcurves ls $COUNTER notitle
```
This works perfectly; however my problem is that depending on how many exact records I have in the file, the `every` command may skip the last entries, which ends up with the colored standard deviation area ending before its respective line.
[](https://i.stack.imgur.com/54OJB.png)
Is there any way to include the last record to the every command/filled plot so that the colored area extends to where it needs to?
EDIT: The effect I'm trying to avoid is this:
[](https://i.stack.imgur.com/l8HTh.png)
I can't seem to really reproduce it atm as I'm working with new data, but I'm sure that picking points every once in a while avoids it. | 2019/04/15 | [
"https://Stackoverflow.com/questions/55690637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1356926/"
] | [amended to show full treatment of NaN value. Demo'ed with a real data file]
Instead of `every`, you can construct a filter function for the `using` specifier.
```
set xrange [100:600]
xmax = 600
filter(x) = (int(column(0))%9 == 0 || x == xmax) ? 1 : 0
set datafile missing NaN
plot 'silver.dat' using (filter($1)?$1:NaN) : ($2-$3) : ($2+$3) with filledcurves, \
'' using 1:2 with lines
```
[](https://i.stack.imgur.com/2JKiI.png) | You mentioned the iridescent patterns when plotting about 10k datapoints with transparent? Although different terminals look different, I can't observe this behaviour with gnuplot 5.2.6 under Win7 or we are talking about different things. Maybe, your data or terminal or OS is special?
**Test code:**
```
### transparent error range
reset session
# set term wxt size 600,600
# set term qt size 600,600
set term pngcairo size 600,600
set output "ErrorRangePNGCairo.png"
set key left
GenerateData = 'set print $Data; \
do for [i=1:Max] { print sprintf("%g\t%g\t%.3f",i,i+rand(0)*Max*0.1,rand(0)*Max*0.1+Max*0.05) }; \
set print'
PlotData = 'plot \
$Data u 1:($2+$3):($2-$3) w filledcurves lc rgb "#aaff0000" t "Error",\
"" u 1:2 w l lc rgb "red" t "Data"'
set multiplot layout 3,1
Max = 100
@GenerateData
@PlotData
Max = 1000
@GenerateData
@PlotData
Max = 10000
@GenerateData
@PlotData
unset multiplot
set output
### end of code
```
**wxt terminal:**
[](https://i.stack.imgur.com/R9WvL.png)
**qt terminal:**
[](https://i.stack.imgur.com/wtty9.png)
**pngcairo terminal:**
[](https://i.stack.imgur.com/OpcXU.png) |
10,664 | What is the food with the highest calorie per unit price that you can buy and eat regularly? The food cannot give you any undesirable health effect due to the sole reason that you eat it regularly. | 2017/01/01 | [
"https://health.stackexchange.com/questions/10664",
"https://health.stackexchange.com",
"https://health.stackexchange.com/users/7809/"
] | For **1 US Dollar** you can get:
Foods with mainly *carbohydrates:*
* **Polenta/cornmeal,** raw, 847 g = **2,930** Cal
* **Potatoes, white,** raw, 2,400 g = **1,844** Cal
* **Bread, black,** 680 g = **1,536** Cal
* **Oatmeal,** raw, 340 g = **1,244** Cal
* **Rice, white,** raw, 320 g = **1,117** Cal-
* **Chickpeas (garbanzo beans),** canned, (also contain protein), 340 g = **558** Cal
Foods with mainly *protein/fat:*
* **Chicken,** raw, 405 g = **640** Cal
* **Sardines,** canned, 142 g = **354** Cal
These are examples of cheap high-calorie foods you can eat regularly as part of a healthy diet.
*Cal = 1 kilocalorie*
*Prices, as available in Slovenia/Europe at 6th January 2017*
---
Calculations and sources:
* Bread, black, 1kg = 1,39 € = 1.47 $; for $1 you get 680 g = 1,536 Cal (226 Cal/100 g) ([source](https://trgovina.mercator.si/market/izdelek/1536699/crni-hlebec-mercator-1kg))
* Rice, white, 1 kg = 2.98 € = 3.15 $; for $1 you get 320 g = 1,117 Cal (349 Cal/100 g) ([source](https://trgovina.mercator.si/market/izdelek/28543/srednjezrnati-brusen-riz-za-domace-jedi-zlato-polje-1-kg))
* Polenta (cornmeal), 500 g = 0.56 € = 0.59 $; for $1 you get 847 g = 2.930 Cal (346 Cal/100 g) ([price](https://trgovina.mercator.si/market/izdelek/16879812/instant-polenta-mercator-500-g), [Calories](http://www.mlinotest.si/okusi/mlinotest/moke-in-mlevski-izdelki/instant-mlevski-izdelki/instant-polenta-500-g/))
* Oatmeal, 500 g = 1.39 € = 1.47 $; for $1 you get 340 g = 1,244 Cal (366 Cal/100 g) ([source](https://trgovina.mercator.si/market/izdelek/82115/ovseni-kosmici-zito-500-g))
* Potatoes, white, 5 kg = 2 € = 2.1 $; for $1 you get 2,400 g = 1,844 Cal (77 Cal/100 g) ([price](https://trgovina.mercator.si/market/izdelek/14939390/krompir-mercator-5kg-pakirano), [Calories](http://www.cenim.se/hranilne-vrednosti.php?id=2924))
* Chickpeas, canned, for $1 you get 340 g = 558 Cal ([price](https://www.walmart.com/ip/La-Preferida-Chick-Peas-15-oz-Pack-of-12/19475594?action=product_interest&action_type=title&beacon_version=1.0.2&bucket_id=irsbucketdefault&client_guid=b0a2d57f-0c10-43c6-81c7-0a31e7ad0827&config_id=106&customer_id_enc&findingMethod=p13n&guid=b0a2d57f-0c10-43c6-81c7-0a31e7ad0827&item_id=19475594&parent_anchor_item_id=10534041&parent_item_id=10534041&placement_id=irs-106-t1&reporter=recommendations&source=new_site&strategy=PWVAV&visitor_id=Qywxb4F8UbLMSgaZbzoypE)), [(Calories)](https://ndb.nal.usda.gov/ndb/foods/show/4796?man=&lfacet=&count=&max=50&qlookup=chickpeas&offset=&sort=default&format=Abridged&reportfmt=other&rptfrm=&ndbno=&nutrient1=&nutrient2=&nutrient3=&subset=&totCount=&measureby=&Qv=3.4&Q9005=1&Qv=1&Q9005=1)
* Canned fish, sardines, 105 g = 0.7 € = 0.74 $; for $1 you get 142 g = 354 Cal (249 Cal/100 g) ([source](https://trgovina.mercator.si/market/izdelek/16882804/sardine-v-rastlinskem-olju-mercator-105-g))
* Chicken, whole, 1.5 kg = 3.5 € = 3.7 $; for $1 you get 405 g = 640 Cal (160 (Cal/100 g) ([source](https://trgovina.mercator.si/market/izdelek/12208088/piscanec-mercator-pakirano-cena-za-kg)) | For millennia, "Rice and Beans" have been a staple worldwide for good reason: they are cheap crops that together provide a "compete protien", that is, every type of amino acid that we cannot synthesize ourselves.
Though they're slightly more time consuming to cook, go with dried beans instead of canned if it'll be a regular thing. Eating canned beans for a large part of your diet will have effects similar to eating canned *anything* for a large part of your diet, that is, way too much sodium. |
2,716,178 | How do I handle closing tags (ex: `</h1>`) with the Java HTML Parser Library?
For example, if I have the following:
```
public class MyFilter implements NodeFilter {
public boolean accept(Node node) {
if (node instanceof TagNode) {
TagNode theNode = (TagNode) node;
if (theNode.getRawTagName().equals("h1")) {
return true;
} else {
return false;
}
}
return false;
}
}
public class MyParser {
public final String parseString(String input) {
Parser parser = new Parser();
MyFilter theFilter = new MyFilter();
parser.setInputHTML("<h1>Welcome, User</h1>");
NodeList theList = parser.parse(theFilter);
return theList.toHtml();
}
}
```
When I run my parser, I get the following output back:
```
<h1>Welcome, User</h1>Welcome, User</h1>
```
The NodeList contains a list of size 3 with the following entities:
```
(tagNode) <h1>
(textNode) Welcome, User
(tagNode) </h1>
```
I would like the output to be "`<h1>Welcome, User</h1>`". Does anyone see what is wrong in my sample parser? | 2010/04/26 | [
"https://Stackoverflow.com/questions/2716178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/326284/"
] | A `DataContext` follows a pattern known as a Unit of Work. It tracks all inserts, updates, and deletes you do during a piece of code.
Once that piece of code is done running, the `SubmitChanges` method sends all modifications to the database *at one time*. There is no need for you to do anything; changes you make will automatically be persisted. | Just don't write this method :)
Any time some business logic needs to update specific fields on a person, *update the specific fields on that person* (and remember to update the datacontext before the http context is unloaded)
You were on the right track when you said "Is that redundant since L2S already mapped my Person Table to a Class?". Just use the class that L2S has provided :)
If you've got a (winforms) screen that needs to edit this 30 field person object, then the easiest thing to do is to [databind](http://msdn.microsoft.com/en-us/library/ef2xyb33(v=VS.100).aspx) the fields on your screen directly to the fields on linq to sql's Person object. Here's a typical screen's lifecycle:
* Your form is constructed (with a person ID)
* Your form's load event handler will retrieve a Person object from Linq to Sql: `context.tblPersons.Single(x=>x.ID == personID)`
* This Person will be set as the form's main [BindingSource's](http://msdn.microsoft.com/en-us/library/system.windows.forms.bindingsource.aspx) DataSource
* A whole lot of textboxes on the screen will be setup to bind to each field on that person object, allowing the user to edit the properties directly (you can just drag a detailsview from the data sources tab onto your form in VS to do these automatically)
* When the user hits save, just call EndEdit on the DataSource, then SubmitChanges on the L2s Datacontext
All going well, you should see new values in your database... |
2,716,178 | How do I handle closing tags (ex: `</h1>`) with the Java HTML Parser Library?
For example, if I have the following:
```
public class MyFilter implements NodeFilter {
public boolean accept(Node node) {
if (node instanceof TagNode) {
TagNode theNode = (TagNode) node;
if (theNode.getRawTagName().equals("h1")) {
return true;
} else {
return false;
}
}
return false;
}
}
public class MyParser {
public final String parseString(String input) {
Parser parser = new Parser();
MyFilter theFilter = new MyFilter();
parser.setInputHTML("<h1>Welcome, User</h1>");
NodeList theList = parser.parse(theFilter);
return theList.toHtml();
}
}
```
When I run my parser, I get the following output back:
```
<h1>Welcome, User</h1>Welcome, User</h1>
```
The NodeList contains a list of size 3 with the following entities:
```
(tagNode) <h1>
(textNode) Welcome, User
(tagNode) </h1>
```
I would like the output to be "`<h1>Welcome, User</h1>`". Does anyone see what is wrong in my sample parser? | 2010/04/26 | [
"https://Stackoverflow.com/questions/2716178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/326284/"
] | Just don't write this method :)
Any time some business logic needs to update specific fields on a person, *update the specific fields on that person* (and remember to update the datacontext before the http context is unloaded)
You were on the right track when you said "Is that redundant since L2S already mapped my Person Table to a Class?". Just use the class that L2S has provided :)
If you've got a (winforms) screen that needs to edit this 30 field person object, then the easiest thing to do is to [databind](http://msdn.microsoft.com/en-us/library/ef2xyb33(v=VS.100).aspx) the fields on your screen directly to the fields on linq to sql's Person object. Here's a typical screen's lifecycle:
* Your form is constructed (with a person ID)
* Your form's load event handler will retrieve a Person object from Linq to Sql: `context.tblPersons.Single(x=>x.ID == personID)`
* This Person will be set as the form's main [BindingSource's](http://msdn.microsoft.com/en-us/library/system.windows.forms.bindingsource.aspx) DataSource
* A whole lot of textboxes on the screen will be setup to bind to each field on that person object, allowing the user to edit the properties directly (you can just drag a detailsview from the data sources tab onto your form in VS to do these automatically)
* When the user hits save, just call EndEdit on the DataSource, then SubmitChanges on the L2s Datacontext
All going well, you should see new values in your database... | What is wrong with your Update method is that you have are creating a datacontext instance within it.
And I presume you also have other CRUD methods which do the same.
If you abstract your CRUD operations to a Repository class you will be using the DataContext as it was meant to be used.
See the answer to this [question](https://stackoverflow.com/questions/2473795/linq-to-sql-add-update-in-different-methods-with-different-datacontexts), if you follow the design outlined you will be just passing a Person object to the repository Update method and it will not be so unwieldy. |
2,716,178 | How do I handle closing tags (ex: `</h1>`) with the Java HTML Parser Library?
For example, if I have the following:
```
public class MyFilter implements NodeFilter {
public boolean accept(Node node) {
if (node instanceof TagNode) {
TagNode theNode = (TagNode) node;
if (theNode.getRawTagName().equals("h1")) {
return true;
} else {
return false;
}
}
return false;
}
}
public class MyParser {
public final String parseString(String input) {
Parser parser = new Parser();
MyFilter theFilter = new MyFilter();
parser.setInputHTML("<h1>Welcome, User</h1>");
NodeList theList = parser.parse(theFilter);
return theList.toHtml();
}
}
```
When I run my parser, I get the following output back:
```
<h1>Welcome, User</h1>Welcome, User</h1>
```
The NodeList contains a list of size 3 with the following entities:
```
(tagNode) <h1>
(textNode) Welcome, User
(tagNode) </h1>
```
I would like the output to be "`<h1>Welcome, User</h1>`". Does anyone see what is wrong in my sample parser? | 2010/04/26 | [
"https://Stackoverflow.com/questions/2716178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/326284/"
] | A `DataContext` follows a pattern known as a Unit of Work. It tracks all inserts, updates, and deletes you do during a piece of code.
Once that piece of code is done running, the `SubmitChanges` method sends all modifications to the database *at one time*. There is no need for you to do anything; changes you make will automatically be persisted. | What is wrong with your Update method is that you have are creating a datacontext instance within it.
And I presume you also have other CRUD methods which do the same.
If you abstract your CRUD operations to a Repository class you will be using the DataContext as it was meant to be used.
See the answer to this [question](https://stackoverflow.com/questions/2473795/linq-to-sql-add-update-in-different-methods-with-different-datacontexts), if you follow the design outlined you will be just passing a Person object to the repository Update method and it will not be so unwieldy. |
60,937,975 | >
> Since Digital Ocean Spaces API is compatible with AWS SDK, how to
> upload images to Digital Ocean Spaces programmatically using AWS SDK
> for Yii2?
>
>
>
Here my details
```
Good, we have the following data:
1. endpoint: fra1.digitaloceanspaces.com
2. bucket name: dev-abc
3. api key: xxxxxxxxxxxxx and api secret: xxxxxxx
4. The url that you need to use to deliver assets is https://dev-abc
```
I have tried with this code whis is not working
```
$uploader = new FileUpload(FileUpload::S_S3, [
'version' => 'latest',
'region' => 'fra1',
'endpoint' => 'https://fra1.digitaloceanspaces.com',
'credentials' => [
'key' => 'xxxxxxxxxxxxx ',
'secret' => 'xxxxxxx'
],
'bucket' => 'dev-abc'
]);
``` | 2020/03/30 | [
"https://Stackoverflow.com/questions/60937975",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5994023/"
] | You can php code to upload image in digital ocean:
1. Configure a client:
use Aws\S3\S3Client;
```
$client = new Aws\S3\S3Client([
'version' => 'latest',
'region' => 'us-east-1',
'endpoint' => 'https://nyc3.digitaloceanspaces.com',
'credentials' => [
'key' => getenv('SPACES_KEY'),
'secret' => getenv('SPACES_SECRET'),
],
]);
```
2. Create a New Space
```
$client->createBucket([
'Bucket' => 'example-space-name',
]);
```
3. Upload Image
```
$client->putObject([
'Bucket' => 'example-space-name',
'Key' => 'file.ext',
'Body' => 'The contents of the file.',
'ACL' => 'private'
]);
``` | Install composer from <https://getcomposer.org/download/> and then run the following to setup the AWS PHP dependencies:
```
composer require aws/aws-sdk-php
```
The following code has a form for uploading images, the code processes the files and uploads them to DO Spaces. Replace your values with those in the code.
```
<?php
require 'vendor/autoload.php';
use Aws\S3\S3Client;
if(isset($_FILES['image'])){
$file_name = $_FILES['image']['name'];
$temp_file_location = $_FILES['image']['tmp_name'];
$s3 = new Aws\S3\S3Client([
'region' => '-- your region --',
'version' => 'latest',
'credentials' => [
'key' => "-- access key id --",
'secret' => "-- secret access key --",
]
]);
$result = $s3->putObject([
'Bucket' => '-- bucket name --',
'Key' => $file_name,
'SourceFile' => $temp_file_location
]);
var_dump($result);
}
?>
<form action="<?= $_SERVER['PHP_SELF']; ?>" method="POST" enctype="multipart/form-data">
<input type="file" name="image" />
<input type="submit"/>
</form>
``` |
60,937,975 | >
> Since Digital Ocean Spaces API is compatible with AWS SDK, how to
> upload images to Digital Ocean Spaces programmatically using AWS SDK
> for Yii2?
>
>
>
Here my details
```
Good, we have the following data:
1. endpoint: fra1.digitaloceanspaces.com
2. bucket name: dev-abc
3. api key: xxxxxxxxxxxxx and api secret: xxxxxxx
4. The url that you need to use to deliver assets is https://dev-abc
```
I have tried with this code whis is not working
```
$uploader = new FileUpload(FileUpload::S_S3, [
'version' => 'latest',
'region' => 'fra1',
'endpoint' => 'https://fra1.digitaloceanspaces.com',
'credentials' => [
'key' => 'xxxxxxxxxxxxx ',
'secret' => 'xxxxxxx'
],
'bucket' => 'dev-abc'
]);
``` | 2020/03/30 | [
"https://Stackoverflow.com/questions/60937975",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5994023/"
] | **Here how i mange to go this**
Added the three libraries gulp,gulp-awspublish,gulp-rename
```
var gulp = require('gulp');
var awspublish = require('gulp-awspublish');
var rename = require('gulp-rename');
var publisherDev = awspublish.create({
region: 'fra1',
params: {
Bucket: 'dev-static-abc-ro'
},
accessKeyId: 'XCCCCCZX',
secretAccessKey: 'EDKDJKJDKDJ',
endpoint: 'fra1.digitaloceanspaces.com'
});
```
Now added the function
// dev server
```
gulp.task('dev', function() {
// console.log("Hi! I'm Gulp default task root!");
return gulp
.src('./temp-dist/**')
.pipe(
rename(function(path) {
path.dirname += '/assets';
// path.basename += "-s3";
})
)
.pipe(publisherDev.publish())
.pipe(publisherDev.sync('assets/'))
.pipe(awspublish.reporter());
});
```
Run the command
>
> gulp dev
>
>
> | Install composer from <https://getcomposer.org/download/> and then run the following to setup the AWS PHP dependencies:
```
composer require aws/aws-sdk-php
```
The following code has a form for uploading images, the code processes the files and uploads them to DO Spaces. Replace your values with those in the code.
```
<?php
require 'vendor/autoload.php';
use Aws\S3\S3Client;
if(isset($_FILES['image'])){
$file_name = $_FILES['image']['name'];
$temp_file_location = $_FILES['image']['tmp_name'];
$s3 = new Aws\S3\S3Client([
'region' => '-- your region --',
'version' => 'latest',
'credentials' => [
'key' => "-- access key id --",
'secret' => "-- secret access key --",
]
]);
$result = $s3->putObject([
'Bucket' => '-- bucket name --',
'Key' => $file_name,
'SourceFile' => $temp_file_location
]);
var_dump($result);
}
?>
<form action="<?= $_SERVER['PHP_SELF']; ?>" method="POST" enctype="multipart/form-data">
<input type="file" name="image" />
<input type="submit"/>
</form>
``` |
188,156 | The users need to be about to print the forms they've filled out on SharePoint after they've filled them out. In just wondering if it is easily possible because I'm not finding anything.
Forms are hosted on SharePoint and created in InfoPath | 2016/07/29 | [
"https://sharepoint.stackexchange.com/questions/188156",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/56516/"
] | * Go to list > Customize List> select your form.
* Add a Content Editor Web part or Script Editor for SharePoint 2013 to the page.
[](https://i.stack.imgur.com/9aUbI.png)
- Add the following code.
```
`< input type="button" value=" Print this page " onclick="window.print();return false;" />`
```
You can also add `on click` the following function
`function printInfoPathForm(){
var ipForm = $(INFOPATH_FORM);
if (ipForm) {
//build html for print page
var html = "<HTML><HEAD>\n"+
$("head").html()+
"</HEAD>\n<BODY>\n"+
ipForm.html()+
"\n</BODY></HTML>";
//open new window
var printWP = window.open("","printWebPart");
printWP.document.open();
//insert content
printWP.document.write(html);
printWP.document.close();
//open print dialog
printWP.print();
}
}`
For more details check this [article](http://www.enjoysharepoint.com/Articles/Details/add-print-button-to-display-form-in-sharepoint-2013-using-20837.aspx) | Have you possibly looked into this: <http://infopathprinter.codeplex.com/>
You can add the option as a Custom Action XML |
188,156 | The users need to be about to print the forms they've filled out on SharePoint after they've filled them out. In just wondering if it is easily possible because I'm not finding anything.
Forms are hosted on SharePoint and created in InfoPath | 2016/07/29 | [
"https://sharepoint.stackexchange.com/questions/188156",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/56516/"
] | * Go to list > Customize List> select your form.
* Add a Content Editor Web part or Script Editor for SharePoint 2013 to the page.
[](https://i.stack.imgur.com/9aUbI.png)
- Add the following code.
```
`< input type="button" value=" Print this page " onclick="window.print();return false;" />`
```
You can also add `on click` the following function
`function printInfoPathForm(){
var ipForm = $(INFOPATH_FORM);
if (ipForm) {
//build html for print page
var html = "<HTML><HEAD>\n"+
$("head").html()+
"</HEAD>\n<BODY>\n"+
ipForm.html()+
"\n</BODY></HTML>";
//open new window
var printWP = window.open("","printWebPart");
printWP.document.open();
//insert content
printWP.document.write(html);
printWP.document.close();
//open print dialog
printWP.print();
}
}`
For more details check this [article](http://www.enjoysharepoint.com/Articles/Details/add-print-button-to-display-form-in-sharepoint-2013-using-20837.aspx) | If you are looking for "Print" button on the form page
Edit the default list form, add "Content Editor" webpart and put the below HTML as content.
you can add css in the same place for formatting. |
84,473 | The Nachem prayer for tisha b'av describes he city as השוממה מאין יושב, "desolate without inhabitant." What does this mean? In what way was Jerusalem desolate without inhabitants? Does this have a non-literal meaning? NOTE: I am not referring to the question of Nachem after 1967. I am asking what this prayer could have meant for the nineteen hundred years beforehand. | 2017/07/31 | [
"https://judaism.stackexchange.com/questions/84473",
"https://judaism.stackexchange.com",
"https://judaism.stackexchange.com/users/14599/"
] | Two thousand years beforehand, they may not have said this text.
[Rambam's text](http://www.mechon-mamre.org/i/2700.htm#23), for example, does not have it, nor do Seder Rav Amram Gaon (ed. Harpenes: Seder Tisha B'av), or Seder Rav Sa'adya Gaon, which just has השוממה.
Nevertheless, it is present in the Siddur of [R. Eleazar Rokeah](https://en.wikipedia.org/wiki/Eleazar_of_Worms) (ch. 123 p. 637). His Siddur makes clear that the references to being bereft of its inhabitants refer particularly to the Jewish inhabitants.
>
> והשוממה מכל טוב. האבלה מבלי בניה שאין ישראל בתוכה, דרכי ציון אבילות מבלי באי מועד...והשוממה מבלי יושב אין איש מיהודה יושב בה, כל שעריה שוממין. היא יושבת בגוים
>
>
> Desolate of all good. That is in mourning without her children: for the Jews are not in it; "The paths of Zion are mourning, without pilgrims." And bereft with no inhabitants; there is no man of Judah living in it: "All its gates are destroyed."
>
>
>
The line השוממה מאין יושב is thus particularly understandable in light of the line: ויבלעוה לגיונים, ויירשוה עובדי פסילים; that it was occupied by foreign legions and idolaters.
This prayer referencing general destruction, absence of Jewish inhabitants, and occupation by foreign armies was always true to one degree or another following the destruction of the Second Templ, until modern times. For example, following the destruction of Jerusalem (in 70), Josephus writes ([The Wars of the Jews: Book VII:1](http://sacred-texts.com/jud/josephus/war-7.htm)):
>
> Now as soon as the army had no more people to slay or to plunder, because there remained none to be the objects of their fury (for they would not have spared any, had there remained any other work to be done), [Titus] Caesar gave orders that they should now demolish the entire city and Temple...**there was left nothing to make those that came thither believe it [Jerusalem] had ever been inhabited**.
>
>
>
Furthermore, the [Bar Kokhba revolt](https://en.wikipedia.org/wiki/Bar_Kokhba_revolt) 65 years later:
>
> Resulted in the extensive depopulation of Judean communities, more so than the First Jewish–Roman War of 70 CE. According to Cassius Dio, 580,000 Jews perished in the war and many more died of hunger and disease. In addition, many Judean war captives were sold into slavery. The Jewish communities of Judea were devastated to an extent which some scholars describe as a genocide. ([Wikipedia](https://en.wikipedia.org/wiki/Bar_Kokhba_revolt)).
>
>
>
Furthermore, Jews were barred from entering Jerusalem except for on Tisha B'av (ibid). They remained banned throughout the remainder of its time as a Roman province, except during a brief period of Persian rule from 614 to 629. ([Wikipedia](https://en.wikipedia.org/wiki/History_of_Jerusalem#Post-Crisis_Roman_and_Early_Byzantine_Empire_period))
Later, during the [First Crusade](https://en.wikipedia.org/wiki/First_Crusade), Jerusalem was captured by Christians in 1099, and:
>
> The capture was accompanied by a massacre of almost all of the Muslim and Jewish inhabitants ([Wikipedia](https://en.wikipedia.org/wiki/History_of_Jerusalem#Kingdom_of_Jerusalem_.28Crusaders.29_period)).
>
>
>
Specifically:
>
> According to the Muslim chronicle of Ibn al-Qalanisi, "The Jews
> assembled in their synagogue, and the Franks burned it over their
> heads. ([Wikipedia](https://en.wikipedia.org/wiki/Siege_of_Jerusalem_(1099)#Jews))
>
>
>
This period lasted until the Crusaders were defeated at the [Siege and Fall of Jerusalem in 1187](https://en.wikipedia.org/wiki/Siege_of_Jerusalem_(1187)). About 30 years later, Jerusalem and its Jewish inhabitants *again* suffered destruction when the Ayyubid ruler of Syria, Al-Mu'azzam destroyed Jerusalem:
>
> The city suffered two waves of destruction in 1219 and 1220. This was absolute and brutal destruction, with most buildings in Jerusalem and its walls destroyed...The vast majority of the population, including the Jewish community, left Jerusalem. ([Wikipedia](https://en.wikipedia.org/wiki/History_of_Jerusalem_during_the_Kingdom_of_Jerusalem#Destruction_of_Jerusalem)).
>
>
>
From 1229 to 1244 the city was returned to mostly Christian control, by Abassids allied with them. In the [Siege of 1244](https://en.wikipedia.org/wiki/Siege_of_Jerusalem_(1244)), however, As-Salih Ayyub who not allied with the Crusaders, summoned a huge mercenary army of Khwarezmians, who proceeded to again, destroy the city.
In 1260, after the city is retaken by the Ayyubids from the Khwarezmians, it is raided by Mongols. ([Wikipedia](https://en.wikipedia.org/wiki/Timeline_of_Jerusalem#Bahri_Mamluk_and_Burji_Mamluk_periods))
Almost a decade later, when Ramban moved to Jerusalem, he is reputed to have found just two Jewish families ([Wikipedia](https://en.wikipedia.org/wiki/Timeline_of_Jerusalem#Bahri_Mamluk_and_Burji_Mamluk_periods)).
While the population grew with time, even 200 years later, in the late 15th century the Jewish population of Jerusalem varied from 76-250 families ([Wikipedia](https://en.wikipedia.org/wiki/Demographic_history_of_Jerusalem#Middle_Ages)). Following a "mass" migration led by Yehuda Hassid (see [here](https://judaism.stackexchange.com/q/60882/8775) about him and his synagogue) in 1700 (when the Jewish population was about 1200), the Jewish population rose to 2000 by 1723. (AFAIK the highest it was since the destruction of temple, and probably just a fraction of a percent of its population then). By the early 19th century, its Jewish population [was no higher](https://en.wikipedia.org/wiki/Demographic_history_of_Jerusalem#Muslim_.22relative_majority.22). After multiple waves of immigration, and significant philanthropic efforts on behalf of residents, the population reached 10000 at the end of the 19th century, and rapidly grew to almost 100000 in 1944.
While the city wasn't always totally uninhabited, or even bereft of all of Jewish inhabitants, (See [timeline](https://en.wikipedia.org/wiki/Timeline_of_Jerusalem)) it frequently changed hands among foreign invaders, was destroyed multiple times, banned Jews for centuries, and for nearly two millennia did not return, to even a shadow of its former self (with a Jewish population of hundreds of presumably hundreds of thousands (Tacitus says 600000) before the destruction of the second Temple.).
---
Alternatively, the [Imrei Emmet](https://en.wikipedia.org/wiki/Avraham_Mordechai_Alter) explains this as referring to the heavenly Jerusalem not being inhabited by God, as it is stated (Ta'anit 5a) that God will not enter the heavenly Jerusalem, until he enters the terrestrial Jerusalem. (Cited in Daf Al HaDaf to Ta'anit 5a). | Perhaps מאין יושב. Does not refer to a complete absence of inhabitants, but a lack. This would seem more literally accurate for much of history |
15,174,517 | I want to send multiple SMS' via using smslib. I make a Java class to send SMS in a loop. But it works only one time. then it returns the following exception:
```
org.smslib.GatewayException: Comm library exception:
java.lang.RuntimeException: javax.comm.PortInUseException:
Port currently owned by org.smslib
at org.smslib.modem.SerialModemDriver.connectPort(SerialModemDriver.java:102)
at org.smslib.modem.AModemDriver.connect(AModemDriver.java:114)
at org.smslib.modem.ModemGateway.startGateway(ModemGateway.java:189)
at org.smslib.Service$1Starter.run(Service.java:276)
```
This is my class:
```
import javax.swing.JOptionPane;
import org.smslib.AGateway;
import org.smslib.IOutboundMessageNotification;
import org.smslib.OutboundMessage;
import org.smslib.Service;
import org.smslib.modem.SerialModemGateway;
public class SendSMS1 {
private static String id;
private static String port;
private static int bitRate;
private static String modemName;
private static String modemPin;
private static String SMSC;
public static void doIt(String number, String text) {
try {
OutboundMessage msg;
OutboundNotification outboundNotification = new OutboundNotification();
SerialModemGateway gateway = new SerialModemGateway(id, port, bitRate, modemName, "E17u-1");
gateway.setInbound(true);
gateway.setOutbound(true);
gateway.setSimPin(modemPin);
Service.getInstance().setOutboundMessageNotification(outboundNotification);
Service.getInstance().addGateway(gateway);
Service.getInstance().startService();
msg = new OutboundMessage(number, text);
Service.getInstance().sendMessage(msg);
System.out.println(msg);
Service.getInstance().stopService();
} catch (Exception ex) {
if (ex.getStackTrace()[2].getLineNumber() == 189) {
JOptionPane.showMessageDialog(null,
"Port currently owned by usb Modem's application. \n Please close it & run the programm again.",
"Port Exception",
JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
} else {
JOptionPane.showMessageDialog(null,
ex.getMessage(),
"Sending faile",
JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
}
}
}
public static class OutboundNotification implements IOutboundMessageNotification {
public void process(AGateway gateway, OutboundMessage msg) {
System.out.println("Outbound handler called from Gateway: " + gateway.getGatewayId());
System.out.println(msg);
}
}
public static void main(String[] args) throws Exception {
String number = "+94772347634", text = "Hello world";
modemName = "Huwawi";
port = "COM4";
bitRate = 115200;
modemPin = "0000";
SMSC = "+947500010";
for (int i = 0; i < 5; i++) {
SendSMS1 app = new SendSMS1();
app.doIt(number, text);
}
}
}
```
Please give me advice, what should I do differently? | 2013/03/02 | [
"https://Stackoverflow.com/questions/15174517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2126003/"
] | I don't know the smslib, but I imagine everything until `startService` should only happen once, not each time you want to send a message, as follows:
```
class SendSMS1
{
public SendSMS1(String modemName, String port, int bitRate,
String modemPin, String SMSC)
{
OutboundNotification outboundNotification = new OutboundNotification();
SerialModemGateway gateway = new SerialModemGateway(id, port, bitRate, modemName, "E17u-1");
gateway.setInbound(true);
gateway.setOutbound(true);
gateway.setSimPin(modemPin);
Service.getInstance().setOutboundMessageNotification(outboundNotification);
Service.getInstance().addGateway(gateway);
Service.getInstance().startService();
}
public static void doIt(String number, String text) {
try {
OutboundMessage msg = new OutboundMessage(number, text);
Service.getInstance().sendMessage(msg);
System.out.println(msg);
Service.getInstance().stopService();
} catch (Exception ex) {
if (ex.getStackTrace()[2].getLineNumber() == 189) {
JOptionPane.showMessageDialog(null,
"Port currently owned by usb Modem's application. \n Please close it & run the programm again.",
"Port Exception",
JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
} else {
JOptionPane.showMessageDialog(null,
ex.getMessage(),
"Sending faile",
JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
}
}
}
public static void main(String[] args) throws Exception {
String number = "+94772347634", text = "Hello world";
SendSMS1 app = new SendSMS1("Huwawi", "COM4", 115200, "0000", "+947500010");
for (int i = 0; i < 5; i++) {
app.doIt(number, text);
}
}
}
``` | Change this.It's Working
```
public static void main(String[] args) throws Exception {
Calendar now = Calendar.getInstance();
String ar=(dateFormat.format(now.getTime()));
String text = "We are the Future of Science "+" "+ar;
SendSMS app = new SendSMS("Huawei", "COM20", 115200, "0000", "+9477000003");
for (int i = 0; i < 1; i++) {
String[] numbers = {"+num","+num","+num","+num","+num","+num","+num","+num"};
for (String item : numbers) {
Service.getInstance().startService();
app.doIt(item, text);
Service.getInstance().stopService();
}}
}
``` |
15,174,517 | I want to send multiple SMS' via using smslib. I make a Java class to send SMS in a loop. But it works only one time. then it returns the following exception:
```
org.smslib.GatewayException: Comm library exception:
java.lang.RuntimeException: javax.comm.PortInUseException:
Port currently owned by org.smslib
at org.smslib.modem.SerialModemDriver.connectPort(SerialModemDriver.java:102)
at org.smslib.modem.AModemDriver.connect(AModemDriver.java:114)
at org.smslib.modem.ModemGateway.startGateway(ModemGateway.java:189)
at org.smslib.Service$1Starter.run(Service.java:276)
```
This is my class:
```
import javax.swing.JOptionPane;
import org.smslib.AGateway;
import org.smslib.IOutboundMessageNotification;
import org.smslib.OutboundMessage;
import org.smslib.Service;
import org.smslib.modem.SerialModemGateway;
public class SendSMS1 {
private static String id;
private static String port;
private static int bitRate;
private static String modemName;
private static String modemPin;
private static String SMSC;
public static void doIt(String number, String text) {
try {
OutboundMessage msg;
OutboundNotification outboundNotification = new OutboundNotification();
SerialModemGateway gateway = new SerialModemGateway(id, port, bitRate, modemName, "E17u-1");
gateway.setInbound(true);
gateway.setOutbound(true);
gateway.setSimPin(modemPin);
Service.getInstance().setOutboundMessageNotification(outboundNotification);
Service.getInstance().addGateway(gateway);
Service.getInstance().startService();
msg = new OutboundMessage(number, text);
Service.getInstance().sendMessage(msg);
System.out.println(msg);
Service.getInstance().stopService();
} catch (Exception ex) {
if (ex.getStackTrace()[2].getLineNumber() == 189) {
JOptionPane.showMessageDialog(null,
"Port currently owned by usb Modem's application. \n Please close it & run the programm again.",
"Port Exception",
JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
} else {
JOptionPane.showMessageDialog(null,
ex.getMessage(),
"Sending faile",
JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
}
}
}
public static class OutboundNotification implements IOutboundMessageNotification {
public void process(AGateway gateway, OutboundMessage msg) {
System.out.println("Outbound handler called from Gateway: " + gateway.getGatewayId());
System.out.println(msg);
}
}
public static void main(String[] args) throws Exception {
String number = "+94772347634", text = "Hello world";
modemName = "Huwawi";
port = "COM4";
bitRate = 115200;
modemPin = "0000";
SMSC = "+947500010";
for (int i = 0; i < 5; i++) {
SendSMS1 app = new SendSMS1();
app.doIt(number, text);
}
}
}
```
Please give me advice, what should I do differently? | 2013/03/02 | [
"https://Stackoverflow.com/questions/15174517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2126003/"
] | You must remove the gateway.
can use this-
*Service.getInstance().removeGateway(gateway);*
you should insert it in doIt method, after - *Service.getInstance().stopService();* | Change this.It's Working
```
public static void main(String[] args) throws Exception {
Calendar now = Calendar.getInstance();
String ar=(dateFormat.format(now.getTime()));
String text = "We are the Future of Science "+" "+ar;
SendSMS app = new SendSMS("Huawei", "COM20", 115200, "0000", "+9477000003");
for (int i = 0; i < 1; i++) {
String[] numbers = {"+num","+num","+num","+num","+num","+num","+num","+num"};
for (String item : numbers) {
Service.getInstance().startService();
app.doIt(item, text);
Service.getInstance().stopService();
}}
}
``` |
60,657,831 | I've set my mapping up as follows:
```
CreateMap<SourceClass, DestinationClass>().ForMember(destinationMember => destinationMember.Provider,
memberOptions => memberOptions.MapFrom(src => src.Providers.FirstOrDefault()));
```
Where I'm mapping from a List in my SourceClass to a string in my destination class.
My question is, how can I handle the case where "Providers" is null?
I've tried using:
`src?.Providers?.FirstOrDefault()`
but I get an error saying I can't use null propagators in a lambda.
I've been reading up on Automapper and am still unsure if AM automatically handles the null case or not. I tried to build the expression tree, but was not able to see any information that provided additional informations.
If it helps, I'm using automapper v 6.1.1. | 2020/03/12 | [
"https://Stackoverflow.com/questions/60657831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4162438/"
] | Like what @goto1 mentioned in a comment, you may create a custom hook to use for a cleaner and reusable look. Here's my take on a custom hook called `useCbOnce` which calls any event callback once:
```
const useCbOnce = (cb) => {
const [called, setCalled] = useState(false);
// Below can be wrapped in useCallback whenever re-renders becomes a problem
return (e) => {
if (!called) {
setCalled(true);
cb(e);
}
}
}
const MyForm = (props) => {
const handleSubmit = useCbOnce((e) => {
e.preventDefault()
console.log('submitted!')
});
return <form onSubmit={handleSubmit}>...</form>;
}
``` | You can reuse `onSubmit` logic with simple [custom hook](https://reactjs.org/docs/hooks-custom.html#using-a-custom-hook).
I oversimplified the logic so it won't cause unnecessary renders:
```
const useOnSubmit = () => {
const [, setSubmitted] = useState(false);
const onSubmit = useCallback(e => {
e.preventDefault();
setSubmitted(prevState => prevState || !prevState);
}, []);
return onSubmit;
};
// Usage
const onSubmit = useOnSubmit();
<form onSubmit={onSubmit}>...</form>
``` |
60,657,831 | I've set my mapping up as follows:
```
CreateMap<SourceClass, DestinationClass>().ForMember(destinationMember => destinationMember.Provider,
memberOptions => memberOptions.MapFrom(src => src.Providers.FirstOrDefault()));
```
Where I'm mapping from a List in my SourceClass to a string in my destination class.
My question is, how can I handle the case where "Providers" is null?
I've tried using:
`src?.Providers?.FirstOrDefault()`
but I get an error saying I can't use null propagators in a lambda.
I've been reading up on Automapper and am still unsure if AM automatically handles the null case or not. I tried to build the expression tree, but was not able to see any information that provided additional informations.
If it helps, I'm using automapper v 6.1.1. | 2020/03/12 | [
"https://Stackoverflow.com/questions/60657831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4162438/"
] | Like what @goto1 mentioned in a comment, you may create a custom hook to use for a cleaner and reusable look. Here's my take on a custom hook called `useCbOnce` which calls any event callback once:
```
const useCbOnce = (cb) => {
const [called, setCalled] = useState(false);
// Below can be wrapped in useCallback whenever re-renders becomes a problem
return (e) => {
if (!called) {
setCalled(true);
cb(e);
}
}
}
const MyForm = (props) => {
const handleSubmit = useCbOnce((e) => {
e.preventDefault()
console.log('submitted!')
});
return <form onSubmit={handleSubmit}>...</form>;
}
``` | Here's an example that lets you customize what action happens on submit, but always prevents the default and only calls the action once.
```js
function useSubmitAction(action=null, dependencies = [action]) {
const [submitted, setSubmitted] = React.useState(false)
return React.useCallback(function (event, ...rest) {
event.preventDefault()
if (submitted) return
setSubmitted(true)
if (action) action(event, ...rest)
}, dependencies)
}
function FooForm(props) {
const onSubmit = useSubmitAction((e) => console.log('submitting event type', e.type))
return (<form onSubmit={ onSubmit }>
<button type="submit">Submit</button>
</form>)
}
ReactDOM.render(<FooForm />, document.getElementById('app'))
```
```html
<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
<div id="app" />
```
Note that you may want to set the `submitted` state to true after you call the action, so that if errors occur then submit doesn't get set to true. But it depends on your use case. |
120,425 | There are several questions around limiting ftp users to certain directories. However, most of them refer to vsftpd, which I don't think I have installed on my system. I'm running Ubuntu 9.04. How can I tell what ftp service I have installed, and then limit certain users to only the `/home/ftpuser` directory instead of having full access to the file system?
I think I can add them to a separate group and give that group access to the proper directories, but then do I have to remove that groups permissions from all other directories? It seems like there should be an easy way like setting the `chroot_local_user` value in the `/etc/vsftpd/vsftpd.conf` file, but that doesn't exist on my system.
**Update**
Here are the results of: `dpkg --list |grep -i ftp`:
`ii curl 7.18.2-8ubuntu4.1 Get a file from an HTTP, HTTPS or FTP server`
I can connect to this servier using sftp but there are no ftp servers installed. Do I have to install one? | 2010/03/08 | [
"https://serverfault.com/questions/120425",
"https://serverfault.com",
"https://serverfault.com/users/37112/"
] | I'd recommend using [proftpd](http://www.proftpd.org/) with Ubuntu.... I follwed these steps recently and it worked ver y well....
Here's quick install steps:
```
sudo apt-get install proftpd
# Add this line in /etc/shells file (sudo gedit /etc/shells to open the file)
/bin/false
cd /home
sudo mkdir FTP-shared
sudo useradd userftp -p your_password -d /home/FTP-shared -s /bin/false
sudo passwd userftp
cd /home
sudo chmod 755 FTP-shared
and edit your proftpd.conf file like that if it fit to your need
sudo gedit /etc/proftpd.conf
or
sudo gedit /etc/proftpd/proftpd.conf
sudo /etc/init.d/proftpd start
```
These steps are from this very helpful [thread](http://ubuntuforums.org/showthread.php?t=79588) on ubuntuforums.org | ```
dpkg --list |grep -i ftp
```
should show you the list of packages on your machine that include 'ftp' in the name. If there's not one, then you may not have any kind of FTP server installed. |
22,528,853 | I have a data frame with alternating columns that I want to reshape. The problem is that `stats::reshape` and `reshape2::reshape` are both very slow and memory intensive on my actual use case. I suspect that the no-copy approach of `data.table` will save me time and use less resources, but I barely know where to start with the syntax (previous related efforts [1](https://stackoverflow.com/q/16494665/1036500), [2](https://stackoverflow.com/q/16494665/1036500)).
Here's an example of how my data frame is structured:
```
set.seed(4)
dt <- data.frame(names = letters[1:10],
one = rep(23,10),
two = sample(1000,10),
three = sample(10,10),
onea = rep(24,10),
twoa = sample(1000,10),
threea = sample(10,10),
oneb = rep(25,10),
twob = sample(1000,10),
threeb = sample(10,10),
onec = rep(26,10),
twoc = sample(1000,10),
threec = sample(10,10),
oned = rep(26,10),
twod = sample(1000,10),
threed = sample(10,10))
```
Which looks like this:
```
names one two three onea twoa threea oneb twob threeb onec twoc threec oned
1 a 23 586 8 24 715 6 25 939 4 26 561 4 26
2 b 23 9 3 24 996 3 25 242 7 26 72 6 26
3 c 23 294 1 24 506 8 25 565 8 26 852 10 26
4 d 23 277 7 24 489 5 25 181 6 26 911 3 26
5 e 23 811 9 24 647 9 25 901 5 26 225 5 26
6 f 23 260 6 24 827 7 25 84 3 26 626 8 26
7 g 23 721 4 24 480 2 25 896 1 26 69 2 26
8 h 23 900 2 24 836 4 25 886 10 26 512 9 26
9 i 23 942 5 24 510 1 25 718 2 26 799 1 26
10 j 23 73 10 24 526 10 25 560 9 26 964 7 26
twod threed
1 911 2
2 709 10
3 571 5
4 915 9
5 899 3
6 59 1
7 46 4
8 982 7
9 205 8
10 921 6
```
Here's what I'm currently doing with `stats::reshape` which takes a long time and uses a lot of memory on my actual use case:
```
df_l <- stats::reshape(dt, idvar='names',
varying=list(ones = colnames(dt[seq(from=2,
to=ncol(dt), by=3)]),
twos = colnames(dt[seq(from=4,
to=ncol(dt), by=3)])),
direction="long")
```
Here's the desired output (I don't care about any of the `three` columns):
```
df_l
names two twoa twob twoc twod time one three
a.1 a 586 715 939 561 911 1 23 8
b.1 b 9 996 242 72 709 1 23 3
c.1 c 294 506 565 852 571 1 23 1
d.1 d 277 489 181 911 915 1 23 7
e.1 e 811 647 901 225 899 1 23 9
f.1 f 260 827 84 626 59 1 23 6
g.1 g 721 480 896 69 46 1 23 4
h.1 h 900 836 886 512 982 1 23 2
i.1 i 942 510 718 799 205 1 23 5
j.1 j 73 526 560 964 921 1 23 10
a.2 a 586 715 939 561 911 2 24 6
b.2 b 9 996 242 72 709 2 24 3
c.2 c 294 506 565 852 571 2 24 8
d.2 d 277 489 181 911 915 2 24 5
e.2 e 811 647 901 225 899 2 24 9
f.2 f 260 827 84 626 59 2 24 7
g.2 g 721 480 896 69 46 2 24 2
h.2 h 900 836 886 512 982 2 24 4
i.2 i 942 510 718 799 205 2 24 1
j.2 j 73 526 560 964 921 2 24 10
a.3 a 586 715 939 561 911 3 25 4
b.3 b 9 996 242 72 709 3 25 7
c.3 c 294 506 565 852 571 3 25 8
d.3 d 277 489 181 911 915 3 25 6
e.3 e 811 647 901 225 899 3 25 5
f.3 f 260 827 84 626 59 3 25 3
g.3 g 721 480 896 69 46 3 25 1
h.3 h 900 836 886 512 982 3 25 10
i.3 i 942 510 718 799 205 3 25 2
j.3 j 73 526 560 964 921 3 25 9
a.4 a 586 715 939 561 911 4 26 4
b.4 b 9 996 242 72 709 4 26 6
c.4 c 294 506 565 852 571 4 26 10
d.4 d 277 489 181 911 915 4 26 3
e.4 e 811 647 901 225 899 4 26 5
f.4 f 260 827 84 626 59 4 26 8
g.4 g 721 480 896 69 46 4 26 2
h.4 h 900 836 886 512 982 4 26 9
i.4 i 942 510 718 799 205 4 26 1
j.4 j 73 526 560 964 921 4 26 7
a.5 a 586 715 939 561 911 5 26 2
b.5 b 9 996 242 72 709 5 26 10
c.5 c 294 506 565 852 571 5 26 5
d.5 d 277 489 181 911 915 5 26 9
e.5 e 811 647 901 225 899 5 26 3
f.5 f 260 827 84 626 59 5 26 1
g.5 g 721 480 896 69 46 5 26 4
h.5 h 900 836 886 512 982 5 26 7
i.5 i 942 510 718 799 205 5 26 8
j.5 j 73 526 560 964 921 5 26 6
```
How can I do this with `data.table`? | 2014/03/20 | [
"https://Stackoverflow.com/questions/22528853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1036500/"
] | You could either do it this way
```
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.newapp.Firstscreen$PlaceholderFragment" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="match_paren"
android:layout_height="match_paren"
android:scaleType="fitXY"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="@drawable/background" />
</RelativeLayout>
```
OR
```
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:background="@drawable/background"
tools:context="com.example.newapp.Firstscreen$PlaceholderFragment" >
<!-- CONTENT HERE -->
</RelativeLayout>
``` | Change `Height` and `Width` of `ImageView` to `match_parent`.
```
<ImageView
android:id="@+id/imageView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/background" />
```
Edit-
Complete code-
```
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.newapp.Firstscreen$PlaceholderFragment" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/background" />
</RelativeLayout>
``` |
22,528,853 | I have a data frame with alternating columns that I want to reshape. The problem is that `stats::reshape` and `reshape2::reshape` are both very slow and memory intensive on my actual use case. I suspect that the no-copy approach of `data.table` will save me time and use less resources, but I barely know where to start with the syntax (previous related efforts [1](https://stackoverflow.com/q/16494665/1036500), [2](https://stackoverflow.com/q/16494665/1036500)).
Here's an example of how my data frame is structured:
```
set.seed(4)
dt <- data.frame(names = letters[1:10],
one = rep(23,10),
two = sample(1000,10),
three = sample(10,10),
onea = rep(24,10),
twoa = sample(1000,10),
threea = sample(10,10),
oneb = rep(25,10),
twob = sample(1000,10),
threeb = sample(10,10),
onec = rep(26,10),
twoc = sample(1000,10),
threec = sample(10,10),
oned = rep(26,10),
twod = sample(1000,10),
threed = sample(10,10))
```
Which looks like this:
```
names one two three onea twoa threea oneb twob threeb onec twoc threec oned
1 a 23 586 8 24 715 6 25 939 4 26 561 4 26
2 b 23 9 3 24 996 3 25 242 7 26 72 6 26
3 c 23 294 1 24 506 8 25 565 8 26 852 10 26
4 d 23 277 7 24 489 5 25 181 6 26 911 3 26
5 e 23 811 9 24 647 9 25 901 5 26 225 5 26
6 f 23 260 6 24 827 7 25 84 3 26 626 8 26
7 g 23 721 4 24 480 2 25 896 1 26 69 2 26
8 h 23 900 2 24 836 4 25 886 10 26 512 9 26
9 i 23 942 5 24 510 1 25 718 2 26 799 1 26
10 j 23 73 10 24 526 10 25 560 9 26 964 7 26
twod threed
1 911 2
2 709 10
3 571 5
4 915 9
5 899 3
6 59 1
7 46 4
8 982 7
9 205 8
10 921 6
```
Here's what I'm currently doing with `stats::reshape` which takes a long time and uses a lot of memory on my actual use case:
```
df_l <- stats::reshape(dt, idvar='names',
varying=list(ones = colnames(dt[seq(from=2,
to=ncol(dt), by=3)]),
twos = colnames(dt[seq(from=4,
to=ncol(dt), by=3)])),
direction="long")
```
Here's the desired output (I don't care about any of the `three` columns):
```
df_l
names two twoa twob twoc twod time one three
a.1 a 586 715 939 561 911 1 23 8
b.1 b 9 996 242 72 709 1 23 3
c.1 c 294 506 565 852 571 1 23 1
d.1 d 277 489 181 911 915 1 23 7
e.1 e 811 647 901 225 899 1 23 9
f.1 f 260 827 84 626 59 1 23 6
g.1 g 721 480 896 69 46 1 23 4
h.1 h 900 836 886 512 982 1 23 2
i.1 i 942 510 718 799 205 1 23 5
j.1 j 73 526 560 964 921 1 23 10
a.2 a 586 715 939 561 911 2 24 6
b.2 b 9 996 242 72 709 2 24 3
c.2 c 294 506 565 852 571 2 24 8
d.2 d 277 489 181 911 915 2 24 5
e.2 e 811 647 901 225 899 2 24 9
f.2 f 260 827 84 626 59 2 24 7
g.2 g 721 480 896 69 46 2 24 2
h.2 h 900 836 886 512 982 2 24 4
i.2 i 942 510 718 799 205 2 24 1
j.2 j 73 526 560 964 921 2 24 10
a.3 a 586 715 939 561 911 3 25 4
b.3 b 9 996 242 72 709 3 25 7
c.3 c 294 506 565 852 571 3 25 8
d.3 d 277 489 181 911 915 3 25 6
e.3 e 811 647 901 225 899 3 25 5
f.3 f 260 827 84 626 59 3 25 3
g.3 g 721 480 896 69 46 3 25 1
h.3 h 900 836 886 512 982 3 25 10
i.3 i 942 510 718 799 205 3 25 2
j.3 j 73 526 560 964 921 3 25 9
a.4 a 586 715 939 561 911 4 26 4
b.4 b 9 996 242 72 709 4 26 6
c.4 c 294 506 565 852 571 4 26 10
d.4 d 277 489 181 911 915 4 26 3
e.4 e 811 647 901 225 899 4 26 5
f.4 f 260 827 84 626 59 4 26 8
g.4 g 721 480 896 69 46 4 26 2
h.4 h 900 836 886 512 982 4 26 9
i.4 i 942 510 718 799 205 4 26 1
j.4 j 73 526 560 964 921 4 26 7
a.5 a 586 715 939 561 911 5 26 2
b.5 b 9 996 242 72 709 5 26 10
c.5 c 294 506 565 852 571 5 26 5
d.5 d 277 489 181 911 915 5 26 9
e.5 e 811 647 901 225 899 5 26 3
f.5 f 260 827 84 626 59 5 26 1
g.5 g 721 480 896 69 46 5 26 4
h.5 h 900 836 886 512 982 5 26 7
i.5 i 942 510 718 799 205 5 26 8
j.5 j 73 526 560 964 921 5 26 6
```
How can I do this with `data.table`? | 2014/03/20 | [
"https://Stackoverflow.com/questions/22528853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1036500/"
] | Change `Height` and `Width` of `ImageView` to `match_parent`.
```
<ImageView
android:id="@+id/imageView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/background" />
```
Edit-
Complete code-
```
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.newapp.Firstscreen$PlaceholderFragment" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/background" />
</RelativeLayout>
``` | Add this line to your ImageView
```
android:scaleType="fitXY"
```
and set the width and height as match\_parent. |
22,528,853 | I have a data frame with alternating columns that I want to reshape. The problem is that `stats::reshape` and `reshape2::reshape` are both very slow and memory intensive on my actual use case. I suspect that the no-copy approach of `data.table` will save me time and use less resources, but I barely know where to start with the syntax (previous related efforts [1](https://stackoverflow.com/q/16494665/1036500), [2](https://stackoverflow.com/q/16494665/1036500)).
Here's an example of how my data frame is structured:
```
set.seed(4)
dt <- data.frame(names = letters[1:10],
one = rep(23,10),
two = sample(1000,10),
three = sample(10,10),
onea = rep(24,10),
twoa = sample(1000,10),
threea = sample(10,10),
oneb = rep(25,10),
twob = sample(1000,10),
threeb = sample(10,10),
onec = rep(26,10),
twoc = sample(1000,10),
threec = sample(10,10),
oned = rep(26,10),
twod = sample(1000,10),
threed = sample(10,10))
```
Which looks like this:
```
names one two three onea twoa threea oneb twob threeb onec twoc threec oned
1 a 23 586 8 24 715 6 25 939 4 26 561 4 26
2 b 23 9 3 24 996 3 25 242 7 26 72 6 26
3 c 23 294 1 24 506 8 25 565 8 26 852 10 26
4 d 23 277 7 24 489 5 25 181 6 26 911 3 26
5 e 23 811 9 24 647 9 25 901 5 26 225 5 26
6 f 23 260 6 24 827 7 25 84 3 26 626 8 26
7 g 23 721 4 24 480 2 25 896 1 26 69 2 26
8 h 23 900 2 24 836 4 25 886 10 26 512 9 26
9 i 23 942 5 24 510 1 25 718 2 26 799 1 26
10 j 23 73 10 24 526 10 25 560 9 26 964 7 26
twod threed
1 911 2
2 709 10
3 571 5
4 915 9
5 899 3
6 59 1
7 46 4
8 982 7
9 205 8
10 921 6
```
Here's what I'm currently doing with `stats::reshape` which takes a long time and uses a lot of memory on my actual use case:
```
df_l <- stats::reshape(dt, idvar='names',
varying=list(ones = colnames(dt[seq(from=2,
to=ncol(dt), by=3)]),
twos = colnames(dt[seq(from=4,
to=ncol(dt), by=3)])),
direction="long")
```
Here's the desired output (I don't care about any of the `three` columns):
```
df_l
names two twoa twob twoc twod time one three
a.1 a 586 715 939 561 911 1 23 8
b.1 b 9 996 242 72 709 1 23 3
c.1 c 294 506 565 852 571 1 23 1
d.1 d 277 489 181 911 915 1 23 7
e.1 e 811 647 901 225 899 1 23 9
f.1 f 260 827 84 626 59 1 23 6
g.1 g 721 480 896 69 46 1 23 4
h.1 h 900 836 886 512 982 1 23 2
i.1 i 942 510 718 799 205 1 23 5
j.1 j 73 526 560 964 921 1 23 10
a.2 a 586 715 939 561 911 2 24 6
b.2 b 9 996 242 72 709 2 24 3
c.2 c 294 506 565 852 571 2 24 8
d.2 d 277 489 181 911 915 2 24 5
e.2 e 811 647 901 225 899 2 24 9
f.2 f 260 827 84 626 59 2 24 7
g.2 g 721 480 896 69 46 2 24 2
h.2 h 900 836 886 512 982 2 24 4
i.2 i 942 510 718 799 205 2 24 1
j.2 j 73 526 560 964 921 2 24 10
a.3 a 586 715 939 561 911 3 25 4
b.3 b 9 996 242 72 709 3 25 7
c.3 c 294 506 565 852 571 3 25 8
d.3 d 277 489 181 911 915 3 25 6
e.3 e 811 647 901 225 899 3 25 5
f.3 f 260 827 84 626 59 3 25 3
g.3 g 721 480 896 69 46 3 25 1
h.3 h 900 836 886 512 982 3 25 10
i.3 i 942 510 718 799 205 3 25 2
j.3 j 73 526 560 964 921 3 25 9
a.4 a 586 715 939 561 911 4 26 4
b.4 b 9 996 242 72 709 4 26 6
c.4 c 294 506 565 852 571 4 26 10
d.4 d 277 489 181 911 915 4 26 3
e.4 e 811 647 901 225 899 4 26 5
f.4 f 260 827 84 626 59 4 26 8
g.4 g 721 480 896 69 46 4 26 2
h.4 h 900 836 886 512 982 4 26 9
i.4 i 942 510 718 799 205 4 26 1
j.4 j 73 526 560 964 921 4 26 7
a.5 a 586 715 939 561 911 5 26 2
b.5 b 9 996 242 72 709 5 26 10
c.5 c 294 506 565 852 571 5 26 5
d.5 d 277 489 181 911 915 5 26 9
e.5 e 811 647 901 225 899 5 26 3
f.5 f 260 827 84 626 59 5 26 1
g.5 g 721 480 896 69 46 5 26 4
h.5 h 900 836 886 512 982 5 26 7
i.5 i 942 510 718 799 205 5 26 8
j.5 j 73 526 560 964 921 5 26 6
```
How can I do this with `data.table`? | 2014/03/20 | [
"https://Stackoverflow.com/questions/22528853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1036500/"
] | You could either do it this way
```
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.newapp.Firstscreen$PlaceholderFragment" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="match_paren"
android:layout_height="match_paren"
android:scaleType="fitXY"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="@drawable/background" />
</RelativeLayout>
```
OR
```
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:background="@drawable/background"
tools:context="com.example.newapp.Firstscreen$PlaceholderFragment" >
<!-- CONTENT HERE -->
</RelativeLayout>
``` | Add this line to your ImageView
```
android:scaleType="fitXY"
```
and set the width and height as match\_parent. |
5,077,070 | I have a scenario where my Java program has to continuously communicate with the database table, for example my Java program has to get the data of my table when new rows are added to it at runtime. There should be continuous communication between my program and database.
If the table has 10 rows initially and 2 rows are added by the user, it must detect this and return the rows. | 2011/02/22 | [
"https://Stackoverflow.com/questions/5077070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/399944/"
] | With HSQLDB, this is supported without continuous polling.
HSQLDB TRIGGERs support synchronous or asynchronous notifications to be sent by the trigger event. The target may be the user's app or any other app.
See <http://hsqldb.org/doc/2.0/guide/triggers-chapt.html> | What do you mean by continuous communication? The connection to database should be kept open once established until you finish the task here. But you will have to keep polling to fetch new records. |
5,077,070 | I have a scenario where my Java program has to continuously communicate with the database table, for example my Java program has to get the data of my table when new rows are added to it at runtime. There should be continuous communication between my program and database.
If the table has 10 rows initially and 2 rows are added by the user, it must detect this and return the rows. | 2011/02/22 | [
"https://Stackoverflow.com/questions/5077070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/399944/"
] | For HSQL you can use trigger. Ref: <http://hsqldb.org/doc/2.0/guide/triggers-chapt.html>
Trigger Action in Java
A trigger action can be written as a Java class that implements the org.hsqldb.Trigger interface. This interface has a single method which is called when the trigger is activated, either before or after the event. When the method is called by the engine, it supplies the type of trigger as an int value defined by the interface(as type argument), the name of the trigger (as trigName argument), the name of the table (as tabName argument), the OLD ROW (as oldRow argument) and the NEW ROW (as newRow argument). The oldRow argument is null for row level INSERT triggers. The newRow argument is null for row level DELETE triggers. For table level triggers, both arguments are null (that is, there is no access to the data). The triggerType argument is one of the constants in the org.hsqldb.Trigger interface which indicate the type of trigger, for example, INSERT\_BEFORE\_ROW or UPDATE\_AFTER\_ROW.
```
CREATE TRIGGER t BEFORE UPDATE ON customer
REFERENCING NEW AS newrow FOR EACH ROW
BEGIN ATOMIC
IF LENGTH(newrow.firstname) > 10 THEN
CALL my_java_function(newrow.firstname, newrow.lastname);
END IF;
END
``` | What do you mean by continuous communication? The connection to database should be kept open once established until you finish the task here. But you will have to keep polling to fetch new records. |
5,077,070 | I have a scenario where my Java program has to continuously communicate with the database table, for example my Java program has to get the data of my table when new rows are added to it at runtime. There should be continuous communication between my program and database.
If the table has 10 rows initially and 2 rows are added by the user, it must detect this and return the rows. | 2011/02/22 | [
"https://Stackoverflow.com/questions/5077070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/399944/"
] | With HSQLDB, this is supported without continuous polling.
HSQLDB TRIGGERs support synchronous or asynchronous notifications to be sent by the trigger event. The target may be the user's app or any other app.
See <http://hsqldb.org/doc/2.0/guide/triggers-chapt.html> | This is not possible. You'll have to regularly poll the database in order to detect changes. |
5,077,070 | I have a scenario where my Java program has to continuously communicate with the database table, for example my Java program has to get the data of my table when new rows are added to it at runtime. There should be continuous communication between my program and database.
If the table has 10 rows initially and 2 rows are added by the user, it must detect this and return the rows. | 2011/02/22 | [
"https://Stackoverflow.com/questions/5077070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/399944/"
] | For HSQL you can use trigger. Ref: <http://hsqldb.org/doc/2.0/guide/triggers-chapt.html>
Trigger Action in Java
A trigger action can be written as a Java class that implements the org.hsqldb.Trigger interface. This interface has a single method which is called when the trigger is activated, either before or after the event. When the method is called by the engine, it supplies the type of trigger as an int value defined by the interface(as type argument), the name of the trigger (as trigName argument), the name of the table (as tabName argument), the OLD ROW (as oldRow argument) and the NEW ROW (as newRow argument). The oldRow argument is null for row level INSERT triggers. The newRow argument is null for row level DELETE triggers. For table level triggers, both arguments are null (that is, there is no access to the data). The triggerType argument is one of the constants in the org.hsqldb.Trigger interface which indicate the type of trigger, for example, INSERT\_BEFORE\_ROW or UPDATE\_AFTER\_ROW.
```
CREATE TRIGGER t BEFORE UPDATE ON customer
REFERENCING NEW AS newrow FOR EACH ROW
BEGIN ATOMIC
IF LENGTH(newrow.firstname) > 10 THEN
CALL my_java_function(newrow.firstname, newrow.lastname);
END IF;
END
``` | This is not possible. You'll have to regularly poll the database in order to detect changes. |
5,077,070 | I have a scenario where my Java program has to continuously communicate with the database table, for example my Java program has to get the data of my table when new rows are added to it at runtime. There should be continuous communication between my program and database.
If the table has 10 rows initially and 2 rows are added by the user, it must detect this and return the rows. | 2011/02/22 | [
"https://Stackoverflow.com/questions/5077070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/399944/"
] | With HSQLDB, this is supported without continuous polling.
HSQLDB TRIGGERs support synchronous or asynchronous notifications to be sent by the trigger event. The target may be the user's app or any other app.
See <http://hsqldb.org/doc/2.0/guide/triggers-chapt.html> | For HSQL you can use trigger. Ref: <http://hsqldb.org/doc/2.0/guide/triggers-chapt.html>
Trigger Action in Java
A trigger action can be written as a Java class that implements the org.hsqldb.Trigger interface. This interface has a single method which is called when the trigger is activated, either before or after the event. When the method is called by the engine, it supplies the type of trigger as an int value defined by the interface(as type argument), the name of the trigger (as trigName argument), the name of the table (as tabName argument), the OLD ROW (as oldRow argument) and the NEW ROW (as newRow argument). The oldRow argument is null for row level INSERT triggers. The newRow argument is null for row level DELETE triggers. For table level triggers, both arguments are null (that is, there is no access to the data). The triggerType argument is one of the constants in the org.hsqldb.Trigger interface which indicate the type of trigger, for example, INSERT\_BEFORE\_ROW or UPDATE\_AFTER\_ROW.
```
CREATE TRIGGER t BEFORE UPDATE ON customer
REFERENCING NEW AS newrow FOR EACH ROW
BEGIN ATOMIC
IF LENGTH(newrow.firstname) > 10 THEN
CALL my_java_function(newrow.firstname, newrow.lastname);
END IF;
END
``` |
7,114,082 | I'm using django to do a pixel tracker on an email
Is it easy to return an actual image from a django view (and how would this be done?) or is it easier to just return a redirect to the url where the actual image lives? | 2011/08/18 | [
"https://Stackoverflow.com/questions/7114082",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/443722/"
] | You don't need an actual image for a tracker pixel. In fact, it's better if you don't have one.
Just use the view as the source for the image tag, and have it return a blank response. | Django has a [static file](https://docs.djangoproject.com/en/dev/howto/static-files/) helper that could be used to serve up the image, but it is not recommended because of performance. I believe that having a view that does the bookkeeping to track the pixel, then redirect to a url that [serves the actual image via the webserver](https://docs.djangoproject.com/en/dev/howto/static-files/#serving-static-files-from-a-dedicated-server) is going to give you the best performance. |
7,114,082 | I'm using django to do a pixel tracker on an email
Is it easy to return an actual image from a django view (and how would this be done?) or is it easier to just return a redirect to the url where the actual image lives? | 2011/08/18 | [
"https://Stackoverflow.com/questions/7114082",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/443722/"
] | Since this was the first result on my google search and the best answer is buried in the link by Daniel (but not mentioned as the best), I figured I would just post the answer so nobody is tempted to return a blank response which as a Michael points out is not ideal.
The solution is to use a standard view and return an HttpResponse with the raw data that makes up a single pixel gif. Not having to hit the disk or redirect is a huge advantage.
Note that the url pattern uses the tracking code as the image name so there is no obvious ?code=jf8992jf in the url.
```
from django.conf.urls import patterns, url
from emails.views.pixel import PixelView
urlpatterns = patterns('',
url(r'^/p/(?P<pixel>\w+).gif$', PixelView.as_view(), name='email_pixel'),
)
```
And here is the view. Note that it uses cache\_control to prevent requests from running wild. Firefox (along with many email clients) for instance will request the image twice every time for some reason you probably don't care about but need to worry about. By adding max\_age=60 you will just get one request per minute.
```
from django.views.decorators.cache import cache_control
from django.http.response import HttpResponse
from django.views.generic import View
class PixelView(View):
@cache_control(must_revalidate=True, max_age=60)
def get(self, request, pixel):
"""
Tracking pixel for opening an email
:param request: WSGIRequest
:param pixel: str
:return: HttpResponse
"""
# Do whatever tracking you want here
# Render the pixel
pixel_image = b'\x47\x49\x46\x38\x39\x61\x01\x00\x01\x00\x80\x00\x00\xff\xff\xff\x00\x00\x00\x21\xf9\x04\x01\x00\x00\x00\x00\x2c\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02\x44\x01\x00\x3b'
return HttpResponse(pixel_image, content_type='image/gif')
``` | Django has a [static file](https://docs.djangoproject.com/en/dev/howto/static-files/) helper that could be used to serve up the image, but it is not recommended because of performance. I believe that having a view that does the bookkeeping to track the pixel, then redirect to a url that [serves the actual image via the webserver](https://docs.djangoproject.com/en/dev/howto/static-files/#serving-static-files-from-a-dedicated-server) is going to give you the best performance. |
7,114,082 | I'm using django to do a pixel tracker on an email
Is it easy to return an actual image from a django view (and how would this be done?) or is it easier to just return a redirect to the url where the actual image lives? | 2011/08/18 | [
"https://Stackoverflow.com/questions/7114082",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/443722/"
] | Django has a [static file](https://docs.djangoproject.com/en/dev/howto/static-files/) helper that could be used to serve up the image, but it is not recommended because of performance. I believe that having a view that does the bookkeeping to track the pixel, then redirect to a url that [serves the actual image via the webserver](https://docs.djangoproject.com/en/dev/howto/static-files/#serving-static-files-from-a-dedicated-server) is going to give you the best performance. | **Python2.x:**
```
from django.http import HttpResponse
PIXEL_GIF_DATA = """
R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7
""".strip().decode('base64')
def pixel_gif(request):
return HttpResponse(PIXEL_GIF_DATA, content_type='image/gif')
```
**Python3.x:**
```
import base64
from django.http import HttpResponse
PIXEL_GIF_DATA = base64.b64decode(
b"R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")
def pixel_gif(request):
return HttpResponse(PIXEL_GIF_DATA, content_type='image/gif')
```
**Source:** <https://gist.github.com/simonw/10235798> |
7,114,082 | I'm using django to do a pixel tracker on an email
Is it easy to return an actual image from a django view (and how would this be done?) or is it easier to just return a redirect to the url where the actual image lives? | 2011/08/18 | [
"https://Stackoverflow.com/questions/7114082",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/443722/"
] | You don't need an actual image for a tracker pixel. In fact, it's better if you don't have one.
Just use the view as the source for the image tag, and have it return a blank response. | Since this was the first result on my google search and the best answer is buried in the link by Daniel (but not mentioned as the best), I figured I would just post the answer so nobody is tempted to return a blank response which as a Michael points out is not ideal.
The solution is to use a standard view and return an HttpResponse with the raw data that makes up a single pixel gif. Not having to hit the disk or redirect is a huge advantage.
Note that the url pattern uses the tracking code as the image name so there is no obvious ?code=jf8992jf in the url.
```
from django.conf.urls import patterns, url
from emails.views.pixel import PixelView
urlpatterns = patterns('',
url(r'^/p/(?P<pixel>\w+).gif$', PixelView.as_view(), name='email_pixel'),
)
```
And here is the view. Note that it uses cache\_control to prevent requests from running wild. Firefox (along with many email clients) for instance will request the image twice every time for some reason you probably don't care about but need to worry about. By adding max\_age=60 you will just get one request per minute.
```
from django.views.decorators.cache import cache_control
from django.http.response import HttpResponse
from django.views.generic import View
class PixelView(View):
@cache_control(must_revalidate=True, max_age=60)
def get(self, request, pixel):
"""
Tracking pixel for opening an email
:param request: WSGIRequest
:param pixel: str
:return: HttpResponse
"""
# Do whatever tracking you want here
# Render the pixel
pixel_image = b'\x47\x49\x46\x38\x39\x61\x01\x00\x01\x00\x80\x00\x00\xff\xff\xff\x00\x00\x00\x21\xf9\x04\x01\x00\x00\x00\x00\x2c\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02\x44\x01\x00\x3b'
return HttpResponse(pixel_image, content_type='image/gif')
``` |
7,114,082 | I'm using django to do a pixel tracker on an email
Is it easy to return an actual image from a django view (and how would this be done?) or is it easier to just return a redirect to the url where the actual image lives? | 2011/08/18 | [
"https://Stackoverflow.com/questions/7114082",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/443722/"
] | You don't need an actual image for a tracker pixel. In fact, it's better if you don't have one.
Just use the view as the source for the image tag, and have it return a blank response. | **Python2.x:**
```
from django.http import HttpResponse
PIXEL_GIF_DATA = """
R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7
""".strip().decode('base64')
def pixel_gif(request):
return HttpResponse(PIXEL_GIF_DATA, content_type='image/gif')
```
**Python3.x:**
```
import base64
from django.http import HttpResponse
PIXEL_GIF_DATA = base64.b64decode(
b"R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")
def pixel_gif(request):
return HttpResponse(PIXEL_GIF_DATA, content_type='image/gif')
```
**Source:** <https://gist.github.com/simonw/10235798> |
7,114,082 | I'm using django to do a pixel tracker on an email
Is it easy to return an actual image from a django view (and how would this be done?) or is it easier to just return a redirect to the url where the actual image lives? | 2011/08/18 | [
"https://Stackoverflow.com/questions/7114082",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/443722/"
] | Since this was the first result on my google search and the best answer is buried in the link by Daniel (but not mentioned as the best), I figured I would just post the answer so nobody is tempted to return a blank response which as a Michael points out is not ideal.
The solution is to use a standard view and return an HttpResponse with the raw data that makes up a single pixel gif. Not having to hit the disk or redirect is a huge advantage.
Note that the url pattern uses the tracking code as the image name so there is no obvious ?code=jf8992jf in the url.
```
from django.conf.urls import patterns, url
from emails.views.pixel import PixelView
urlpatterns = patterns('',
url(r'^/p/(?P<pixel>\w+).gif$', PixelView.as_view(), name='email_pixel'),
)
```
And here is the view. Note that it uses cache\_control to prevent requests from running wild. Firefox (along with many email clients) for instance will request the image twice every time for some reason you probably don't care about but need to worry about. By adding max\_age=60 you will just get one request per minute.
```
from django.views.decorators.cache import cache_control
from django.http.response import HttpResponse
from django.views.generic import View
class PixelView(View):
@cache_control(must_revalidate=True, max_age=60)
def get(self, request, pixel):
"""
Tracking pixel for opening an email
:param request: WSGIRequest
:param pixel: str
:return: HttpResponse
"""
# Do whatever tracking you want here
# Render the pixel
pixel_image = b'\x47\x49\x46\x38\x39\x61\x01\x00\x01\x00\x80\x00\x00\xff\xff\xff\x00\x00\x00\x21\xf9\x04\x01\x00\x00\x00\x00\x2c\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02\x44\x01\x00\x3b'
return HttpResponse(pixel_image, content_type='image/gif')
``` | **Python2.x:**
```
from django.http import HttpResponse
PIXEL_GIF_DATA = """
R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7
""".strip().decode('base64')
def pixel_gif(request):
return HttpResponse(PIXEL_GIF_DATA, content_type='image/gif')
```
**Python3.x:**
```
import base64
from django.http import HttpResponse
PIXEL_GIF_DATA = base64.b64decode(
b"R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")
def pixel_gif(request):
return HttpResponse(PIXEL_GIF_DATA, content_type='image/gif')
```
**Source:** <https://gist.github.com/simonw/10235798> |
12,917,001 | I have this site : <http://test.tamarawobben.nl>
What's the best way to achieve that the footer will always be on the bottom of the screen? | 2012/10/16 | [
"https://Stackoverflow.com/questions/12917001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1692026/"
] | CSS for the footer
```
footer {
position:absolute;
bottom:0;
width:100%;
height:60px; /* Height of the footer */
background:#6cf;
}
```
Full article on this : [How to keep footers at the bottom of the page](http://matthewjamestaylor.com/blog/keeping-footers-at-the-bottom-of-the-page) | Take a look at this tutorial on how to do this - <http://matthewjamestaylor.com/blog/keeping-footers-at-the-bottom-of-the-page>.
Should get you what you're looking for. |
12,917,001 | I have this site : <http://test.tamarawobben.nl>
What's the best way to achieve that the footer will always be on the bottom of the screen? | 2012/10/16 | [
"https://Stackoverflow.com/questions/12917001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1692026/"
] | It depends on what you mean by "always on the bottom". There are two type of footers that are "always on the bottom": Fixed and sticky.
A fixed footer is always on the bottom *of the browser window*, where as a sticky footer is always on the bottom *of the page content or the browser, whichever is lower*.
For the sticky footer, you can check out the code [on this page](http://ryanfait.com/sticky-footer/). For a fixed footer, you just want to give it the following properties:
```
#footer {
position: fixed;
bottom: 0px;
}
``` | Take a look at this tutorial on how to do this - <http://matthewjamestaylor.com/blog/keeping-footers-at-the-bottom-of-the-page>.
Should get you what you're looking for. |
49,674,318 | I've noticed that in PHP the following code works with no complaints:
```
class A {
public static function echoes($b) {
echo $b->protectedFunction();
}
}
class B extends A {
protected function protectedFunction() {
return "this is protected";
}
}
$b = new B();
A::echoes($b);
```
Example <https://3v4l.org/JTpuQ>
However I've tried this in C# and it does not work as the parent cannot access the child protected members.
My question is who's got the OOP principles right here? I've read through the LSP but it doesn't seem concerned with parent classes, so is it correct for a parent to access child protected members (like PHP assumes it is) or should it be restricted (like C# assumes it should be)? | 2018/04/05 | [
"https://Stackoverflow.com/questions/49674318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/487813/"
] | The way that C# restricts access seems to be the most logical way to do it.
A parent should not be able to inherit anything from a child. And without inheriting anything from the child, the parent should not have access to the child's protected methods. | I think you might get problems letting the parent know something about the children. Because parents are used to extract and bundle behavior and attributes from multiple classes, so the way of information is just in one direction.
Maybe there are cases in which you need to access the protected attributes, but I guess wherever it is not needed avoid it. |
49,674,318 | I've noticed that in PHP the following code works with no complaints:
```
class A {
public static function echoes($b) {
echo $b->protectedFunction();
}
}
class B extends A {
protected function protectedFunction() {
return "this is protected";
}
}
$b = new B();
A::echoes($b);
```
Example <https://3v4l.org/JTpuQ>
However I've tried this in C# and it does not work as the parent cannot access the child protected members.
My question is who's got the OOP principles right here? I've read through the LSP but it doesn't seem concerned with parent classes, so is it correct for a parent to access child protected members (like PHP assumes it is) or should it be restricted (like C# assumes it should be)? | 2018/04/05 | [
"https://Stackoverflow.com/questions/49674318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/487813/"
] | I think you might get problems letting the parent know something about the children. Because parents are used to extract and bundle behavior and attributes from multiple classes, so the way of information is just in one direction.
Maybe there are cases in which you need to access the protected attributes, but I guess wherever it is not needed avoid it. | PHP is a dynamically typed language. Function and method calls are not checked until that line of code is actually executed. In PHP you can have two objects instances from the same class with different methods. [This works fine.](https://stackoverflow.com/questions/2938004/how-to-add-a-new-method-to-a-php-object-on-the-fly)
Statically typed languages like C# require to know the types of objects before execution. You can still [use reflection to call children methods from the parent](https://stackoverflow.com/questions/2202381/reflection-how-to-invoke-method-with-parameters), but you can't add new methods dynamically. |
49,674,318 | I've noticed that in PHP the following code works with no complaints:
```
class A {
public static function echoes($b) {
echo $b->protectedFunction();
}
}
class B extends A {
protected function protectedFunction() {
return "this is protected";
}
}
$b = new B();
A::echoes($b);
```
Example <https://3v4l.org/JTpuQ>
However I've tried this in C# and it does not work as the parent cannot access the child protected members.
My question is who's got the OOP principles right here? I've read through the LSP but it doesn't seem concerned with parent classes, so is it correct for a parent to access child protected members (like PHP assumes it is) or should it be restricted (like C# assumes it should be)? | 2018/04/05 | [
"https://Stackoverflow.com/questions/49674318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/487813/"
] | The way that C# restricts access seems to be the most logical way to do it.
A parent should not be able to inherit anything from a child. And without inheriting anything from the child, the parent should not have access to the child's protected methods. | PHP is a dynamically typed language. Function and method calls are not checked until that line of code is actually executed. In PHP you can have two objects instances from the same class with different methods. [This works fine.](https://stackoverflow.com/questions/2938004/how-to-add-a-new-method-to-a-php-object-on-the-fly)
Statically typed languages like C# require to know the types of objects before execution. You can still [use reflection to call children methods from the parent](https://stackoverflow.com/questions/2202381/reflection-how-to-invoke-method-with-parameters), but you can't add new methods dynamically. |
69,737,525 | I am working on a form in React e-commerce project.
Here's how it should work: When user fills up the form and clicks the submit button I want to post the form data to a server and redirect the user to a confirmation/thank you page.
Unfortunately, when I fill up the form and click the submit button the following code works in a specific way:
1st click - it sends the data but "setSubmitted(true)" doesn't work so I am not redirected
2nd click - is sends the data again, setSubmitted works and I am redirected
Could you tell me how to fix the code?
```
let history = useHistory();
const [submitted, setSubmitted] = useState(false);
const handleSubmit = (e) => {
e.preventDefault();
fetch('http://localhost:8000/orders', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ cart: 1 }), //dummy data
})
.then((response) => {
setSubmitted(true);
return response.json();
})
.then(() => {
if (submitted) {
return history.push('/thank-you-page');
}
});
};
return (
<form onSubmit={handleSubmit}> ... </form>
);
``` | 2021/10/27 | [
"https://Stackoverflow.com/questions/69737525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15278400/"
] | You can loop over each key value pair and replace the value if its empty. Be aware that a backslash is used for escaping a character. To fix this we first replace the backslashes with dashes and then replace the rest.
The regex could also be simplified to `/[^-|]/g` which means replace all symbols except `-` and `|`
```js
const lines = {
"part": "Intro",
"e": "------5/6-----8\\6-|-------------------|-------------------",
"B": "-----------9-------|---------6p8---(6)-|-------------------",
"G": "--8----------------|---8h9-------------|--<8>--------------",
"D": "",
"A": "",
"E": "",
"endMsg": "Continue..."
};
const createFullLines = (lines, blacklist = ['part', 'endMsg']) => {
// Find a line that is not empty
const line = Object.entries(lines).find(([key, line]) => {
return !blacklist.includes(key) && line.trim();
});
// Exit if all lines are empty
if(!line) return lines;
// Destructure to get only value
const [_, filledLine] = line;
// Create new line with only dashes
const newLine = filledLine.replace(/[^-|]/g, '-');
// Update lines
for(const key in lines) {
lines[key] ||= newLine;
}
return lines;
}
const result = createFullLines(lines);
console.log(result);
``` | You should just iterate between your object's keys like this:
```js
// find first non-empty field, !! - conversion to boolean
let nonEmptyKey = Object.keys(obj).find(key => !!obj[key]);
for(let key of Object.keys(obj)) {
// check if value is empty
if(!obj[key]) {
obj[key] = obj[nonEmptyKey].replace(/[0-9-. a-zA-Z // \ ~ ( ) < >]/g, '-');
}
}
```
Also, you can simplify your regex to this:
```js
// replace all symbols except - and |
str.replace(/[^-|]/g, '-');
``` |
269,379 | I am using the `fp` package to write a coursework in mechanics **and** calculate the numerical values on the fly. Here is some example code:
```
\documentclass{article}
\usepackage[nomessages]{fp} % http://ctan.org/pkg/fp
\begin{document}
\section{Requirements}
\FPset{P_output_kW}{11}
\FPset{n_output_max_rpm}{5000}
P_output_kW = \FPprint{P_output_kW} kW
n_output_max_rpm = \FPprint{n_output_max_rpm} rpm
\end{document}
```
As is evident, I am attempting to print every assigned variable by name, value and measurement unit. First of all, the above code does not compile with the error:
```
! Missing $ inserted.
```
I would like to invoke into a single command (with a single parameter) the two operations:
* print variable name, followed by `=`
* print variable value
How can that be achieved? | 2015/09/24 | [
"https://tex.stackexchange.com/questions/269379",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/45581/"
] | The following sets the variable name in typewriter font, the number via `\FPprint` and the unit is taken from the variable name:
```
\documentclass{article}
\usepackage[nomessages]{fp} % http://ctan.org/pkg/fp
\newcommand*{\VarOutput}[1]{%
\begingroup
\fontencoding{T1}%
\fontfamily{lmvtt}\selectfont % variable typewriter font
% alternative: \ttfamily
\detokenize{#1}% make _ to character
\endgroup
~=~%
\FPprint{#1}%
\,%
\ExtractUnit{#1}%
}
\newcommand*{\ExtractUnit}[1]{%
\expandafter\ExtractUnitAux\detokenize{#1_}\relax
}
\begingroup
\catcode`\_=12 %
\gdef\ExtractUnitAux#1_#2\relax{%
\ifx\\#2\\%
#1
\else
\ExtractUnitAux#2\relax
\fi
}
\endgroup
\begin{document}
\section{Requirements}
\FPset{P_output_kW}{11}
\FPset{n_output_max_rpm}{5000}
\VarOutput{P_output_kW}\\
\VarOutput{n_output_max_rpm}
\end{document}
```
>
> [](https://i.stack.imgur.com/3QRTo.png)
>
>
> | This uses \csname.
```
\documentclass{article}
\usepackage{showframe}
\usepackage{siunitx}
\usepackage{pgfmath}
\parindent=0pt
\newcommand{\FPset}[2]% #1 = varaible name, #2 = value
{\expandafter\gdef\csname FPV#1\endcsname{#2}}
\newcommand{\FPunit}[2]% #1 = variable name, #2 = units
{\expandafter\gdef\csname FPU#1\endcsname{#2}}
\newcommand{\FPmacro}[2]% #1 = variable name, #2 = macro to store value
{\edef #2{\csname FPV#1\endcsname}}
\newcommand{\FPprint}[1]% #1 = variable name
{#1 $=$ \num{\csname FPV#1\endcsname} \si{\csname FPU#1\endcsname}}
\begin{document}
\FPset{power}{5}
\FPunit{power}{\si{\kilo\watt}}% predefined from sciunitx
\FPprint{power}
\FPset{time}{2}
\FPunit{time}{\si{\hour}}
\FPprint{time}\par
\FPmacro{power}{\x}
\FPmacro{time}{\t}
\pgfmathparse{\x*\t}
\FPset{energy}{\pgfmathresult}
\FPunit{energy}{\si{\kilo\watt\hour}}
\FPprint{energy}
\end{document}
```
[](https://i.stack.imgur.com/F7Jd9.png) |
969,824 | I'm trying to set up a brand-new Epson WorkForce WF-3640 printer and it seems there are some weird mechanical issues. It would seem the carriage is not moving freely. This is *before* I get to install the ink cartridges.
The printer may make a loud grinding noise and return errors 0xF1, 0xEA, 0xE8, or 0xE1. Alternatively, the printer may report a paper jam when there is no paper in the paper path at all.
Any ideas?
---
It seems the carriage is getting stuck on a movable plastic clip at the front right end of the unit or is not engaging correctly at the right end. Why would this be happening? | 2015/09/08 | [
"https://superuser.com/questions/969824",
"https://superuser.com",
"https://superuser.com/users/73918/"
] | ### 0xE8 and later 0xEA codes
>
> There is a blue tape on the interior that needs to be removed- once I did this it worked fine.
>
>
>
...
>
> I had the same issue: 0xE8 and later 0xEA codes. I could see that it
> was the white moving clip under the ink tank holder when on the far
> right that was catching it. The ONLY thing that fixed it was: once it
> made a noise and errored I unwillingly pushed the tank holder over to
> the left until the tanks pushed past the white clip and all the way to
> the left..
>
>
> Then there were no more errors.
>
>
>
Source [0xE8 and later 0xEA codes](http://www.askmefast.com/Epson_wf3620__need_resolution_for_error_code_0xE8-qna8892260.html#q6764814)
---
### 520 FATAL CODE:0xF1 EPSON Workforce
>
> This relates to the print head not being able to completely pass from the left to right side during startup. I had a plastic carriage on the one side that was stuck in a position that stop the carriage from make the complete run from side to side. When I forced the plastic carriage down and it clicked into place the error stopped and the printer started up normally with no codes.
>
>
> If anything is causing the print head to not travel completely from left to right during startup, this will probable cause the code. It will be hard to see if the print head is being obstructed if you don't remove the sides.
>
>
>
Source [520 FATAL CODE:0xF1 EPSON Workforce](http://hpprintermanual.blogspot.co.uk/2013/03/520-fatal-code0xf1-epson-workforce.html)
---
### Print Error Code0xE3 and 0xEA
>
> We have seen some success with this issue by following these
> instructions. Please try this procedure one more time using the
> instructions below.
>
>
> 1. Turn the printer off, then disconnect the power and the interface cable. Open the cover and check for any torn or jammed paper
> and remove it.
> 2. Reconnect the power cable and turn the printer back on.
> 3. Press the Copy button and see if the unit responds.
>
>
> Note: Also check that the ink cartridges and lids are pushed down
> fully.
>
>
> If the issue persists, the hardware itself is malfunctioning and will
> require service
>
>
>
Source [Print Error Code0xE3 and 0xEA](http://www.fixya.com/support/t25141495-print_error_code0xe3_0xea) | Epson technical support stated that this is a hardware failure. Standard troubleshooting steps have not produced a solution.
The printer is being replaced under warranty.
---
**Update:** The replacement printer has been set up and is fully operational. Well, defective product is defective... |
969,824 | I'm trying to set up a brand-new Epson WorkForce WF-3640 printer and it seems there are some weird mechanical issues. It would seem the carriage is not moving freely. This is *before* I get to install the ink cartridges.
The printer may make a loud grinding noise and return errors 0xF1, 0xEA, 0xE8, or 0xE1. Alternatively, the printer may report a paper jam when there is no paper in the paper path at all.
Any ideas?
---
It seems the carriage is getting stuck on a movable plastic clip at the front right end of the unit or is not engaging correctly at the right end. Why would this be happening? | 2015/09/08 | [
"https://superuser.com/questions/969824",
"https://superuser.com",
"https://superuser.com/users/73918/"
] | ### 0xE8 and later 0xEA codes
>
> There is a blue tape on the interior that needs to be removed- once I did this it worked fine.
>
>
>
...
>
> I had the same issue: 0xE8 and later 0xEA codes. I could see that it
> was the white moving clip under the ink tank holder when on the far
> right that was catching it. The ONLY thing that fixed it was: once it
> made a noise and errored I unwillingly pushed the tank holder over to
> the left until the tanks pushed past the white clip and all the way to
> the left..
>
>
> Then there were no more errors.
>
>
>
Source [0xE8 and later 0xEA codes](http://www.askmefast.com/Epson_wf3620__need_resolution_for_error_code_0xE8-qna8892260.html#q6764814)
---
### 520 FATAL CODE:0xF1 EPSON Workforce
>
> This relates to the print head not being able to completely pass from the left to right side during startup. I had a plastic carriage on the one side that was stuck in a position that stop the carriage from make the complete run from side to side. When I forced the plastic carriage down and it clicked into place the error stopped and the printer started up normally with no codes.
>
>
> If anything is causing the print head to not travel completely from left to right during startup, this will probable cause the code. It will be hard to see if the print head is being obstructed if you don't remove the sides.
>
>
>
Source [520 FATAL CODE:0xF1 EPSON Workforce](http://hpprintermanual.blogspot.co.uk/2013/03/520-fatal-code0xf1-epson-workforce.html)
---
### Print Error Code0xE3 and 0xEA
>
> We have seen some success with this issue by following these
> instructions. Please try this procedure one more time using the
> instructions below.
>
>
> 1. Turn the printer off, then disconnect the power and the interface cable. Open the cover and check for any torn or jammed paper
> and remove it.
> 2. Reconnect the power cable and turn the printer back on.
> 3. Press the Copy button and see if the unit responds.
>
>
> Note: Also check that the ink cartridges and lids are pushed down
> fully.
>
>
> If the issue persists, the hardware itself is malfunctioning and will
> require service
>
>
>
Source [Print Error Code0xE3 and 0xEA](http://www.fixya.com/support/t25141495-print_error_code0xe3_0xea) | Same error code 0xEA for WF-3640 received today.
...multiple attempts to clear it, but each time (after I finally got the carriage to go to the left), the carriage returned to the right, locked up, and error'd out.
Called Epson...cycled through the same process, even sent them a picture of the l-shaped bracket (for whatever they needed to look at)...tried again, and...surprise the same error occurred. They finally stated "hardware error", please return it to the place of purchase for a replacement. This is the first Epson in 20+ years...have had nothing but Canons and first one out of the box...it's really a shame. Hopefully the warranty replacement will be happier. |
969,824 | I'm trying to set up a brand-new Epson WorkForce WF-3640 printer and it seems there are some weird mechanical issues. It would seem the carriage is not moving freely. This is *before* I get to install the ink cartridges.
The printer may make a loud grinding noise and return errors 0xF1, 0xEA, 0xE8, or 0xE1. Alternatively, the printer may report a paper jam when there is no paper in the paper path at all.
Any ideas?
---
It seems the carriage is getting stuck on a movable plastic clip at the front right end of the unit or is not engaging correctly at the right end. Why would this be happening? | 2015/09/08 | [
"https://superuser.com/questions/969824",
"https://superuser.com",
"https://superuser.com/users/73918/"
] | ### 0xE8 and later 0xEA codes
>
> There is a blue tape on the interior that needs to be removed- once I did this it worked fine.
>
>
>
...
>
> I had the same issue: 0xE8 and later 0xEA codes. I could see that it
> was the white moving clip under the ink tank holder when on the far
> right that was catching it. The ONLY thing that fixed it was: once it
> made a noise and errored I unwillingly pushed the tank holder over to
> the left until the tanks pushed past the white clip and all the way to
> the left..
>
>
> Then there were no more errors.
>
>
>
Source [0xE8 and later 0xEA codes](http://www.askmefast.com/Epson_wf3620__need_resolution_for_error_code_0xE8-qna8892260.html#q6764814)
---
### 520 FATAL CODE:0xF1 EPSON Workforce
>
> This relates to the print head not being able to completely pass from the left to right side during startup. I had a plastic carriage on the one side that was stuck in a position that stop the carriage from make the complete run from side to side. When I forced the plastic carriage down and it clicked into place the error stopped and the printer started up normally with no codes.
>
>
> If anything is causing the print head to not travel completely from left to right during startup, this will probable cause the code. It will be hard to see if the print head is being obstructed if you don't remove the sides.
>
>
>
Source [520 FATAL CODE:0xF1 EPSON Workforce](http://hpprintermanual.blogspot.co.uk/2013/03/520-fatal-code0xf1-epson-workforce.html)
---
### Print Error Code0xE3 and 0xEA
>
> We have seen some success with this issue by following these
> instructions. Please try this procedure one more time using the
> instructions below.
>
>
> 1. Turn the printer off, then disconnect the power and the interface cable. Open the cover and check for any torn or jammed paper
> and remove it.
> 2. Reconnect the power cable and turn the printer back on.
> 3. Press the Copy button and see if the unit responds.
>
>
> Note: Also check that the ink cartridges and lids are pushed down
> fully.
>
>
> If the issue persists, the hardware itself is malfunctioning and will
> require service
>
>
>
Source [Print Error Code0xE3 and 0xEA](http://www.fixya.com/support/t25141495-print_error_code0xe3_0xea) | Had 0xF1 and 0x69 errors on our Epson. Solved 0xF1 by discovering the lever on the ink carriage was open and required closing, then rebooting the machine.
0x69 was solved by re-seating the ink cartridges.
Not a good start for a brand new printer. |
969,824 | I'm trying to set up a brand-new Epson WorkForce WF-3640 printer and it seems there are some weird mechanical issues. It would seem the carriage is not moving freely. This is *before* I get to install the ink cartridges.
The printer may make a loud grinding noise and return errors 0xF1, 0xEA, 0xE8, or 0xE1. Alternatively, the printer may report a paper jam when there is no paper in the paper path at all.
Any ideas?
---
It seems the carriage is getting stuck on a movable plastic clip at the front right end of the unit or is not engaging correctly at the right end. Why would this be happening? | 2015/09/08 | [
"https://superuser.com/questions/969824",
"https://superuser.com",
"https://superuser.com/users/73918/"
] | Epson technical support stated that this is a hardware failure. Standard troubleshooting steps have not produced a solution.
The printer is being replaced under warranty.
---
**Update:** The replacement printer has been set up and is fully operational. Well, defective product is defective... | Same error code 0xEA for WF-3640 received today.
...multiple attempts to clear it, but each time (after I finally got the carriage to go to the left), the carriage returned to the right, locked up, and error'd out.
Called Epson...cycled through the same process, even sent them a picture of the l-shaped bracket (for whatever they needed to look at)...tried again, and...surprise the same error occurred. They finally stated "hardware error", please return it to the place of purchase for a replacement. This is the first Epson in 20+ years...have had nothing but Canons and first one out of the box...it's really a shame. Hopefully the warranty replacement will be happier. |
969,824 | I'm trying to set up a brand-new Epson WorkForce WF-3640 printer and it seems there are some weird mechanical issues. It would seem the carriage is not moving freely. This is *before* I get to install the ink cartridges.
The printer may make a loud grinding noise and return errors 0xF1, 0xEA, 0xE8, or 0xE1. Alternatively, the printer may report a paper jam when there is no paper in the paper path at all.
Any ideas?
---
It seems the carriage is getting stuck on a movable plastic clip at the front right end of the unit or is not engaging correctly at the right end. Why would this be happening? | 2015/09/08 | [
"https://superuser.com/questions/969824",
"https://superuser.com",
"https://superuser.com/users/73918/"
] | Epson technical support stated that this is a hardware failure. Standard troubleshooting steps have not produced a solution.
The printer is being replaced under warranty.
---
**Update:** The replacement printer has been set up and is fully operational. Well, defective product is defective... | Had 0xF1 and 0x69 errors on our Epson. Solved 0xF1 by discovering the lever on the ink carriage was open and required closing, then rebooting the machine.
0x69 was solved by re-seating the ink cartridges.
Not a good start for a brand new printer. |
43,830,633 | How create query with using CriteriaQuery and EntityManager for this SQL query:
```
SELECT * FROM user WHERE user.login = '?' and user.password = '?'
```
I try so:
```
final CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();
final CriteriaQuery<User> criteriaQuery = criteriaBuilder.createQuery(User.class);
Root<User> root = criteriaQuery.from(User.class);
criteriaQuery.select(root);
criteriaQuery.where(criteriaBuilder.gt(root.get("login"), userLogin));
return getEntityManager().createQuery(criteriaQuery).getResultList().get(0);
``` | 2017/05/07 | [
"https://Stackoverflow.com/questions/43830633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7785247/"
] | Your code looks like it's on the right track, except that it only has one `WHERE` condition, which does not agree with your raw SQL query, which has two conditions.
```
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<User> q = cb.createQuery(User.class);
Root<User> c = q.from(User.class);
q.select(c);
ParameterExpression<String> p1 = cb.parameter(String.class);
ParameterExpression<String> p2 = cb.parameter(String.class);
q.where(
cb.equal(c.get("login"), p1),
cb.equal(c.get("password"), p2)
);
return em.createQuery(q).getResultList().get(0);
```
As a side note, in real life you would typically *not* be storing raw user passwords in your database. Rather, you be storing a salted and encrypted password. So hopefully your actual program is not storing raw passwords. | This worked for me in the end was this:
```
entityManager.getTransaction().begin();
CriteriaQuery<Object> criteriaQuery = criteriaBuilder.createQuery();
Root<Profile> fromRoot = criteriaQuery.from(Profile.class);
criteriaQuery.select(fromRoot);
criteriaQuery.where(criteriaBuilder.equal(fromRoot.get("userName"), username),
criteriaBuilder.equal(fromRoot.get("password"), password));
List<Object> resultList = entityManager.createQuery(criteriaQuery).getResultList();
Profile dbProfile = null;
if (resultList.isEmpty()) {
// Handle Error
} else {
dbProfile = (Profile) resultList.get(0);
}
entityManager.getTransaction().commit();
``` |
53,452,937 | While reading a csv file with PHP a problem occured with a line break within the CSV file. The contents of one cell will be split once a comma is followed by a line break:
```
$csv = array_map('str_getcsv', file($file));
first,second,"third,
more,text","forth"
next,dataset
```
This will result in:
```
1) first | second | third
2) more text | forth
3) next | dataset
```
While it should result in:
```
1) first | second | third more text | forth
2) next | dataset
```
Is this a bug within str\_getcsv? | 2018/11/23 | [
"https://Stackoverflow.com/questions/53452937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/547262/"
] | Don't do that, use [`fgetcsv()`](https://secure.php.net/manual/en/function.fgetcsv.php). You're having problems because `file()` doesn't care about the string encapsulation in your file.
```
$fh = fopen('file.csv', 'r');
while( $line = fgetcsv($fh) ) {
// do a thing
}
fclose($fh);
```
<https://secure.php.net/manual/en/function.fgetcsv.php>
And try not to store all the lines into an array before performing your operations if you can help it. Your system's memory usage will thank you. | ```
<?php
$csvString = "ID,Condition,Condition,Condition,Condition,AdSize,Content:Text,Content:Text,Content:Text,Content:ImageUrl,Content:LandingPageUrl,Archive,Default
ID,Locations:Region,Device Properties:Device,Weather:Condition,Dmp:Liveramp,AdSize,title1,description1,price1,imageUrl1,landingPageUrl1,Archive,Default
ROW_001,\"Wa, Ca, Tn\",Mobile,Snow,12345,300x250,Hello Washingtonian,My Custom Description,10,http://domain/Snow.jpg,https://www.example.com,TRUE,
ROW_002,Wa,Mobile,Snow,12345,300x250,Hello Washingtonian,My Custom Description,10,http://domain/New_Snow.jpg,https://www.example.com,,
ROW_003,Wa,Mobile,,,300x250,Hello Washingtonian,My Custom Description,10,http://domain/clear.jpg,https://www.example.com,,
ROW_004,,,,,300x250,Hello,My Custom Description,20,http://domain/clear.jpg,https://www.example.com,,TRUE";
function csvToArray($csvString, $delimiter = ',', $lineBreak = "\n") {
$csvArray = [];
$rows = str_getcsv($csvString, $lineBreak); // Parses the rows. Treats the rows as a CSV with \n as a delimiter
foreach ($rows as $row) {
$csvArray[] = str_getcsv($row, $delimiter); // Parses individual rows. Now treats a row as a regular CSV with ',' as a delimiter
}
return $csvArray;
}
print_r(csvToArray($csvString));
```
**<https://gist.github.com/sul4bh/d392315c7049abd86916e077707bf123>** |
50,488,474 | The data source passed to a report has a `Serial` property, I need to write a field in this format for every details section: [Serial] from [Top serial]
I wrote this formula for the top serial:
```
Maximum({VW_Sizes.Serial})
```
but it gets the current serial, so instead of : 1 of 2, 2 of 2
It gets 1 of 1, 2 of 2. | 2018/05/23 | [
"https://Stackoverflow.com/questions/50488474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6197785/"
] | The problem you are running into is that when each iteration of the details section prints to the report, it only knows the Max value for SERIAL for the rows that have already printed to the report.
I prefer to use a SQL Expression Field to get around this issue. This allows you to use a SQL query to retrieve the maximum value of SERIAL for the grouped data before all of the rows are printed to the report.
Something like this usually works for me.
```
(
SELECT MAX("ORD_DETAIL"."ORD_DET_SEQNO")
FROM ORD_DETAIL
WHERE "ORD_DETAIL"."ORDERS_ID" = "ORDERS"."ID"
)
```
In my example, I have two tables, `ORDERS` and `ORD_DETAIL`. `ORD_DETAIL.ORD_DET_SEQNO` contains the sequence numbers of order detail rows. My data is grouped on `ORDERS.ID` to iterate through each Order and the following formula field would print an output for each detail line that indicates its sequence out of the maximum value of all sequence numbers for that order.
```
ToText({ORD_DETAIL.ORD_DET_SEQNO}) + " of " + ToText({%Max});
```
In this formula, `%Max` is the name of the SQL Expression Field in the example above.
If you have no point in your data where the SERIAL number resets, then your SQL Expression Field would look like this.
```
(
SELECT MAX(Serial)
FROM VW_Sizes
)
```
If you need a reset at certain points, simply add a WHERE clause that references the table.column that is used to group a set of SERIAL values. | You can concatenate that variable in a *Formula Field* inside your detail section with a content about this:
```
{VW_Sizes.Serial} & " from " & Maximum ({VW_Sizes.Serial})
```
otherwise you only can put a summary field with the maximum value outside the detail section, for example in *Grand Total (Report Footer)*. |
50,488,474 | The data source passed to a report has a `Serial` property, I need to write a field in this format for every details section: [Serial] from [Top serial]
I wrote this formula for the top serial:
```
Maximum({VW_Sizes.Serial})
```
but it gets the current serial, so instead of : 1 of 2, 2 of 2
It gets 1 of 1, 2 of 2. | 2018/05/23 | [
"https://Stackoverflow.com/questions/50488474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6197785/"
] | You can concatenate that variable in a *Formula Field* inside your detail section with a content about this:
```
{VW_Sizes.Serial} & " from " & Maximum ({VW_Sizes.Serial})
```
otherwise you only can put a summary field with the maximum value outside the detail section, for example in *Grand Total (Report Footer)*. | i think there is an easier way to do something like that, from the report you need to create running field from the field explorer :
* set field name e.g. (max\_Serial)
* select your field to summarize.
* after selecting your field crystal report provides multiple types of summary according to field data type.
* select maximum and reset according to your requirement e.g. after each group. |
50,488,474 | The data source passed to a report has a `Serial` property, I need to write a field in this format for every details section: [Serial] from [Top serial]
I wrote this formula for the top serial:
```
Maximum({VW_Sizes.Serial})
```
but it gets the current serial, so instead of : 1 of 2, 2 of 2
It gets 1 of 1, 2 of 2. | 2018/05/23 | [
"https://Stackoverflow.com/questions/50488474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6197785/"
] | The problem you are running into is that when each iteration of the details section prints to the report, it only knows the Max value for SERIAL for the rows that have already printed to the report.
I prefer to use a SQL Expression Field to get around this issue. This allows you to use a SQL query to retrieve the maximum value of SERIAL for the grouped data before all of the rows are printed to the report.
Something like this usually works for me.
```
(
SELECT MAX("ORD_DETAIL"."ORD_DET_SEQNO")
FROM ORD_DETAIL
WHERE "ORD_DETAIL"."ORDERS_ID" = "ORDERS"."ID"
)
```
In my example, I have two tables, `ORDERS` and `ORD_DETAIL`. `ORD_DETAIL.ORD_DET_SEQNO` contains the sequence numbers of order detail rows. My data is grouped on `ORDERS.ID` to iterate through each Order and the following formula field would print an output for each detail line that indicates its sequence out of the maximum value of all sequence numbers for that order.
```
ToText({ORD_DETAIL.ORD_DET_SEQNO}) + " of " + ToText({%Max});
```
In this formula, `%Max` is the name of the SQL Expression Field in the example above.
If you have no point in your data where the SERIAL number resets, then your SQL Expression Field would look like this.
```
(
SELECT MAX(Serial)
FROM VW_Sizes
)
```
If you need a reset at certain points, simply add a WHERE clause that references the table.column that is used to group a set of SERIAL values. | i think there is an easier way to do something like that, from the report you need to create running field from the field explorer :
* set field name e.g. (max\_Serial)
* select your field to summarize.
* after selecting your field crystal report provides multiple types of summary according to field data type.
* select maximum and reset according to your requirement e.g. after each group. |
189,160 | I want to include an image that contains 4-5 graphs from diverse sources next to each other, in order to illustrate their similarities. Since I do not own any of those images I want to include, how do I properly cite them? | 2022/09/28 | [
"https://academia.stackexchange.com/questions/189160",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/163127/"
] | I'd suggest no link at all for several reasons. Most important is that you don't want the reader to go off somewhere else while reading your SoP. You want them to focus on what you write.
Also, as you note, you don't know how the SoP will be read (paper, electronic...). And, you probably have a word limit and might find a better use for the few words it would take for the link.
You should consider that such statements are likely to be viewed, at least in part, as examples of your writing.
A commercial site (Amazon,...) would probably be incorrect.
I would only consider it if the work were obscure. It is likely however, that if it is important to what you say, then others in the field can probably find it easily enough. | From my experience, only mention it in the PS if that book is truly important for your development (Do you have a good reason to justify that to yourself?). If the book is popular, it is probably unnecessary to provide extra information on the details of the book. If it is obscure, as Buffy answered, it is not a terrible idea to mention the details in the essay. However, you have to take into account that you only have limited space for the PS. You have more to say than what you have learnt from a book. The committee has limited time for each applicant too and probably will not look at it.
It is better if you can provide evidence that you truly learnt something from the book, and produced something as the direct result of reading the book. In fact, that was what I did. The course I wanted to take was not available, so I instead bought an advanced book for that course, self-studied, built a small project based on what I learnt and rewrote code for all algorithms in the book in another programming language. I mentioned it in "**Miscellaneous**" section of my CV instead.
Also, it is good to have some other supplement documents. |
16,126,290 | I need to be able to check if a variable exists (if if it doesn't assign it to {}) without throwing an error in javascript. When I try this code
```
if (a) {}
```
it throws uncaughtReferenceError
What I really want to do is something like this without throwing an error:
```
a = a || {}
```
or maybe it looks like this
```
if (a) { a = {} }
``` | 2013/04/20 | [
"https://Stackoverflow.com/questions/16126290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2303307/"
] | ```
if (typeof a === 'undefined'){
// variable is not available and you can write a = {}
}
```
but `a = a || {}` is shortly | ```
a = a || {}
```
simply won't work, because `a` is not defined. But you can use `typeof` to check if it exists or not.
```
a = (typeof(a) === 'undefined' ? {} : a);
``` |
16,126,290 | I need to be able to check if a variable exists (if if it doesn't assign it to {}) without throwing an error in javascript. When I try this code
```
if (a) {}
```
it throws uncaughtReferenceError
What I really want to do is something like this without throwing an error:
```
a = a || {}
```
or maybe it looks like this
```
if (a) { a = {} }
``` | 2013/04/20 | [
"https://Stackoverflow.com/questions/16126290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2303307/"
] | If `a` is a global, you can use the *global object* to avoid the error. In browsers, that object is `window`:
```
window.a = window.a || {};
```
Or, as Ozerich suggested, you can use [`typeof`](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/typeof), which won't throw reference errors:
```
if (typeof a === 'undefined') {
a = {};
}
``` | ```
a = a || {}
```
simply won't work, because `a` is not defined. But you can use `typeof` to check if it exists or not.
```
a = (typeof(a) === 'undefined' ? {} : a);
``` |
27,216,645 | I'm looking into ways of deploying my application (web / DB / application tier) across multiple hosts while utilizing Chef. What I've come up with is **using Chef recipes to represent each step of the deployment as an individual node state**. For example if there is a step that handles the stopping of X daemons & monitoring, it could be written as a chef recipe that simply expects the specific X daemons to be stopped.
In the same way, the deployment step that moves an artifact from a shared location to the web root could also be referenced as a chef recipe that represents that specific state of the node (having the artifact copied from point A to point B).
The whole deployment process will consist of various steps that basically do these three things:
1. Modify the run list of the nodes depending on the current deployment
step.
2. Have chef-client run on each node
3. Log any failures and allow for a repeat of the chef run on the failed nodes or the skipping of the step so the deployment can continue.
Questions:
* Is using Chef in such a way (constantly modifying the run list of my nodes in order to alter the node state) a bad practice? And if so why?
* What are the best ways to orchestrate all this? I can use any kind of CI tools there, but I'm having trouble figuring out how to capture the output of chef-client and be able to repeat or ignore the chef-client runs on specific nodes. | 2014/11/30 | [
"https://Stackoverflow.com/questions/27216645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1906965/"
] | This is really not the kind of thing Chef is best for. Chef excels at convergent configuration, less so with the procedural bits. Use Chef for handling the parts where you do a convergent change like deploying new code or rewriting config files, use a procedural tool for the other bits.
As for tools to coordinate this, RunDeck is one choice if you want something more service-y. If you want a command-line tool look at Fabric or maybe Capistrano. Personally I use a mix, RunDeck plus Fabric to get the best of both. Some other less complete options include Chef Push Jobs, Mcollective, and Saltstack. | Puppet and Chef are not orchestration tools and they do a very bad job from this perspective. They were not designed to be orchestration and even though some parties with specific interests are pushing the boundaries of the definition of orchestration to get Chef to be considered for orchestration, they are ignoring critical facts/needs. Unfortunately, I am not aware of a single serious solution for orchestration of large environments - most of the tools are quite specific to some needs and some are really not production ready yet. I had to invent my own workarounds to get this done but there was nothing elegant in doing so. |
26,251,429 | In a form I've 3 subgrids with N:N relation which point on the same entity (but don't display the same view).
When I create only 1 of theses subgrids, I've correctly the addbutton and I can add records in my subgrids.
But when I've more than 1 subgrid, the + button in each subgrids (and all the button like edit etc which are in the subgrid's command bar) are hidden...
I guess that the problem is that I've 3 times the same N:N relations for my subgrids in the same form, but I don't figure out why it's a problem and I don't know how can I make the + buttons visibles...
Could you help me? | 2014/10/08 | [
"https://Stackoverflow.com/questions/26251429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4120191/"
] | Hide it -
```
v.findViewById(R.id.links_bar).setVisibility(View.GONE);
```
show it again with -
```
v.findViewById(R.id.links_bar).setVisibility(View.VISIBLE);
```
or `numero_info <=0` is never `= true` | I assume you want to show/hide views from the layout.
You have correctly used setVisibility() method but FYI there are 3 attributes you can use with it:
* View.VISIBLE - which makes item visible and stays there in layout
* View.INVISIBLE - which makes item invisible but stays there in layout
* View.GONE - whic makes item invisible and remove it's presence/space from layout.
So if you would want to complete hide the view then use GONE otherwise INVISIBLE. |
26,251,429 | In a form I've 3 subgrids with N:N relation which point on the same entity (but don't display the same view).
When I create only 1 of theses subgrids, I've correctly the addbutton and I can add records in my subgrids.
But when I've more than 1 subgrid, the + button in each subgrids (and all the button like edit etc which are in the subgrid's command bar) are hidden...
I guess that the problem is that I've 3 times the same N:N relations for my subgrids in the same form, but I don't figure out why it's a problem and I don't know how can I make the + buttons visibles...
Could you help me? | 2014/10/08 | [
"https://Stackoverflow.com/questions/26251429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4120191/"
] | I assume you want to show/hide views from the layout.
You have correctly used setVisibility() method but FYI there are 3 attributes you can use with it:
* View.VISIBLE - which makes item visible and stays there in layout
* View.INVISIBLE - which makes item invisible but stays there in layout
* View.GONE - whic makes item invisible and remove it's presence/space from layout.
So if you would want to complete hide the view then use GONE otherwise INVISIBLE. | Here is an example of mine I use for animating.
Java
```
if (mIsVisibleAfter) {
mAnimatedView.setVisibility(View.Visible);
}
```
XML
```
<RelativeLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/member_name"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="@+id/hiddenlay"
android:visibility="gone"
android:weightSum="1">
<TextView
android:id="@+id/desctv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="15dp"
android:textSize="17sp"
android:text="Descr"
android:layout_weight="0.13"
android:layout_toLeftOf="@+id/kind"
android:textColor="#666666"
android:visibility="visible"
android:layout_marginLeft="10dp" />
<TextView
android:id="@+id/kind"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Kind "
android:padding="15dp"
android:textSize="17sp"
android:textStyle="bold"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:visibility="gone" />
</RelativeLayout>
```
I hope it helps |
26,251,429 | In a form I've 3 subgrids with N:N relation which point on the same entity (but don't display the same view).
When I create only 1 of theses subgrids, I've correctly the addbutton and I can add records in my subgrids.
But when I've more than 1 subgrid, the + button in each subgrids (and all the button like edit etc which are in the subgrid's command bar) are hidden...
I guess that the problem is that I've 3 times the same N:N relations for my subgrids in the same form, but I don't figure out why it's a problem and I don't know how can I make the + buttons visibles...
Could you help me? | 2014/10/08 | [
"https://Stackoverflow.com/questions/26251429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4120191/"
] | Hide it -
```
v.findViewById(R.id.links_bar).setVisibility(View.GONE);
```
show it again with -
```
v.findViewById(R.id.links_bar).setVisibility(View.VISIBLE);
```
or `numero_info <=0` is never `= true` | You can use the option GONE instead of INVISIBLE.
A good option is to define it in XML as GONE and when you need it make it visible.
```
<ListView
android:id="@+id/links_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone" />
``` |
26,251,429 | In a form I've 3 subgrids with N:N relation which point on the same entity (but don't display the same view).
When I create only 1 of theses subgrids, I've correctly the addbutton and I can add records in my subgrids.
But when I've more than 1 subgrid, the + button in each subgrids (and all the button like edit etc which are in the subgrid's command bar) are hidden...
I guess that the problem is that I've 3 times the same N:N relations for my subgrids in the same form, but I don't figure out why it's a problem and I don't know how can I make the + buttons visibles...
Could you help me? | 2014/10/08 | [
"https://Stackoverflow.com/questions/26251429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4120191/"
] | You can use the option GONE instead of INVISIBLE.
A good option is to define it in XML as GONE and when you need it make it visible.
```
<ListView
android:id="@+id/links_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone" />
``` | Here is an example of mine I use for animating.
Java
```
if (mIsVisibleAfter) {
mAnimatedView.setVisibility(View.Visible);
}
```
XML
```
<RelativeLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/member_name"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="@+id/hiddenlay"
android:visibility="gone"
android:weightSum="1">
<TextView
android:id="@+id/desctv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="15dp"
android:textSize="17sp"
android:text="Descr"
android:layout_weight="0.13"
android:layout_toLeftOf="@+id/kind"
android:textColor="#666666"
android:visibility="visible"
android:layout_marginLeft="10dp" />
<TextView
android:id="@+id/kind"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Kind "
android:padding="15dp"
android:textSize="17sp"
android:textStyle="bold"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:visibility="gone" />
</RelativeLayout>
```
I hope it helps |
26,251,429 | In a form I've 3 subgrids with N:N relation which point on the same entity (but don't display the same view).
When I create only 1 of theses subgrids, I've correctly the addbutton and I can add records in my subgrids.
But when I've more than 1 subgrid, the + button in each subgrids (and all the button like edit etc which are in the subgrid's command bar) are hidden...
I guess that the problem is that I've 3 times the same N:N relations for my subgrids in the same form, but I don't figure out why it's a problem and I don't know how can I make the + buttons visibles...
Could you help me? | 2014/10/08 | [
"https://Stackoverflow.com/questions/26251429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4120191/"
] | Hide it -
```
v.findViewById(R.id.links_bar).setVisibility(View.GONE);
```
show it again with -
```
v.findViewById(R.id.links_bar).setVisibility(View.VISIBLE);
```
or `numero_info <=0` is never `= true` | Here is an example of mine I use for animating.
Java
```
if (mIsVisibleAfter) {
mAnimatedView.setVisibility(View.Visible);
}
```
XML
```
<RelativeLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/member_name"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="@+id/hiddenlay"
android:visibility="gone"
android:weightSum="1">
<TextView
android:id="@+id/desctv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="15dp"
android:textSize="17sp"
android:text="Descr"
android:layout_weight="0.13"
android:layout_toLeftOf="@+id/kind"
android:textColor="#666666"
android:visibility="visible"
android:layout_marginLeft="10dp" />
<TextView
android:id="@+id/kind"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Kind "
android:padding="15dp"
android:textSize="17sp"
android:textStyle="bold"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:visibility="gone" />
</RelativeLayout>
```
I hope it helps |
40,250,590 | I want to Partition the input number to use its ciphers.
For example, I have an input number : 1563
How can I separate 1, 5, 6 and 3 and use them as separate integers?
```
package todicemal;
public class um {
public static void main(String[] args) {
// TODO Auto-generated method stub
int k=1563;
System.out.println(k);
}
}
```
How can I use the parts of k which form 1563 and use every single cipher as an integer? | 2016/10/25 | [
"https://Stackoverflow.com/questions/40250590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7061863/"
] | Here's a simple and more elegant way of what you're trying to do.
First, simplify your function (if your'e going to be using it in a pipe, it doesn't need to take the entire df as an argument):
```
fun.rb <- function(estimate, baseline){
(estimate-baseline)/(baseline)*100
}
```
Now, all you need to do is create the baseline column, and then call your function for each row, passing in the estimate and baseline columns to your function:
```
df <- df %>%
group_by(site,group) %>%
mutate(baseline = estimate[method=="method0"], rb = fun.rb(estimate, baseline))
``` | This may not be the most elegant. I'm just a hack. But I think it does what you want.
```
> library(dplyr)
> newdf <- df %>% filter(method=="method0") %>%
+ rename(method0_value = estimate) %>%
+ select(-method)
> head(newdf)
site group method0_value
1 A group1 2.529237
2 B group2 7.863411
```
This data set would contain all your baseline/control values.
The next bit of code merges it back to your initial dataframe and creates the variable you want. You could then remove the method0\_value if you wanted to. It is a nice check.
```
> finaldf <- left_join(df,newdf,by=c("site","group")) %>%
+ mutate(rb= (estimate/method0_value)*100)
> head(finaldf)
site group estimate method method0_value rb
1 A group1 8.928171 method1 2.529237 352.9986
2 A group1 11.171023 method1 2.529237 441.6757
3 A group1 10.790150 method1 2.529237 426.6169
4 A group1 8.990635 method1 2.529237 355.4683
5 A group1 14.813661 method1 2.529237 585.6969
6 A group1 14.518803 method1 2.529237 574.0390
```
I know there are ways of doing this that might be more efficient, but I'm still a noob. |
13,547,367 | I have a question about Safety. I have a Javascript variable:
```
var toSearch = "something"
```
I want to send this variable to another php page. I'm using sessions: `<?php session_start(); ?>`
From what I've read I need to use a AJAX GET/POST procedure to pass this javascript client side variable to PHP server side.
I know it's possible to do this with:
```
window.location.href = "myphpfile.php?name=" + javascriptVariable;
```
then `$_GET['name']` the variable. I've read that this isn't safe? Is it? | 2012/11/25 | [
"https://Stackoverflow.com/questions/13547367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1850432/"
] | It's only unsafe depending on what you do with it. Anyone can type whatever they like in the address bar, and you have no control over that. For instance, I could go to
```
http://example.com/myphpfile.php?name=fuzzball
```
Now, that's not a danger in itself, but if I were to put some MySQL code and you were placing this directly in a MySQL database with no sanitisation, then it's dangerous. If I put in HTML which you then display to other users, then it's dangerous.
All you have to do is remember that while GET and POST aren't dangerous, they cannot be trusted to be what you expect them to be, therefore you should make sure that they are on the server side, where it can be trusted. | Well the better solution would be to go with an ajax request if you dont want to force page reload. regarding security its the same hence every user can manipulate querystrings with ease... we have an address bar for this :)
```
window.XMLHttpRequest = window.XMLHttpRequest || window.ActiveXObject('MSXML2.XMLHTTP') || window.ActiveXObject('Microsoft.XMLHTTP');
var ajax = new XMLHttpRequest();
ajax.open('get', 'page.php?name=' + javascriptVariable, true);
if ( ajax.readyState == 4 && ajax.status == 200 )
{
// ajax.responseText is the result from php server
// ajax.responseXML is the result from php server
}
ajax.send(null);
``` |
13,547,367 | I have a question about Safety. I have a Javascript variable:
```
var toSearch = "something"
```
I want to send this variable to another php page. I'm using sessions: `<?php session_start(); ?>`
From what I've read I need to use a AJAX GET/POST procedure to pass this javascript client side variable to PHP server side.
I know it's possible to do this with:
```
window.location.href = "myphpfile.php?name=" + javascriptVariable;
```
then `$_GET['name']` the variable. I've read that this isn't safe? Is it? | 2012/11/25 | [
"https://Stackoverflow.com/questions/13547367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1850432/"
] | It's only unsafe depending on what you do with it. Anyone can type whatever they like in the address bar, and you have no control over that. For instance, I could go to
```
http://example.com/myphpfile.php?name=fuzzball
```
Now, that's not a danger in itself, but if I were to put some MySQL code and you were placing this directly in a MySQL database with no sanitisation, then it's dangerous. If I put in HTML which you then display to other users, then it's dangerous.
All you have to do is remember that while GET and POST aren't dangerous, they cannot be trusted to be what you expect them to be, therefore you should make sure that they are on the server side, where it can be trusted. | If you are not good with JavaScript or Ajax requests, I suggest the jquery .ajax method. jQuery is really well-documented and great for beginners.
Also, your variable is not set properly. Should be:
```
var toSearch = "something";
```
So visit: <http://api.jquery.com/jQuery.ajax/> to get started.
A sample of how to do this.
JS:
```
function myFunction() {
var toSearch = "something";
$.ajax({
url: 'mysite/action_page.php?toSearch=' + toSearch,
success: function(data) {
alert('Here is some data from the $_GET request: ' + data);
}
});
}
```
PHP:
```
<?php
/**
* I strongly suggest a security measure here
* ie: if($_GET['token'] != $_SESSION['token']) die('access not permitted');
*/
//init
$search_string = '';
//set
$search_string = htmlspecialchars(trim($_GET['toString']), ENT_QUOTES);
//TAKE A LOOK AT PHP.net IF YOU DON'T KNOW WHAT THE TWO METHODS ABOVE DO.
// will help prevent xss
echo $search_string;
//all done!
?>
``` |
13,547,367 | I have a question about Safety. I have a Javascript variable:
```
var toSearch = "something"
```
I want to send this variable to another php page. I'm using sessions: `<?php session_start(); ?>`
From what I've read I need to use a AJAX GET/POST procedure to pass this javascript client side variable to PHP server side.
I know it's possible to do this with:
```
window.location.href = "myphpfile.php?name=" + javascriptVariable;
```
then `$_GET['name']` the variable. I've read that this isn't safe? Is it? | 2012/11/25 | [
"https://Stackoverflow.com/questions/13547367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1850432/"
] | Well the better solution would be to go with an ajax request if you dont want to force page reload. regarding security its the same hence every user can manipulate querystrings with ease... we have an address bar for this :)
```
window.XMLHttpRequest = window.XMLHttpRequest || window.ActiveXObject('MSXML2.XMLHTTP') || window.ActiveXObject('Microsoft.XMLHTTP');
var ajax = new XMLHttpRequest();
ajax.open('get', 'page.php?name=' + javascriptVariable, true);
if ( ajax.readyState == 4 && ajax.status == 200 )
{
// ajax.responseText is the result from php server
// ajax.responseXML is the result from php server
}
ajax.send(null);
``` | If you are not good with JavaScript or Ajax requests, I suggest the jquery .ajax method. jQuery is really well-documented and great for beginners.
Also, your variable is not set properly. Should be:
```
var toSearch = "something";
```
So visit: <http://api.jquery.com/jQuery.ajax/> to get started.
A sample of how to do this.
JS:
```
function myFunction() {
var toSearch = "something";
$.ajax({
url: 'mysite/action_page.php?toSearch=' + toSearch,
success: function(data) {
alert('Here is some data from the $_GET request: ' + data);
}
});
}
```
PHP:
```
<?php
/**
* I strongly suggest a security measure here
* ie: if($_GET['token'] != $_SESSION['token']) die('access not permitted');
*/
//init
$search_string = '';
//set
$search_string = htmlspecialchars(trim($_GET['toString']), ENT_QUOTES);
//TAKE A LOOK AT PHP.net IF YOU DON'T KNOW WHAT THE TWO METHODS ABOVE DO.
// will help prevent xss
echo $search_string;
//all done!
?>
``` |
33,354 | I am the owner of a Google Group. I am using the new interface. The group is a public group and is available at <https://groups.google.com/forum/?fromgroups=&nomobile=true#!forum/sr-api>.
I cannot find a way to subscribe to new posts using an RSS reader. I have done some googling and it seems that the new Google Groups does not support RSS feeds. Have anyone found a way to get an RSS feed from the new Google Groups? | 2012/10/17 | [
"https://webapps.stackexchange.com/questions/33354",
"https://webapps.stackexchange.com",
"https://webapps.stackexchange.com/users/25097/"
] | You can find it here:
<https://groups.google.com/group/sr-api/about?noredirect>
The link is currently missing from the About page in the new Group groups. | Combining answers by [Rich Feit](https://webapps.stackexchange.com/a/33390/30592) and [vishvAs vAsuki](https://webapps.stackexchange.com/a/41045/30592), the about page for your project is reached via
<https://groups.google.com/group/sr-api/about?noredirect> please replace `sr-api` with your group
This will lead to links like:
[**https://groups.google.com/forum/feed/sr-api/msgs/rss.xml?num=50**](https://groups.google.com/forum/feed/sr-api/msgs/rss.xml?num=50)(again, replacing `sr-api`)
from the about page, which anyway, as of 2014, looks like this:

(the end) |
44,567,580 | I'm writing a custom control that inherits ItemsControl. I need to call a method whenever certain properties change. For my own dependency properties I can call this in the setter no problem, but for inherited ones like ItemsSource I don't know how to do this and I'd like to learn how without overriding the whole thing.
When searching for this I saw [mention](https://stackoverflow.com/questions/834929/silverlight-how-to-receive-notification-of-a-change-in-an-inherited-dependencyp/1835068) that this could be done with OverrideMetadata in WPF at least (my project is UWP). I see how OverrideMetadata is used to change the default value, but I don't see how it can be used as a property changed notification. | 2017/06/15 | [
"https://Stackoverflow.com/questions/44567580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5357729/"
] | There's a new method in UWP called `RegisterPropertyChangedCallback` designed just for this. For example, the following is how I remove the default entrance transition in an extended `GridView` control.
```
// Remove the default entrance transition if existed.
RegisterPropertyChangedCallback(ItemContainerTransitionsProperty, (s, e) =>
{
var entranceThemeTransition = ItemContainerTransitions.OfType<EntranceThemeTransition>().SingleOrDefault();
if (entranceThemeTransition != null)
{
ItemContainerTransitions.Remove(entranceThemeTransition);
}
})
```
You can un-register using `UnregisterPropertyChangedCallback`.
More information can be found [here](https://learn.microsoft.com/en-us/uwp/api/windows.ui.xaml.dependencyobject). | For the `ItemsSource` property you could just override the `OnItemsSourceChanged` method but for any other dependency property you could use a `DependencyPropertyDescriptor`:
```
public class MyItemsControl : ItemsControl
{
public MyItemsControl()
{
DependencyPropertyDescriptor dpd = DependencyPropertyDescriptor
.FromProperty(ItemsControl.ItemsSourceProperty, typeof(ItemsControl));
if (dpd != null)
{
dpd.AddValueChanged(this, OnMyItemsSourceChange);
}
}
private void OnMyItemsSourceChange(object sender, EventArgs e)
{
//...
}
}
```
That goes for WPF. In a UWP app you should be able to use @Thomas Levesque's `DependencyPropertyWatcher` class: <https://www.thomaslevesque.com/2013/04/21/detecting-dependency-property-changes-in-winrt/> |
70,878,553 | So I'm trying to migrate a table from MySQL to MSSQL (`sql server migration assistant MySQL`), but I get this error:
```
Migrating data...
Analyzing metadata...
Preparing table testreportingdebug.testcase...
Preparing data migration package...
Starting data migration Engine
Starting data migration...
The data migration engine is migrating table '`testreportingdebug`.`testcase`': > [SwMetrics].[testreportingdebug].[testcase], 8855 rows total
Violation of UNIQUE KEY constraint 'testcase$Unique'. Cannot insert duplicate key in object 'testreportingdebug.testcase'. The duplicate key value is (<NULL>, <NULL>).
Errors: Violation of UNIQUE KEY constraint 'testcase$Unique'. Cannot insert duplicate key in object 'testreportingdebug.testcase'. The duplicate key value is (<NULL>, <NULL>).
Completing migration of table `testreportingdebug`.`testcase`...
Migration complete for table '`testreportingdebug`.`testcase`': > [SwMetrics].[testreportingdebug].[testcase], 0 rows migrated (Elapsed Time = 00:00:00:01:352).
Data migration operation has finished.
0 table(s) successfully migrated.
0 table(s) partially migrated.
1 table(s) failed to migrate.
```
I've just copied three rows from my table, and this is what they look like:
```sql
'1', 'Pump# TimeToService', NULL, NULL, 'A general test case comment ...', '0'
'2', 'Config.SlaveMinimumReplyDelay', NULL, NULL, NULL, '0'
'3', 'Config.RESERVED', NULL, NULL, NULL, '0'
```
If you are wondering how the colons in the MySQL table is setup, here you go:
[](https://i.stack.imgur.com/25RDB.png)
Is is because `right, left and comment` can be null?
**DDL of table**
```sql
CREATE TABLE `testcase` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`TestCaseName` varchar(150) DEFAULT NULL,
`Left` int(11) DEFAULT NULL,
`Right` int(11) DEFAULT NULL,
`Comment` text,
`Hidden` tinyint(4) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE KEY `Unique` (`Left`,`Right`)
) ENGINE=InnoDB AUTO_INCREMENT=10580 DEFAULT CHARSET=utf8
``` | 2022/01/27 | [
"https://Stackoverflow.com/questions/70878553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15552128/"
] | There's the [Python debugging console](https://code.visualstudio.com/docs/python/debugging) in VSCode.
When your code stops on a breakpoint, you can click on the debug console button to open an interactive Python console with your current program state loaded in.
[](https://i.stack.imgur.com/nMgsG.png) | This Topic bugged me too, so I opened a [feature](https://github.com/microsoft/vscode-python/issues/19540) request, where someone pointed the Debug-Console out which lets you interact with python at the point, where you're debugging. |
70,878,553 | So I'm trying to migrate a table from MySQL to MSSQL (`sql server migration assistant MySQL`), but I get this error:
```
Migrating data...
Analyzing metadata...
Preparing table testreportingdebug.testcase...
Preparing data migration package...
Starting data migration Engine
Starting data migration...
The data migration engine is migrating table '`testreportingdebug`.`testcase`': > [SwMetrics].[testreportingdebug].[testcase], 8855 rows total
Violation of UNIQUE KEY constraint 'testcase$Unique'. Cannot insert duplicate key in object 'testreportingdebug.testcase'. The duplicate key value is (<NULL>, <NULL>).
Errors: Violation of UNIQUE KEY constraint 'testcase$Unique'. Cannot insert duplicate key in object 'testreportingdebug.testcase'. The duplicate key value is (<NULL>, <NULL>).
Completing migration of table `testreportingdebug`.`testcase`...
Migration complete for table '`testreportingdebug`.`testcase`': > [SwMetrics].[testreportingdebug].[testcase], 0 rows migrated (Elapsed Time = 00:00:00:01:352).
Data migration operation has finished.
0 table(s) successfully migrated.
0 table(s) partially migrated.
1 table(s) failed to migrate.
```
I've just copied three rows from my table, and this is what they look like:
```sql
'1', 'Pump# TimeToService', NULL, NULL, 'A general test case comment ...', '0'
'2', 'Config.SlaveMinimumReplyDelay', NULL, NULL, NULL, '0'
'3', 'Config.RESERVED', NULL, NULL, NULL, '0'
```
If you are wondering how the colons in the MySQL table is setup, here you go:
[](https://i.stack.imgur.com/25RDB.png)
Is is because `right, left and comment` can be null?
**DDL of table**
```sql
CREATE TABLE `testcase` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`TestCaseName` varchar(150) DEFAULT NULL,
`Left` int(11) DEFAULT NULL,
`Right` int(11) DEFAULT NULL,
`Comment` text,
`Hidden` tinyint(4) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE KEY `Unique` (`Left`,`Right`)
) ENGINE=InnoDB AUTO_INCREMENT=10580 DEFAULT CHARSET=utf8
``` | 2022/01/27 | [
"https://Stackoverflow.com/questions/70878553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15552128/"
] | There's the [Python debugging console](https://code.visualstudio.com/docs/python/debugging) in VSCode.
When your code stops on a breakpoint, you can click on the debug console button to open an interactive Python console with your current program state loaded in.
[](https://i.stack.imgur.com/nMgsG.png) | Do you mean the debug console tab? It's usually a tab on the bottom of the VS Code screen.
[](https://i.stack.imgur.com/02fyF.jpg)
Here is a video where it shows how to debug a server written in python and goes over the code using debug console: <https://youtu.be/O2Skmwns6o8?t=424> |
38,731,743 | transition opacity from 0 to 1 is not working. here is my code: <https://jsfiddle.net/ax4aLhjq/19/>
```
//html
<div id="a">
<div style="height:20px"></div>
</div>
//css
#a{
width:200px;
background-color:salmon;
margin:0px;
padding:0px;
height:200px;
overflow: auto;
}
#a .item{
margin:0px 5px;
background-color:teal;
padding:10px;
color:white;
opacity:0;
transition:opacity .5s ease-in-out;
}
//js
function add(){
var div = document.createElement("div");
div.className ="item";
var newtext = document.createTextNode("aa");
div.appendChild(newtext);
document.querySelector("#a").appendChild(div);
var separator = document.createElement("div");
separator.style.height="10px";
document.querySelector("#a").appendChild(separator);
//apply opacity
div.style.opacity=1;
}
setInterval(add,3000);
```
Am I doing something wrong? | 2016/08/02 | [
"https://Stackoverflow.com/questions/38731743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/714211/"
] | I've found the answer here: <https://timtaubert.de/blog/2012/09/css-transitions-for-dynamically-created-dom-elements/>
It appears that when an element is added, repaint is needed and somehow the browser is trying to optimize the computation, and is doing the opacity=0 and opacity=1 in the same cycle.
The solution is to use `getComputedStyle` : <https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle>
>
> " getComputedStyle() in combination with accessing a property value
> actually flushes all pending style changes and forces the layout
> engine to compute our ’s current state"
>
>
>
```
var elem = document.createElement("div");
document.body.appendChild(elem);
// Make the element fully transparent.
elem.style.opacity = 0;
// Make sure the initial state is applied.
window.getComputedStyle(elem).opacity;
// Fade it in.
elem.style.opacity = 1;
``` | **Problem:**
You are setting the `opacity`to `1` the same time you were creating the element.
**Solution:**
You have to delay tha action of showing the element, you need to set the opacity within a timeout to make the animation effect otherwise all elements will be just appended.
You can see this snippet I used a `setTimout`to make the effect of the opacity animation:
```js
//js
function add(){
var div = document.createElement("div");
div.className ="item";
var newtext = document.createTextNode("aa");
div.appendChild(newtext);
document.querySelector("#a").appendChild(div);
var separator = document.createElement("div");
separator.style.height="10px";
document.querySelector("#a").appendChild(separator);
//apply opacity
setTimeout(function(){
div.style.opacity=1;
}, 2000);
}
setInterval(add,1000);
```
```css
//css
#a{
width:200px;
background-color:salmon;
margin:0px;
padding:0px;
height:200px;
overflow: auto;
}
#a .item{
margin:0px 5px;
background-color:teal;
padding:10px;
color:white;
opacity:0;
transition:opacity .5s ease-in-out;
}
```
```html
<div id="a">
<div style="height:20px"></div>
</div>
``` |
38,731,743 | transition opacity from 0 to 1 is not working. here is my code: <https://jsfiddle.net/ax4aLhjq/19/>
```
//html
<div id="a">
<div style="height:20px"></div>
</div>
//css
#a{
width:200px;
background-color:salmon;
margin:0px;
padding:0px;
height:200px;
overflow: auto;
}
#a .item{
margin:0px 5px;
background-color:teal;
padding:10px;
color:white;
opacity:0;
transition:opacity .5s ease-in-out;
}
//js
function add(){
var div = document.createElement("div");
div.className ="item";
var newtext = document.createTextNode("aa");
div.appendChild(newtext);
document.querySelector("#a").appendChild(div);
var separator = document.createElement("div");
separator.style.height="10px";
document.querySelector("#a").appendChild(separator);
//apply opacity
div.style.opacity=1;
}
setInterval(add,3000);
```
Am I doing something wrong? | 2016/08/02 | [
"https://Stackoverflow.com/questions/38731743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/714211/"
] | **Problem:**
You are setting the `opacity`to `1` the same time you were creating the element.
**Solution:**
You have to delay tha action of showing the element, you need to set the opacity within a timeout to make the animation effect otherwise all elements will be just appended.
You can see this snippet I used a `setTimout`to make the effect of the opacity animation:
```js
//js
function add(){
var div = document.createElement("div");
div.className ="item";
var newtext = document.createTextNode("aa");
div.appendChild(newtext);
document.querySelector("#a").appendChild(div);
var separator = document.createElement("div");
separator.style.height="10px";
document.querySelector("#a").appendChild(separator);
//apply opacity
setTimeout(function(){
div.style.opacity=1;
}, 2000);
}
setInterval(add,1000);
```
```css
//css
#a{
width:200px;
background-color:salmon;
margin:0px;
padding:0px;
height:200px;
overflow: auto;
}
#a .item{
margin:0px 5px;
background-color:teal;
padding:10px;
color:white;
opacity:0;
transition:opacity .5s ease-in-out;
}
```
```html
<div id="a">
<div style="height:20px"></div>
</div>
``` | Make a setTimeout like this *window.setTimeout(function(){div.style.opacity=1;},17);*. So the animation will effect next time. |
38,731,743 | transition opacity from 0 to 1 is not working. here is my code: <https://jsfiddle.net/ax4aLhjq/19/>
```
//html
<div id="a">
<div style="height:20px"></div>
</div>
//css
#a{
width:200px;
background-color:salmon;
margin:0px;
padding:0px;
height:200px;
overflow: auto;
}
#a .item{
margin:0px 5px;
background-color:teal;
padding:10px;
color:white;
opacity:0;
transition:opacity .5s ease-in-out;
}
//js
function add(){
var div = document.createElement("div");
div.className ="item";
var newtext = document.createTextNode("aa");
div.appendChild(newtext);
document.querySelector("#a").appendChild(div);
var separator = document.createElement("div");
separator.style.height="10px";
document.querySelector("#a").appendChild(separator);
//apply opacity
div.style.opacity=1;
}
setInterval(add,3000);
```
Am I doing something wrong? | 2016/08/02 | [
"https://Stackoverflow.com/questions/38731743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/714211/"
] | I've found the answer here: <https://timtaubert.de/blog/2012/09/css-transitions-for-dynamically-created-dom-elements/>
It appears that when an element is added, repaint is needed and somehow the browser is trying to optimize the computation, and is doing the opacity=0 and opacity=1 in the same cycle.
The solution is to use `getComputedStyle` : <https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle>
>
> " getComputedStyle() in combination with accessing a property value
> actually flushes all pending style changes and forces the layout
> engine to compute our ’s current state"
>
>
>
```
var elem = document.createElement("div");
document.body.appendChild(elem);
// Make the element fully transparent.
elem.style.opacity = 0;
// Make sure the initial state is applied.
window.getComputedStyle(elem).opacity;
// Fade it in.
elem.style.opacity = 1;
``` | Make a setTimeout like this *window.setTimeout(function(){div.style.opacity=1;},17);*. So the animation will effect next time. |
1,579,306 | They're more noticeable when in maximize windows:
>
> [](https://i.stack.imgur.com/YLX5v.png).
>
>
> | 2020/08/20 | [
"https://superuser.com/questions/1579306",
"https://superuser.com",
"https://superuser.com/users/1209370/"
] | These borders are part of the default Windows 7 windows appearance. Eithe set your border to 0 pixels width or use an alternative style.
Both may require hacks, and will not be limited to just IrfanView | As of Version 4.60 (Release date: 2022-03-18) there is a shortcut that will permit "thin" borders, in a way similar to the original request:
New hotkey: `ALT` + `SHIFT` + `B`: Show thin or normal border (current session only) |
62,233,061 | I've been re-factoring some code and using it to explore how to structure maintainable, flexible, concise code when using Pandas and Numpy. (Usually I only use them briefly, I'm now in a role where I should be aiming to become an ex-spurt.)
One example I came across is a function that can sometimes be called on one column of values, and sometimes called on three columns of values. Vectorised code using Numpy encapsulated it wonderfully. But using it becomes a bit clunky.
How should I "better" write the following function?
```
def project_unit_space_to_index_space(v, vertices_per_edge):
return np.rint((v + 1) / 2 * (vertices_per_edge - 1)).astype(int)
input = np.concatenate(([df['x']], [df['y']], [df['z']]), axis=0)
index_space = project_unit_space_to_index_space(input, 42)
magic_space = some_other_transformation_code(index_space, foo, bar)
df['x_'], df['y_'], df['z_'] = magic_space
```
As written the function can accept one column of data, or many columns of data, and it still works correctly, and speedily.
The return type is the right shape to be passed directly in to another similarly structured function, allowing me to chain functions neatly.
Even assigning the results back to new columns in a dataframe isn't "awful", though it is a little clunky.
But packaging up the inputs as a single `np.ndarray` is very very clunky indeed.
I haven't found any style guides that cover this. They're all over itterrows and lambda expressions, etc. But I found nothing on best practices for encapsulating such logic.
So, how you ***you*** structure the above code?
***EDIT:*** Timings of various options for collating the inputs
```
%timeit test = project_unit_sphere_to_unit_cube(df[['x','y','z']].unstack().to_numpy())
# 1.44 ms ± 57.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit test = project_unit_sphere_to_unit_cube(df[['x','y','z']].to_numpy().T)
# 558 µs ± 6.25 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit test = project_unit_sphere_to_unit_cube(df[['x','y','z']].transpose().to_numpy())
# 817 µs ± 18.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit test = project_unit_sphere_to_unit_cube(np.concatenate(([df['x']], [df['y']], [df['z']]), axis=0))
# 3.46 ms ± 42.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
``` | 2020/06/06 | [
"https://Stackoverflow.com/questions/62233061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/53341/"
] | ```
In [101]: df = pd.DataFrame(np.arange(12).reshape(4,3))
In [102]: df
Out[102]:
0 1 2
0 0 1 2
1 3 4 5
2 6 7 8
3 9 10 11
```
You are making a (n,m) array from n columns of the dataframe:
```
In [103]: np.concatenate([[df[0]],[df[1]],[df[2]]],0)
Out[103]:
array([[ 0, 3, 6, 9],
[ 1, 4, 7, 10],
[ 2, 5, 8, 11]])
```
a more compact way to do this is transpose the array of those columns:
```
In [104]: df.to_numpy().T
Out[104]:
array([[ 0, 3, 6, 9],
[ 1, 4, 7, 10],
[ 2, 5, 8, 11]])
```
The dataframe has its own transpose:
```
In [109]: df.transpose().to_numpy()
Out[109]:
array([[ 0, 3, 6, 9],
[ 1, 4, 7, 10],
[ 2, 5, 8, 11]])
```
Your calculation works with a dataframe, returning a dataframe with same shape and indices:
```
In [113]: np.rint((df+1)/2 *(42-1)).astype(int)
Out[113]:
0 1 2
0 20 41 62
1 82 102 123
2 144 164 184
3 205 226 246
```
Some `numpy` functions convert the inputs to `numpy` arrays and return an array. Others, by delegating details to `pandas` methods, can work directly on the dataframe, and return a dataframe. | I don't like accepting my own answers, so I'm not going to change the accepted answer.
@hpaulj helped me explore this problem further by making additional functionality and opportunities clear to me. This helped me more clearly define my competing objectives, and also to be able to begin ascribing priority to them.
1. Code should be terse / compact and maintainable, not full of boiler plate, including...
* invoking the function
* utilising the results
* the function implementation itself
2. Function performance should not be compromised
* being 5% slower but better in every other respect may be acceptable
* being 100% slower is probably never acceptable
3. Implementation should be as data-type agnostic as possible
* one function for scalars and another for vectors is less than ideal
This lead me to my ***currently*** preferred implementation / style...
```
def scale_unit_cube_to_unit_sphere(*values):
"""
Scales all the inputs (on a row basis for array_line types) such that when
treated as n-dimensional vectors, their scale is always 1.
(Divides the vector represented by each row of inputs by that row's
root-of-sum-of-squares, so as to normalise to a unit magnitude.)
Examples - Scalar Inputs
--------
>>> scale_unit_cube_to_unit_sphere(1, 1, 1)
[0.5773502691896258, 0.5773502691896258, 0.5773502691896258]
Examples - Array Like Inputs
--------
>>> x = [ 1, 2, 3]
>>> y = [ 1, 4, 3]
>>> z = [ 1,-3,-1]
>>> scale_unit_cube_to_unit_sphere(x, y, z)
[array([0.57735027, 0.37139068, 0.6882472 ]),
array([0.57735027, 0.74278135, 0.6882472 ]),
array([ 0.57735027, -0.55708601, -0.22941573])]
>>> a = np.array([x, y, z])
>>> scale_unit_cube_to_unit_sphere(*a)
[array([0.57735027, 0.37139068, 0.6882472 ]),
array([0.57735027, 0.74278135, 0.6882472 ]),
array([ 0.57735027, -0.55708601, -0.22941573])]
scale_unit_cube_to_unit_sphere(*t)
>>> t = (x, y, z)
>>> scale_unit_cube_to_unit_sphere(*t)
[array([0.57735027, 0.37139068, 0.6882472 ]),
array([0.57735027, 0.74278135, 0.6882472 ]),
array([ 0.57735027, -0.55708601, -0.22941573])]
>>> df = pd.DataFrame(data={'x':x,'y':y,'z':z})
>>> scale_unit_cube_to_unit_sphere(df['x'], df['y'], df['z'])
[0 0.577350
1 0.371391
2 0.688247
dtype: float64,
0 0.577350
1 0.742781
2 0.688247
dtype: float64,
0 0.577350
1 -0.557086
2 -0.229416
dtype: float64]
For all array_like inputs, the results can then be utilised in similar
ways, such as writing them to an existing DataFrame as follows:
>>> transform = scale_unit_cube_to_unit_sphere(df['x'], df['y'], df['z'])
>> df['i'], df['j'], df['k'] = transform
"""
# Scale the position in space to be a unit vector, as on the surface of a sphere
################################################################################
scaler = np.sqrt(sum([np.multiply(v, v) for v in values]))
return [np.divide(v, scaler) for v in values]
```
As per the doc string, this works with Scalars, Arrays, Series, etc, whether providing one Scalar, three Scalars, n-scalars, n-Arrays, etc.
*(I don't yet have a neat and tidy way of passing in a single DataFrame rather than three distinct DataSeries, but that's a low priority for now.)*
They also work in "chains" such as the example below (the functions' implementations not being relevant, just the pattern of chaining input to output)...
```
cube, ix = generate_index_cube(vertices_per_edge)
df = pd.DataFrame(
data = {
'x': cube[0],
'y': cube[1],
'z': cube[2],
},
index = ix,
)
unit = scale_index_to_unit(vertices_per_edge, *cube)
distortion = scale_unit_to_distortion(distortion_factor, *unit)
df['a'], df['b'], df['c'] = distortion
sphere = scale_unit_cube_to_unit_sphere(*distortion)
df['i'], df['j'], df['k'] = sphere
recovered_distortion = scale_unit_sphere_to_unit_cube(*sphere)
df['a_'], df['b_'], df['c_'] = recovered_distortion
recovered_cube = scale_unit_to_index(
vertices_per_edge,
*scale_distortion_to_unit(
distortion_factor,
*recovered_distortion,
),
)
df['x_'], df['y_'], df['z_'] = recovered_cube
print(len(df[np.logical_not(np.isclose(df['a'], df['a_']))])) # No Differences
print(len(df[np.logical_not(np.isclose(df['b'], df['b_']))])) # No Differences
print(len(df[np.logical_not(np.isclose(df['c'], df['c_']))])) # No Differences
print(len(df[np.logical_not(np.isclose(df['x'], df['x_']))])) # No Differences
print(len(df[np.logical_not(np.isclose(df['y'], df['y_']))])) # No Differences
print(len(df[np.logical_not(np.isclose(df['z'], df['z_']))])) # No Differences
```
Please do comment or critique. |
7,486,543 | I need to store an CARD ID number in Database. So there is no calculation just a search of the ID and putting the value in Session as property in a class.
The is ID is always numeric and it's 12 positions.
e.g. 123456789012 and I would like to show on the screen in this format. 123.456.789.012 (every 3 digit a dot).
I tried a test and defined Decimal(12,0) in database and I have put this value in database: 555666777888
then I try to display on the screen I used this code (CardID is decimal):
```
lblCardID.Text = ent.CardID.ToString("0:#,###")
```
but it shows on the screen like this: **555,666,77:7,888**
where is the **colon (:)** coming from?
question additional:
- What type shall use in MS SQL to store this value in Database. Decimal (12,0) or Nvarchar(12) ? | 2011/09/20 | [
"https://Stackoverflow.com/questions/7486543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/472092/"
] | `nvarchar` is definitely not needed. if it's always 12 digits, `char(12)` would be fine, but I think a 64-bit integer would be most appropriate. | If you need to store the formatting, and it's just a numeric value, use varchar, don't waste time with nvarchar as it increases your storage size and won't do you any good unless you expect special (international) chars |
7,486,543 | I need to store an CARD ID number in Database. So there is no calculation just a search of the ID and putting the value in Session as property in a class.
The is ID is always numeric and it's 12 positions.
e.g. 123456789012 and I would like to show on the screen in this format. 123.456.789.012 (every 3 digit a dot).
I tried a test and defined Decimal(12,0) in database and I have put this value in database: 555666777888
then I try to display on the screen I used this code (CardID is decimal):
```
lblCardID.Text = ent.CardID.ToString("0:#,###")
```
but it shows on the screen like this: **555,666,77:7,888**
where is the **colon (:)** coming from?
question additional:
- What type shall use in MS SQL to store this value in Database. Decimal (12,0) or Nvarchar(12) ? | 2011/09/20 | [
"https://Stackoverflow.com/questions/7486543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/472092/"
] | Try writing
```
lblCardID.Text = ent.CardID.ToString("#,###")
```
You can user the `decimal(12,0)` or the `bigint` datatype. `bigint` requires one byte less (8 bytes total) per stored value. | If it's never going to be calculated on, I would store it as char(12).
Then in your code, split it with something like this and use the replace function to convert commas to dots:
`lblCardID.Text = ent.CardID.ToString("#,###").Replace(",", ".")` |
7,486,543 | I need to store an CARD ID number in Database. So there is no calculation just a search of the ID and putting the value in Session as property in a class.
The is ID is always numeric and it's 12 positions.
e.g. 123456789012 and I would like to show on the screen in this format. 123.456.789.012 (every 3 digit a dot).
I tried a test and defined Decimal(12,0) in database and I have put this value in database: 555666777888
then I try to display on the screen I used this code (CardID is decimal):
```
lblCardID.Text = ent.CardID.ToString("0:#,###")
```
but it shows on the screen like this: **555,666,77:7,888**
where is the **colon (:)** coming from?
question additional:
- What type shall use in MS SQL to store this value in Database. Decimal (12,0) or Nvarchar(12) ? | 2011/09/20 | [
"https://Stackoverflow.com/questions/7486543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/472092/"
] | `nvarchar` is definitely not needed. if it's always 12 digits, `char(12)` would be fine, but I think a 64-bit integer would be most appropriate. | If it's never going to be calculated on, I would store it as char(12).
Then in your code, split it with something like this and use the replace function to convert commas to dots:
`lblCardID.Text = ent.CardID.ToString("#,###").Replace(",", ".")` |
7,486,543 | I need to store an CARD ID number in Database. So there is no calculation just a search of the ID and putting the value in Session as property in a class.
The is ID is always numeric and it's 12 positions.
e.g. 123456789012 and I would like to show on the screen in this format. 123.456.789.012 (every 3 digit a dot).
I tried a test and defined Decimal(12,0) in database and I have put this value in database: 555666777888
then I try to display on the screen I used this code (CardID is decimal):
```
lblCardID.Text = ent.CardID.ToString("0:#,###")
```
but it shows on the screen like this: **555,666,77:7,888**
where is the **colon (:)** coming from?
question additional:
- What type shall use in MS SQL to store this value in Database. Decimal (12,0) or Nvarchar(12) ? | 2011/09/20 | [
"https://Stackoverflow.com/questions/7486543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/472092/"
] | Try writing
```
lblCardID.Text = ent.CardID.ToString("#,###")
```
You can user the `decimal(12,0)` or the `bigint` datatype. `bigint` requires one byte less (8 bytes total) per stored value. | If it's an ID number store it as a string datatype, you're not going to be doing sums on it, you also won't have problems losing any leading zeros. You could also then store the card id with the embedded dots, sorting out your formatting problems. |
7,486,543 | I need to store an CARD ID number in Database. So there is no calculation just a search of the ID and putting the value in Session as property in a class.
The is ID is always numeric and it's 12 positions.
e.g. 123456789012 and I would like to show on the screen in this format. 123.456.789.012 (every 3 digit a dot).
I tried a test and defined Decimal(12,0) in database and I have put this value in database: 555666777888
then I try to display on the screen I used this code (CardID is decimal):
```
lblCardID.Text = ent.CardID.ToString("0:#,###")
```
but it shows on the screen like this: **555,666,77:7,888**
where is the **colon (:)** coming from?
question additional:
- What type shall use in MS SQL to store this value in Database. Decimal (12,0) or Nvarchar(12) ? | 2011/09/20 | [
"https://Stackoverflow.com/questions/7486543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/472092/"
] | `nvarchar` is definitely not needed. if it's always 12 digits, `char(12)` would be fine, but I think a 64-bit integer would be most appropriate. | If it's an ID number store it as a string datatype, you're not going to be doing sums on it, you also won't have problems losing any leading zeros. You could also then store the card id with the embedded dots, sorting out your formatting problems. |
7,486,543 | I need to store an CARD ID number in Database. So there is no calculation just a search of the ID and putting the value in Session as property in a class.
The is ID is always numeric and it's 12 positions.
e.g. 123456789012 and I would like to show on the screen in this format. 123.456.789.012 (every 3 digit a dot).
I tried a test and defined Decimal(12,0) in database and I have put this value in database: 555666777888
then I try to display on the screen I used this code (CardID is decimal):
```
lblCardID.Text = ent.CardID.ToString("0:#,###")
```
but it shows on the screen like this: **555,666,77:7,888**
where is the **colon (:)** coming from?
question additional:
- What type shall use in MS SQL to store this value in Database. Decimal (12,0) or Nvarchar(12) ? | 2011/09/20 | [
"https://Stackoverflow.com/questions/7486543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/472092/"
] | I would use [`bigint`](http://msdn.microsoft.com/en-us/library/aa933198%28v=sql.80%29.aspx) because it needs only 8 bytes per value.
[`decimal(12,0)`](http://msdn.microsoft.com/en-us/library/aa258832%28v=sql.80%29.aspx) needs 9 bytes and `varchar` or `nvarchar` even more (12 or 24 bytes respectively in case of storing 12 digits).
Smaller column size makes indexes smaller, which make indexes faster in use.
Formatting numbers can be done in application.
It's also much easier to change formatting in app in case of requirements change. | If it's an ID number store it as a string datatype, you're not going to be doing sums on it, you also won't have problems losing any leading zeros. You could also then store the card id with the embedded dots, sorting out your formatting problems. |
7,486,543 | I need to store an CARD ID number in Database. So there is no calculation just a search of the ID and putting the value in Session as property in a class.
The is ID is always numeric and it's 12 positions.
e.g. 123456789012 and I would like to show on the screen in this format. 123.456.789.012 (every 3 digit a dot).
I tried a test and defined Decimal(12,0) in database and I have put this value in database: 555666777888
then I try to display on the screen I used this code (CardID is decimal):
```
lblCardID.Text = ent.CardID.ToString("0:#,###")
```
but it shows on the screen like this: **555,666,77:7,888**
where is the **colon (:)** coming from?
question additional:
- What type shall use in MS SQL to store this value in Database. Decimal (12,0) or Nvarchar(12) ? | 2011/09/20 | [
"https://Stackoverflow.com/questions/7486543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/472092/"
] | The colon is coming from the colon in your format string. The "0:" at the beginning of the format string is needed when you are using string.Format(), as a placeholder to identify which of the arguments to format, but not if you are using ToString() (since there's only one value being formatted). | If it's an ID number store it as a string datatype, you're not going to be doing sums on it, you also won't have problems losing any leading zeros. You could also then store the card id with the embedded dots, sorting out your formatting problems. |
7,486,543 | I need to store an CARD ID number in Database. So there is no calculation just a search of the ID and putting the value in Session as property in a class.
The is ID is always numeric and it's 12 positions.
e.g. 123456789012 and I would like to show on the screen in this format. 123.456.789.012 (every 3 digit a dot).
I tried a test and defined Decimal(12,0) in database and I have put this value in database: 555666777888
then I try to display on the screen I used this code (CardID is decimal):
```
lblCardID.Text = ent.CardID.ToString("0:#,###")
```
but it shows on the screen like this: **555,666,77:7,888**
where is the **colon (:)** coming from?
question additional:
- What type shall use in MS SQL to store this value in Database. Decimal (12,0) or Nvarchar(12) ? | 2011/09/20 | [
"https://Stackoverflow.com/questions/7486543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/472092/"
] | Try writing
```
lblCardID.Text = ent.CardID.ToString("#,###")
```
You can user the `decimal(12,0)` or the `bigint` datatype. `bigint` requires one byte less (8 bytes total) per stored value. | Does your identifier's domain have matematical properties, other than being composed of digits? If not, your value is fixed width, so use `CHAR(12)`. Do not forget to add appropriate domain checks (no characters other than digits, no leading zero, etc) e.g.
```
CREATE TABLE Cards
(
card_ID CHAR(12) NOT NULL
UNIQUE
CONSTRAINT card_ID__all_digits
CHECK (card_ID NOT LIKE '%[^0-9]%'),
CONSTRAINT card_ID__no_leading_zero
CHECK (card_ID NOT LIKE '[1-9]%)')
);
``` |
7,486,543 | I need to store an CARD ID number in Database. So there is no calculation just a search of the ID and putting the value in Session as property in a class.
The is ID is always numeric and it's 12 positions.
e.g. 123456789012 and I would like to show on the screen in this format. 123.456.789.012 (every 3 digit a dot).
I tried a test and defined Decimal(12,0) in database and I have put this value in database: 555666777888
then I try to display on the screen I used this code (CardID is decimal):
```
lblCardID.Text = ent.CardID.ToString("0:#,###")
```
but it shows on the screen like this: **555,666,77:7,888**
where is the **colon (:)** coming from?
question additional:
- What type shall use in MS SQL to store this value in Database. Decimal (12,0) or Nvarchar(12) ? | 2011/09/20 | [
"https://Stackoverflow.com/questions/7486543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/472092/"
] | The colon is coming from the colon in your format string. The "0:" at the beginning of the format string is needed when you are using string.Format(), as a placeholder to identify which of the arguments to format, but not if you are using ToString() (since there's only one value being formatted). | Does your identifier's domain have matematical properties, other than being composed of digits? If not, your value is fixed width, so use `CHAR(12)`. Do not forget to add appropriate domain checks (no characters other than digits, no leading zero, etc) e.g.
```
CREATE TABLE Cards
(
card_ID CHAR(12) NOT NULL
UNIQUE
CONSTRAINT card_ID__all_digits
CHECK (card_ID NOT LIKE '%[^0-9]%'),
CONSTRAINT card_ID__no_leading_zero
CHECK (card_ID NOT LIKE '[1-9]%)')
);
``` |
7,486,543 | I need to store an CARD ID number in Database. So there is no calculation just a search of the ID and putting the value in Session as property in a class.
The is ID is always numeric and it's 12 positions.
e.g. 123456789012 and I would like to show on the screen in this format. 123.456.789.012 (every 3 digit a dot).
I tried a test and defined Decimal(12,0) in database and I have put this value in database: 555666777888
then I try to display on the screen I used this code (CardID is decimal):
```
lblCardID.Text = ent.CardID.ToString("0:#,###")
```
but it shows on the screen like this: **555,666,77:7,888**
where is the **colon (:)** coming from?
question additional:
- What type shall use in MS SQL to store this value in Database. Decimal (12,0) or Nvarchar(12) ? | 2011/09/20 | [
"https://Stackoverflow.com/questions/7486543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/472092/"
] | Try writing
```
lblCardID.Text = ent.CardID.ToString("#,###")
```
You can user the `decimal(12,0)` or the `bigint` datatype. `bigint` requires one byte less (8 bytes total) per stored value. | If you need to store the formatting, and it's just a numeric value, use varchar, don't waste time with nvarchar as it increases your storage size and won't do you any good unless you expect special (international) chars |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.