问:
TensorFlow - Simple Feed Forward NN not training
I'm new to TensorFlow and just constructed my first very small network!!  My code runs, but it has the same accuracy all along; it doesn't change with training. My data has 15 features and 6 classes. Maybe I'll add more features if that makes it easier and better. In short, my question is:

What's a general procedure for debugging TensorFlow code?

My network architecture was determined arbitrarily, so maybe I should change the number of neurons per layer, not entirely sure.

```<code>sess1 = tf.Session()

num_predictors = len(training_predictors_tf.columns)
num_classes = len(training_classes_tf.columns)

feature_data = tf.placeholder(tf.float32, [None, num_predictors])
actual_classes = tf.placeholder(tf.float32, [None, num_classes])

weights1 = tf.Variable(tf.truncated_normal([num_predictors, 50], stddev=0.0001))
biases1 = tf.Variable(tf.ones([50]))

weights2 = tf.Variable(tf.truncated_normal([50, 45], stddev=0.0001))
biases2 = tf.Variable(tf.ones([45]))

weights3 = tf.Variable(tf.truncated_normal([45, 25], stddev=0.0001))
biases3 = tf.Variable(tf.ones([25]))

weights4 = tf.Variable(tf.truncated_normal([25, num_classes], stddev=0.0001))
biases4 = tf.Variable(tf.ones([num_classes]))

hidden_layer_1 = tf.nn.relu(tf.matmul(feature_data, weights1) + biases1)
hidden_layer_2 = tf.nn.relu(tf.matmul(hidden_layer_1, weights2) + biases2)
hidden_layer_3 = tf.nn.relu(tf.matmul(hidden_layer_2, weights3) + biases3)

out = tf.matmul(hidden_layer_3, weights4) + biases4

model = tf.nn.softmax_cross_entropy_with_logits(labels=actual_classes, logits=out)

# cost = -tf.reduce_sum(actual_classes*tf.log(model))

cross_entropy = tf.reduce_mean( model)

train_step = tf.train.GradientDescentOptimizer(0.05).minimize(cross_entropy)

# train_step = tf.train.AdamOptimizer(learning_rate=0.0001).minimize(cross_entropy)

sess1.run(tf.global_variables_initializer())

correct_prediction = tf.equal(tf.argmax(out, 1), tf.argmax(actual_classes, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

for i in range(1, 30001):
    sess1.run(
        train_step,
        feed_dict={
            feature_data: training_predictors_tf.values,
            actual_classes: training_classes_tf.values.reshape(len(training_classes_tf.values), num_classes)
        }
    )
    if i%5000 == 0:
        print(i, sess1.run(
            accuracy,
            feed_dict={
                feature_data: training_predictors_tf.values,
                actual_classes: training_classes_tf.values.reshape(len(training_classes_tf.values), num_classes)
            }
        ))
</code>```

And this is my output:

```<code>5000 0.3627
10000 0.3627
15000 0.3627
20000 0.3627
25000 0.3627
30000 0.3627
</code>```

EDIT: I scaled my data as explained here, in the range of [-5;0] but it still does not train the network any better :(

Snippet of unscaled data (one-hot encoding first 6 columns):

```<code>2017-06-27  0   0   0   1   0   0   20120.0 20080.0 20070.0 20090.0 ... 20050.0 20160.0 20130.0 20160.0 20040.0 20040.0 20040.0 31753.0 36927.0 41516.0
2017-06-28  0   0   1   0   0   0   20150.0 20120.0 20080.0 20150.0 ... 20060.0 20220.0 20160.0 20130.0 20130.0 20040.0 20040.0 39635.0 31753.0 36927.0
2017-06-29  0   0   0   1   0   0   20140.0 20150.0 20120.0 20140.0 ... 20090.0 20220.0 20220.0 20160.0 20100.0 20130.0 20040.0 50438.0 39635.0 31753.0
2017-06-30  0   1   0   0   0   0   20210.0 20140.0 20150.0 20130.0 ... 20150.0 20270.0 20220.0 20220.0 20050.0 20100.0 20130.0 58983.0 50438.0 39635.0
2017-07-03  0   0   0   1   0   0   20020.0 20210.0 20140.0 20210.0 ... 20140.0 20250.0 20270.0 20220.0 19850.0 20050.0 20100.0 88140.0 58983.0 50438.0
</code>```

答:
Debugging your network and improving it are two different things. To improve it, once you've chosen a type of classifier (for instance a neural network), you should use the training and validation accuracies, and adjust your hyperparameters in functions of both of these. See the chapter Practical methodology of Goodfellow and alii's book for instance to know how to tune the hyperparameters (it's a bit long, but pure gold !).

As to debugging, this is the harder part. You usually do that by printing some "key tensor" values every once in a while. You clearly have a bug somewhere, or your accuracy would change at least a bit during training. A common problem causing that is exploding gradient, that causes Nans to appear very early in training (sometimes infinity or even 0s at strange places), which then basically stops any update in your network. I'd suggest printing your loss, and maybe the norm of your gradients, that should tell you if this is the problem. If so, the quick-and-dirty solution is to use a smaller LR at start and then augment it. The real solution is to use gradient clipping.

Example of how to print multiple tensor values:

```<code>if i%5000 == 0:
    acc_val, loss_val, predictions = sess1.run(
        [accuracy, cross_entropy, tf.argmax(out, 1)],
        feed_dict={
            feature_data: training_predictors_tf.values,
            actual_classes: training_classes_tf.values.reshape(len(training_classes_tf.values), num_classes)
        })
    print(i, acc_val, loss_val) # You can also print predictions, but it will be very big so it'll be harder to see the others. Doing it would allow you to check if, for instance, the model always predicts class 0...
</code>```

Body:
I'm new to TensorFlow and just constructed my first very small network!!  My code runs, but it has the same accuracy all along; it doesn't change with training. My data has 15 features and 6 classes. Maybe I'll add more features if that makes it easier and better. In short, my question is:

What's a general procedure for debugging TensorFlow code?

My network architecture was determined arbitrarily, so maybe I should change the number of neurons per layer, not entirely sure.

sess1 = tf.Session()

num_predictors = len(training_predictors_tf.columns)
num_classes = len(training_classes_tf.columns)

feature_data = tf.placeholder(tf.float32, [None, num_predictors])
actual_classes = tf.placeholder(tf.float32, [None, num_classes])

weights1 = tf.Variable(tf.truncated_normal([num_predictors, 50], stddev=0.0001))
biases1 = tf.Variable(tf.ones([50]))

weights2 = tf.Variable(tf.truncated_normal([50, 45], stddev=0.0001))
biases2 = tf.Variable(tf.ones([45]))

weights3 = tf.Variable(tf.truncated_normal([45, 25], stddev=0.0001))
biases3 = tf.Variable(tf.ones([25]))

weights4 = tf.Variable(tf.truncated_normal([25, num_classes], stddev=0.0001))
biases4 = tf.Variable(tf.ones([num_classes]))

hidden_layer_1 = tf.nn.relu(tf.matmul(feature_data, weights1) + biases1)
hidden_layer_2 = tf.nn.relu(tf.matmul(hidden_layer_1, weights2) + biases2)
hidden_layer_3 = tf.nn.relu(tf.matmul(hidden_layer_2, weights3) + biases3)

out = tf.matmul(hidden_layer_3, weights4) + biases4

model = tf.nn.softmax_cross_entropy_with_logits(labels=actual_classes, logits=out)

# cost = -tf.reduce_sum(actual_classes*tf.log(model))

cross_entropy = tf.reduce_mean( model)

train_step = tf.train.GradientDescentOptimizer(0.05).minimize(cross_entropy)

# train_step = tf.train.AdamOptimizer(learning_rate=0.0001).minimize(cross_entropy)

sess1.run(tf.global_variables_initializer())

correct_prediction = tf.equal(tf.argmax(out, 1), tf.argmax(actual_classes, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

for i in range(1, 30001):
    sess1.run(
        train_step,
        feed_dict={
            feature_data: training_predictors_tf.values,
            actual_classes: training_classes_tf.values.reshape(len(training_classes_tf.values), num_classes)
        }
    )
    if i%5000 == 0:
        print(i, sess1.run(
            accuracy,
            feed_dict={
                feature_data: training_predictors_tf.values,
                actual_classes: training_classes_tf.values.reshape(len(training_classes_tf.values), num_classes)
            }
        ))

And this is my output:

5000 0.3627
10000 0.3627
15000 0.3627
20000 0.3627
25000 0.3627
30000 0.3627

EDIT: I scaled my data as explained here, in the range of [-5;0] but it still does not train the network any better :(

Snippet of unscaled data (one-hot encoding first 6 columns):

2017-06-27  0   0   0   1   0   0   20120.0 20080.0 20070.0 20090.0 ... 20050.0 20160.0 20130.0 20160.0 20040.0 20040.0 20040.0 31753.0 36927.0 41516.0
2017-06-28  0   0   1   0   0   0   20150.0 20120.0 20080.0 20150.0 ... 20060.0 20220.0 20160.0 20130.0 20130.0 20040.0 20040.0 39635.0 31753.0 36927.0
2017-06-29  0   0   0   1   0   0   20140.0 20150.0 20120.0 20140.0 ... 20090.0 20220.0 20220.0 20160.0 20100.0 20130.0 20040.0 50438.0 39635.0 31753.0
2017-06-30  0   1   0   0   0   0   20210.0 20140.0 20150.0 20130.0 ... 20150.0 20270.0 20220.0 20220.0 20050.0 20100.0 20130.0 58983.0 50438.0 39635.0
2017-07-03  0   0   0   1   0   0   20020.0 20210.0 20140.0 20210.0 ... 20140.0 20250.0 20270.0 20220.0 19850.0 20050.0 20100.0 88140.0 58983.0 50438.0

Body:
Debugging your network and improving it are two different things. To improve it, once you've chosen a type of classifier (for instance a neural network), you should use the training and validation accuracies, and adjust your hyperparameters in functions of both of these. See the chapter Practical methodology of Goodfellow and alii's book for instance to know how to tune the hyperparameters (it's a bit long, but pure gold !).

As to debugging, this is the harder part. You usually do that by printing some "key tensor" values every once in a while. You clearly have a bug somewhere, or your accuracy would change at least a bit during training. A common problem causing that is exploding gradient, that causes Nans to appear very early in training (sometimes infinity or even 0s at strange places), which then basically stops any update in your network. I'd suggest printing your loss, and maybe the norm of your gradients, that should tell you if this is the problem. If so, the quick-and-dirty solution is to use a smaller LR at start and then augment it. The real solution is to use gradient clipping.

Example of how to print multiple tensor values:

if i%5000 == 0:
    acc_val, loss_val, predictions = sess1.run(
        [accuracy, cross_entropy, tf.argmax(out, 1)],
        feed_dict={
            feature_data: training_predictors_tf.values,
            actual_classes: training_classes_tf.values.reshape(len(training_classes_tf.values), num_classes)
        })
    print(i, acc_val, loss_val) # You can also print predictions, but it will be very big so it'll be harder to see the others. Doing it would allow you to check if, for instance, the model always predicts class 0...


来源: stackexchange

问:
How to check the length of file which is inside the zip file
I want to check files inside the zip are not empty. I know the unzip -l command but it gives lot of information.

```<code>[abc@localhost test]$ unzip -l empty_file_test.zip
Archive:  empty_file_test.zip
  Length      Date    Time    Name
---------  ---------- -----   ----
    0      07-05-2017 06:43   empty_first_20170505.csv
    0      07-05-2017 06:43   empty_second_20170505.csv
---------                     -------
    0                         2 files
</code>```

I extracted the file names from the zip file by command

```<code>file_names="$(unzip -Z1 empty_file_test.zip)
file_name_array=($file_names)
file1=${file_name_array[0]}
file2=${file_name_array[1]}
</code>```

I tried using -s option but not useful

```<code>if [ -s $file1 ]; then
   echo "file is non zero"
else
   echo "file is empty"
fi
</code>```

It always prints file is empty even though file is not empty.

答:
You could format the output fo unzip -l

```<code>unzip -l test.zip | awk '{print $1 "\t"  $4}' | tail -n+4 | head -n-2
</code>```

Explanation:

unzip -l unzips the files and returns the deisred information

awk '{print $1 "\t"  $4}' prints columns 1 and 4 (size and filename)

tail -n+4 strips the first few lines from the output (removing the header and unwanted information)

head -n-2 strips the last two lines from the output (removing the unwanted summary)

Edit:

To store empty files into an array you can map the output of the comand:

```<code>read -r -a array <<< `unzip -l test.zip | awk '{print $1 "\t"  $4}' | tail -n+4 | head -n-2 | awk '{if($1==0) print $2}'`
</code>```

Explanation

unzip -l test.zip | awk '{print $1 "\t"  $4}' | tail -n+4 | head -n-2 is explained above

awk '{if($1==0)}{print $2}' just gives you the filenames of the empty files

<<< inputs the output of the command in backticks `` into the read command

read -r -a array reads the input into the variable array

BUT

You could just use the shorter command of Sjsam and do the same:

```<code>read -r -a array <<< `unzip -l empty_file_test.zip | awk 'NR>=4{if($1==0){print $4}}'`
</code>```

read -r -a array is explained above

<<< is explained above

awk 'NR>=4{if($1==0){print $4}}'

NR>=4 puts out every line > 4 (strip the header and unwanted output)

if($1==0){print $4}} if the size ($0) is 0 it executes {print $4}

{print $4} outputs the filename

ContentLicense: CC BY-SA 3.0

Body:
I want to check files inside the zip are not empty. I know the unzip -l command but it gives lot of information.

[abc@localhost test]$ unzip -l empty_file_test.zip
Archive:  empty_file_test.zip
  Length      Date    Time    Name
---------  ---------- -----   ----
    0      07-05-2017 06:43   empty_first_20170505.csv
    0      07-05-2017 06:43   empty_second_20170505.csv
---------                     -------
    0                         2 files

I extracted the file names from the zip file by command

file_names="$(unzip -Z1 empty_file_test.zip)
file_name_array=($file_names)
file1=${file_name_array[0]}
file2=${file_name_array[1]}

I tried using -s option but not useful

if [ -s $file1 ]; then
   echo "file is non zero"
else
   echo "file is empty"
fi

It always prints file is empty even though file is not empty.

Body:
You could format the output fo unzip -l

unzip -l test.zip | awk '{print $1 "\t"  $4}' | tail -n+4 | head -n-2

Explanation:

unzip -l unzips the files and returns the deisred information

awk '{print $1 "\t"  $4}' prints columns 1 and 4 (size and filename)

tail -n+4 strips the first few lines from the output (removing the header and unwanted information)

head -n-2 strips the last two lines from the output (removing the unwanted summary)

Edit:

To store empty files into an array you can map the output of the comand:

read -r -a array <<< `unzip -l test.zip | awk '{print $1 "\t"  $4}' | tail -n+4 | head -n-2 | awk '{if($1==0) print $2}'`

Explanation

unzip -l test.zip | awk '{print $1 "\t"  $4}' | tail -n+4 | head -n-2 is explained above

awk '{if($1==0)}{print $2}' just gives you the filenames of the empty files

<<< inputs the output of the command in backticks `` into the read command

read -r -a array reads the input into the variable array

BUT

You could just use the shorter command of Sjsam and do the same:

read -r -a array <<< `unzip -l empty_file_test.zip | awk 'NR>=4{if($1==0){print $4}}'`

read -r -a array is explained above

<<< is explained above

awk 'NR>=4{if($1==0){print $4}}'

NR>=4 puts out every line > 4 (strip the header and unwanted output)

if($1==0){print $4}} if the size ($0) is 0 it executes {print $4}

{print $4} outputs the filename


问:
Conditionally replace elements of a vector based on an index
It's best explained with an example.

I have a vector, or column from data.frame named vec:

```<code>vec <- c(NA, NA, 1, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA)
</code>```

I would like a vectorized process (not a for loop) to change the three trailing NA when a 1 is observed.

The end vector would be:

```<code>c(NA, NA, 1, 1, 1, 1, NA, 1, 1, 1, 1, NA, NA, NA)
</code>```

If we had:

```<code>vec <- c(NA, NA, 1, NA, 1, NA, NA, 1, NA, NA, NA, NA, NA, NA)
</code>```

The end vector would look like:

```<code>c(NA, NA, 1, 1, 1, 1, 1, 1, 1, 1, 1, NA, NA, NA)
</code>```

A very badly written solution is:

```<code>vec2 <- vec
for(i in index(v)){
  if(!is.na(v[i])) vec2[i] <- 1
  if(i>3){
    if(!is.na(vec[i-1])) vec2[i] <- 1
    if(!is.na(vec[i-2])) vec2[i] <- 1
    if(!is.na(vec[i-3])) vec2[i] <- 1
  }
  if(i==3){
    if(!is.na(vec[i-1])) vec2[i] <- 1
    if(!is.na(vec[i-2])) vec2[i] <- 1
  }
  if(i==2){
    if(!is.na(vec[i-1])) vec2[i] <- 1
  }
}
</code>```

答:
What really is 'vectorised', if not a loop written in a C-language?

Here's a C++ loop that benchmarks well.

```<code>vec <- c(NA, NA, 1, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA)

library(Rcpp)

cppFunction('NumericVector fixVec(NumericVector myVec){

    int n = myVec.size();
    int foundCount = 0;

    for(int i = 0; i < n; i++){
      if(myVec[i] == 1) foundCount = 1;

      if(ISNA(myVec[i])){
        if(foundCount >= 1 & foundCount <= 3){
          myVec[i] = 1;
          foundCount++;
        }
      }
    }
    return myVec;
    }')

fixVec(vec)
# [1] NA NA  1  1  1  1 NA  1  1  1  1 NA NA NA
</code>```

Benchmarks

```<code>library(microbenchmark)

microbenchmark(
      ans.jaap = {
        vec <- rep(c(NA, NA, 1, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA),1e4);
      vec[rep(which(vec == 1), each = 4) + c(0:3)] <- 1
},

    ans.nicola = {
        vec <- rep(c(NA, NA, 1, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA),1e4);
      `[<-`(vec,c(outer(which(vec==1),0:3,"+")),1)
        },

    ans.symbolix = {
        vec <- rep(c(NA, NA, 1, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA),1e4);
      vec <- fixVec(vec)
        }
)

# Unit: microseconds
# expr              min       lq      mean   median        uq       max neval
# ans.jaap     2017.789 2264.318 2905.2437 2579.315 3588.4850  4667.249   100
# ans.nicola   1242.002 1626.704 3839.4768 2095.311 3066.4795 81299.962   100
# ans.symbolix  504.577  533.426  838.5661  718.275  966.9245  2354.373   100

vec <- rep(c(NA, NA, 1, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA),1e4)
vec <- fixVec(vec)

vec2 <- rep(c(NA, NA, 1, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA),1e4)
vec2[rep(which(vec2 == 1), each = 4) + c(0:3)] <- 1

identical(vec, vec2)
# [1] TRUE
</code>```

Body:
It's best explained with an example.

I have a vector, or column from data.frame named vec:

vec <- c(NA, NA, 1, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA)

I would like a vectorized process (not a for loop) to change the three trailing NA when a 1 is observed.

The end vector would be:

c(NA, NA, 1, 1, 1, 1, NA, 1, 1, 1, 1, NA, NA, NA)

If we had:

vec <- c(NA, NA, 1, NA, 1, NA, NA, 1, NA, NA, NA, NA, NA, NA)

The end vector would look like:

c(NA, NA, 1, 1, 1, 1, 1, 1, 1, 1, 1, NA, NA, NA)

A very badly written solution is:

vec2 <- vec
for(i in index(v)){
  if(!is.na(v[i])) vec2[i] <- 1
  if(i>3){
    if(!is.na(vec[i-1])) vec2[i] <- 1
    if(!is.na(vec[i-2])) vec2[i] <- 1
    if(!is.na(vec[i-3])) vec2[i] <- 1
  }
  if(i==3){
    if(!is.na(vec[i-1])) vec2[i] <- 1
    if(!is.na(vec[i-2])) vec2[i] <- 1
  }
  if(i==2){
    if(!is.na(vec[i-1])) vec2[i] <- 1
  }
}

Body:
What really is 'vectorised', if not a loop written in a C-language?

Here's a C++ loop that benchmarks well.

vec <- c(NA, NA, 1, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA)

library(Rcpp)

cppFunction('NumericVector fixVec(NumericVector myVec){

    int n = myVec.size();
    int foundCount = 0;

    for(int i = 0; i < n; i++){
      if(myVec[i] == 1) foundCount = 1;

      if(ISNA(myVec[i])){
        if(foundCount >= 1 & foundCount <= 3){
          myVec[i] = 1;
          foundCount++;
        }
      }
    }
    return myVec;
    }')

fixVec(vec)
# [1] NA NA  1  1  1  1 NA  1  1  1  1 NA NA NA

Benchmarks

library(microbenchmark)

microbenchmark(
      ans.jaap = {
        vec <- rep(c(NA, NA, 1, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA),1e4);
      vec[rep(which(vec == 1), each = 4) + c(0:3)] <- 1
},

    ans.nicola = {
        vec <- rep(c(NA, NA, 1, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA),1e4);
      `[<-`(vec,c(outer(which(vec==1),0:3,"+")),1)
        },

    ans.symbolix = {
        vec <- rep(c(NA, NA, 1, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA),1e4);
      vec <- fixVec(vec)
        }
)

# Unit: microseconds
# expr              min       lq      mean   median        uq       max neval
# ans.jaap     2017.789 2264.318 2905.2437 2579.315 3588.4850  4667.249   100
# ans.nicola   1242.002 1626.704 3839.4768 2095.311 3066.4795 81299.962   100
# ans.symbolix  504.577  533.426  838.5661  718.275  966.9245  2354.373   100

vec <- rep(c(NA, NA, 1, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA),1e4)
vec <- fixVec(vec)

vec2 <- rep(c(NA, NA, 1, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA),1e4)
vec2[rep(which(vec2 == 1), each = 4) + c(0:3)] <- 1

identical(vec, vec2)
# [1] TRUE


问:
Using pointers and structs
Hello i'm not sure if I'm understand the following piece of code. I would glad if someone could read my explanations and correct me if I'm wrong.

 So first of all I'm declaring a struct with three arrays of char and an integer.

```<code>struct Employee
{
    char last[16];
    char first[11];
    char title[16];
    int salary;
};
</code>```

 After that I declare a function which takes three pointers to char and an integer value. This function uses malloc() and sizeof() to create a struct on the heap. Now this creations of the object on the heap is not really clear to me. When I use struct Employee* p = malloc(sizeof(struct Employee)), what happens there exactly?
 What happens when I use the function struct Employee* createEmployee (char* last, char* first, char* title, int salary) several times with different input. I know that I will get back a pointer p but isn't that the same pointer to the same struct on the heap. So do I rewrite the information on the heap, when I use the function several times? Or does it always create a new object in a different memory space?

```<code>struct Employee* createEmployee(char*, char*, char*, int);

struct Employee* createEmployee(char* last, char* first, char* title, int salary)
{
    struct Employee* p = malloc(sizeof(struct Employee));
    if (p != NULL)
    {
        strcpy(p->last, last);
        strcpy(p->first, first);
        strcpy(p->title, title);
        p->salary = salary;
    }
    return p;
}
</code>```

I would be glad if someone could explain it to me. Thank you very much.

答:
Every time you call malloc(), you're telling it to give you a new chunk of memory, at least as long as you've asked for, not currently in use anywhere else. So the following gives you three different pointers:

```<code>void *p1 = malloc(100);
void *p2 = malloc(100);
void *p3 = malloc(100);
</code>```

It's like hitting a button on a vending machine. Each time, you get a different candy bar that conforms to your requests ("Caramilk" for instance.)

ContentLicense: CC BY-SA 2.5

Title: Using pointers and structs

Body:
Hello i'm not sure if I'm understand the following piece of code. I would glad if someone could read my explanations and correct me if I'm wrong.

 So first of all I'm declaring a struct with three arrays of char and an integer.

struct Employee
{
    char last[16];
    char first[11];
    char title[16];
    int salary;
};

 After that I declare a function which takes three pointers to char and an integer value. This function uses malloc() and sizeof() to create a struct on the heap. Now this creations of the object on the heap is not really clear to me. When I use struct Employee* p = malloc(sizeof(struct Employee)), what happens there exactly?
 What happens when I use the function struct Employee* createEmployee (char* last, char* first, char* title, int salary) several times with different input. I know that I will get back a pointer p but isn't that the same pointer to the same struct on the heap. So do I rewrite the information on the heap, when I use the function several times? Or does it always create a new object in a different memory space?

struct Employee* createEmployee(char*, char*, char*, int);

struct Employee* createEmployee(char* last, char* first, char* title, int salary)
{
    struct Employee* p = malloc(sizeof(struct Employee));
    if (p != NULL)
    {
        strcpy(p->last, last);
        strcpy(p->first, first);
        strcpy(p->title, title);
        p->salary = salary;
    }
    return p;
}

I would be glad if someone could explain it to me. Thank you very much.

Body:
Every time you call malloc(), you're telling it to give you a new chunk of memory, at least as long as you've asked for, not currently in use anywhere else. So the following gives you three different pointers:

void *p1 = malloc(100);
void *p2 = malloc(100);
void *p3 = malloc(100);

It's like hitting a button on a vending machine. Each time, you get a different candy bar that conforms to your requests ("Caramilk" for instance.)


问:
Flink: Stateful stream processing by key
I have stream of data such as JSON records with an ID.

I would like to process the data such that all records with the same key are processed by the same stateful task.

How can I do that?

答:
This can be done with a stateful operator on a KeyedStream. A KeyedStream partitions all records on a key and ensures that all records with the same key go to the same operator instance and interact with the same state.

In code this looks like:

```<code>val stream: DataStream[(String, Long)] = ???
val sumByKey: DataStream[(String, Long)] = stream
  .keyBy(_._1) // key on the first attribute
  .map(new SumMapper())

class SumMapper extends RichMapFunction[(String, Long), (String, Long)] {

  var sumState: ValueState[Long] = _

  override def open(config: Configuration) {
    // configure state
    val sumDesc: ValueStateDescriptor[Long] =
      new ValueStateDescriptor[Long]("sum", classOf[Long])
    sumState = getRuntimeContext.getState(sumDesc)
  }

  override def map(in: (String, Long)): (String, Long) = {
    val sum = sumState.value() // get current sum from state
    val newSum = sum + in._2   // compute new sum
    sumState.update(newSum)    // update state
    (in._1, newSum)            // emit result
  }
}
</code>```

Body:
This can be done with a stateful operator on a KeyedStream. A KeyedStream partitions all records on a key and ensures that all records with the same key go to the same operator instance and interact with the same state.

In code this looks like:

val stream: DataStream[(String, Long)] = ???
val sumByKey: DataStream[(String, Long)] = stream
  .keyBy(_._1) // key on the first attribute
  .map(new SumMapper())

class SumMapper extends RichMapFunction[(String, Long), (String, Long)] {

  var sumState: ValueState[Long] = _

  override def open(config: Configuration) {
    // configure state
    val sumDesc: ValueStateDescriptor[Long] =
      new ValueStateDescriptor[Long]("sum", classOf[Long])
    sumState = getRuntimeContext.getState(sumDesc)
  }

  override def map(in: (String, Long)): (String, Long) = {
    val sum = sumState.value() // get current sum from state
    val newSum = sum + in._2   // compute new sum
    sumState.update(newSum)    // update state
    (in._1, newSum)            // emit result
  }
}


问:
retrieving number of observations with non missing values
I would like to compute the number of observations (Persons in my following example) that have non-missing values.

```<code>unbal <- data.frame(PERSON=c(rep('Frank',5),rep('Tony',5),rep('Edward',5)), YEAR=c(2001,2002,2003,2004,2005,2001,2002,2003,2004,2005,2001,2002,2003,2004,2005), Y=c(21,22,23,24,25,5,6,NA,7,8,31,32,33,34,35), X=c(1:15))
unbal

   PERSON YEAR  Y  X
1   Frank 2001 21  1
2   Frank 2002 22  2
3   Frank 2003 23  3
4   Frank 2004 24  4
5   Frank 2005 25  5
6    Tony 2001  5  6
7    Tony 2002  6  7
8    Tony 2003 NA  8
9    Tony 2004  7  9
10   Tony 2005  8 10
11 Edward 2001 31 11
12 Edward 2002 32 12
13 Edward 2003 33 13
14 Edward 2004 34 14
15 Edward 2005 35 15
</code>```

In this case will be 2, since only two persons (Frank and Edward) have all the data.

答:
One way via base R,

```<code>sapply(split(unbal, unbal$PERSON), function(i) all(complete.cases(i)))
#Edward  Frank   Tony
#  TRUE   TRUE  FALSE
</code>```

You can do this to extract,

```<code>ind <- sapply(split(unbal, unbal$PERSON), function(i) all(complete.cases(i)))
names(ind)[ind]
#[1] "Edward" "Frank"

#or for the length
length(ind[ind])
#[1] 2
</code>```

Body:
I would like to compute the number of observations (Persons in my following example) that have non-missing values.

unbal <- data.frame(PERSON=c(rep('Frank',5),rep('Tony',5),rep('Edward',5)), YEAR=c(2001,2002,2003,2004,2005,2001,2002,2003,2004,2005,2001,2002,2003,2004,2005), Y=c(21,22,23,24,25,5,6,NA,7,8,31,32,33,34,35), X=c(1:15))
unbal

   PERSON YEAR  Y  X
1   Frank 2001 21  1
2   Frank 2002 22  2
3   Frank 2003 23  3
4   Frank 2004 24  4
5   Frank 2005 25  5
6    Tony 2001  5  6
7    Tony 2002  6  7
8    Tony 2003 NA  8
9    Tony 2004  7  9
10   Tony 2005  8 10
11 Edward 2001 31 11
12 Edward 2002 32 12
13 Edward 2003 33 13
14 Edward 2004 34 14
15 Edward 2005 35 15

In this case will be 2, since only two persons (Frank and Edward) have all the data.

Body:
One way via base R,

sapply(split(unbal, unbal$PERSON), function(i) all(complete.cases(i)))
#Edward  Frank   Tony
#  TRUE   TRUE  FALSE

You can do this to extract,

ind <- sapply(split(unbal, unbal$PERSON), function(i) all(complete.cases(i)))
names(ind)[ind]
#[1] "Edward" "Frank"

#or for the length
length(ind[ind])
#[1] 2


问:
How to properly access a text file in Android Studio
When I try to read some files in my Android app they appear to not exist, here is my code:

```<code>public class ReadFiles1 {

    //Static Scanner and File Objects
    static Scanner s;

    // Static method that returns an ArrayList
    static ArrayList<String> words (String filename){

        //Instantiate File with file name within parameters
        File n = new File(filename);

        //Instantiate Scanner s with f variable within parameters
        //surround with try and catch to see whether the file was read or not
        try {
            s = new Scanner(n);
        } catch (FileNotFoundException e) {

            e.printStackTrace();
            System.out.println("Problem here");
        }

        //Instantiate a new ArrayList of String type
        ArrayList<String> theWord = new ArrayList <String>();

        //while it has next ..
        while(s.hasNext()){
            //Initialise str with word read
            String str=s.next();

            //add to ArrayList
            theWord.add(str);

        }
        //return ArrayList
        return theWord;

    }
</code>```

I don't know what the problem is, I put the txt files in the same package as the .java files.
This is the error I get when runnning this:
check this link for PICTURE(https://ibb.co/cn3QCv)

```<code>W/System.err: java.io.FileNotFoundException: build/numbers.txt: open failed: ENOENT (No such file or directory)
</code>```

答:
Don't put your text files in java folder instead put it in

app/src/main/res/raw/ folder and read it in program using below code.

```<code>static ArrayList<String> words (InputStream in) {
    try {
        s = new Scanner(in);
    } catch (FileNotFoundException e) {

        e.printStackTrace();
        System.out.println("Problem here");
    }
</code>```

and call this method from any activity or service using below code

```<code>InputStream in = getResources().openRawResource(R.raw.numbers);
ArrayList<String> words = ReadFiles1.words(in);
</code>```

or if you're calling this method from any other class then should have context reference

```<code>InputStream in = context.getResources().openRawResource(R.raw.numbers);
ArrayList<String> words = ReadFiles1.words(in);
</code>```

Hope this will work.

ContentLicense: CC BY-SA 4.0

Body:
When I try to read some files in my Android app they appear to not exist, here is my code:

public class ReadFiles1 {

    //Static Scanner and File Objects
    static Scanner s;

    // Static method that returns an ArrayList
    static ArrayList<String> words (String filename){

        //Instantiate File with file name within parameters
        File n = new File(filename);

        //Instantiate Scanner s with f variable within parameters
        //surround with try and catch to see whether the file was read or not
        try {
            s = new Scanner(n);
        } catch (FileNotFoundException e) {

            e.printStackTrace();
            System.out.println("Problem here");
        }

        //Instantiate a new ArrayList of String type
        ArrayList<String> theWord = new ArrayList <String>();

        //while it has next ..
        while(s.hasNext()){
            //Initialise str with word read
            String str=s.next();

            //add to ArrayList
            theWord.add(str);

        }
        //return ArrayList
        return theWord;

    }

I don't know what the problem is, I put the txt files in the same package as the .java files.
This is the error I get when runnning this:
check this link for PICTURE(https://ibb.co/cn3QCv)

W/System.err: java.io.FileNotFoundException: build/numbers.txt: open failed: ENOENT (No such file or directory)

Body:
Don't put your text files in java folder instead put it in

app/src/main/res/raw/ folder and read it in program using below code.

static ArrayList<String> words (InputStream in) {
    try {
        s = new Scanner(in);
    } catch (FileNotFoundException e) {

        e.printStackTrace();
        System.out.println("Problem here");
    }

and call this method from any activity or service using below code

InputStream in = getResources().openRawResource(R.raw.numbers);
ArrayList<String> words = ReadFiles1.words(in);

or if you're calling this method from any other class then should have context reference

InputStream in = context.getResources().openRawResource(R.raw.numbers);
ArrayList<String> words = ReadFiles1.words(in);

Hope this will work.


问:
why a pointer to List can also point to Node?
I am a primer to c programming and reading c primer: 5th edition. What confuse me is why  plist  as a pointer to  List can also point to Node?

sorry, I did not paste function ListItemCount to the code block. In this function, Node * pnode = *plist;,  Does that mean plist was converted as a ponter point to Node ?  If so, why does the program need to convert to a pointer to node instead of assigning  plist->head to pnode(a pointer to Node)?

```<code>typedef struct film {
    char title[TSIZE];
    int rating;
} Item;

typedef struct node{
    Item item;
    // typical usage
    struct node * next;
} Node;

/*
* Note: to manage a linked list, we need  a pointer to its beginning,
* and we've used typedef to make List the name for a pointer of this
* type.
*/
typedef struct list{
    // should point to linked list Node
    Node * head;

    int size;
} List;

// TODO why  `plist`  as a pointer to  List can also point to Node?
/* returns number of nodes */
unsigned int ListItemCount(const List * plist)
{
    unsigned int count = 0;
    Node * pnode = *plist; /* set to start of list */
    while (pnode != NULL)
    {
        ++count;
        pnode = pnode->next; /* set to next node */
    }
    return count;
}
</code>```

答:
The compiler should shout warnings at you for that code.

However lets take a look at how it works...

The memory layout of the List structure is something like

```
+------+------+
| head | size |
+------+------+
```

(The above illustration ignores possible padding.)

The variable plist points to the beginning of that structure:

```
+------+------+
| head | size |
+------+------+
^
|
plist
```

As you can see it points to the location where head is stored. So by dereferencing plist we can get the head member.

But it is bad code and you should never write code like that. It makes code hard to read, understand and maintain. Be explicit and use

```<code>Node * pnode = plist->head; /* set to start of list */
</code>```

instead.

Body:
I am a primer to c programming and reading c primer: 5th edition. What confuse me is why  plist  as a pointer to  List can also point to Node?

sorry, I did not paste function ListItemCount to the code block. In this function, Node * pnode = *plist;,  Does that mean plist was converted as a ponter point to Node ?  If so, why does the program need to convert to a pointer to node instead of assigning  plist->head to pnode(a pointer to Node)?

typedef struct film {
    char title[TSIZE];
    int rating;
} Item;

typedef struct node{
    Item item;
    // typical usage
    struct node * next;
} Node;

/*
* Note: to manage a linked list, we need  a pointer to its beginning,
* and we've used typedef to make List the name for a pointer of this
* type.
*/
typedef struct list{
    // should point to linked list Node
    Node * head;

    int size;
} List;

// TODO why  `plist`  as a pointer to  List can also point to Node?
/* returns number of nodes */
unsigned int ListItemCount(const List * plist)
{
    unsigned int count = 0;
    Node * pnode = *plist; /* set to start of list */
    while (pnode != NULL)
    {
        ++count;
        pnode = pnode->next; /* set to next node */
    }
    return count;
}

Body:
The compiler should shout warnings at you for that code.

However lets take a look at how it works...

The memory layout of the List structure is something like

+------+------+
| head | size |
+------+------+

(The above illustration ignores possible padding.)

The variable plist points to the beginning of that structure:

+------+------+
| head | size |
+------+------+
^
|
plist

As you can see it points to the location where head is stored. So by dereferencing plist we can get the head member.

But it is bad code and you should never write code like that. It makes code hard to read, understand and maintain. Be explicit and use

Node * pnode = plist->head; /* set to start of list */

instead.


问:
How to do exact search in Shiny DataTables column
I have the following self-sufficient Shiny script:

```<code>mydf <- data.frame(commonality=c("common","uncommon","common","uncommon","common"),value=c(1,2,3,4,5))

library(shiny)
shinyApp(
  ui = fluidPage(DT::dataTableOutput('tbl')),
  server = function(input, output) {
    output$tbl = DT::renderDataTable(
      mydf, options = list(lengthChange = FALSE)
    )
  }
)
</code>```

Which produces this:

What I want to do is to do exact search. For example when I type common,
the values uncommon should not appear. How can I do that?

答:
You can use the filter of the DT package :

```<code> library(shiny)
    shinyApp( ui = fluidPage(DT::dataTableOutput('tbl')),
    server = function(input, output) {
    output$tbl = DT::renderDataTable( mydf,filter = 'top', options = list(lengthChange = T, dom = 'tip') )
      })
</code>```

and the result look like this :

Body:
I have the following self-sufficient Shiny script:

mydf <- data.frame(commonality=c("common","uncommon","common","uncommon","common"),value=c(1,2,3,4,5))

library(shiny)
shinyApp(
  ui = fluidPage(DT::dataTableOutput('tbl')),
  server = function(input, output) {
    output$tbl = DT::renderDataTable(
      mydf, options = list(lengthChange = FALSE)
    )
  }
)

Which produces this:

What I want to do is to do exact search. For example when I type common,
the values uncommon should not appear. How can I do that?

Body:
You can use the filter of the DT package :

 library(shiny)
    shinyApp( ui = fluidPage(DT::dataTableOutput('tbl')),
    server = function(input, output) {
    output$tbl = DT::renderDataTable( mydf,filter = 'top', options = list(lengthChange = T, dom = 'tip') )
      })

and the result look like this :


问:
WPF PRISM - Register view with region without resolving instance
Is it possible to register a view by type with a region within the Module initialization without causing the view to be resolved (instantiated) until the view is request for activation.

A scenario for this is when we have view-first approach with a dependency on and external service. I do not want the service to be initialized until the user really requires that view and this will help improve performance because some external services cost time to initialize.

Note: Multiple views are register to the same region (eg. menu navigation style scenario).

答:
There are two ways to go about this.  One has more documentation than the other.

Take over instantiation yourself by using View Injection, rather than allowing the Region to instantiate your view (called View Discovery).  This is pretty straightforward, but without knowing your solution, it'd be hard to know exactly what you are looking for.

Utilize the IActiveAware interface. In this scenario, you actually allow the view to be instantiated, but your view would wait for notification from the Region Manager that the view is active.  Here is a look at the IActiveAware interface (it's pretty self-explanatory): http://msdn.microsoft.com/en-us/library/microsoft.practices.prism.iactiveaware_members(v=pandp.38).aspx

And a small codesample:

```<code>public class MyView : IActiveAware
{
     private bool _isActive = false;
     public bool IsActive
     {
          get { return _isActive; }
          set
          {
               _isActive = value;
               if(value)
               {
                     //Good idea to thread this if you can
                     DoSomethingExpensive();
               }
          }

     }

}
</code>```

Body:
There are two ways to go about this.  One has more documentation than the other.

Take over instantiation yourself by using View Injection, rather than allowing the Region to instantiate your view (called View Discovery).  This is pretty straightforward, but without knowing your solution, it'd be hard to know exactly what you are looking for.

Utilize the IActiveAware interface. In this scenario, you actually allow the view to be instantiated, but your view would wait for notification from the Region Manager that the view is active.  Here is a look at the IActiveAware interface (it's pretty self-explanatory): http://msdn.microsoft.com/en-us/library/microsoft.practices.prism.iactiveaware_members(v=pandp.38).aspx

And a small codesample:

public class MyView : IActiveAware
{
     private bool _isActive = false;
     public bool IsActive
     {
          get { return _isActive; }
          set
          {
               _isActive = value;
               if(value)
               {
                     //Good idea to thread this if you can
                     DoSomethingExpensive();
               }
          }

     }

}


问:
How do I change qt label text to look like window title text
In my program I am displaying a dialog window to provide information to the user. I am using the QT Label element to do this and I would like to make the text look more "organic" or carved in, like the title text of a window than simple black on gray. Does anyone have any suggestions? I am using QT Creator and coding in c++ for Linux.

here is an image of what I am trying to acomplish

答:
I prepared an MCVE to demonstrate the options I suggested in my comments.

Changing style of QLabel is rather simple and straight forward.

Using the QStylePainter doesn't quite match what I actually expected. I left in the sample code what I got so far. (May be, somebody could leave a helpful hint.) I will investigate in this topic later and edit this answer as soon as I got some satisfying progress on this topic.

The sample code:

```<code>#include <QtWidgets>

class TitleBar: public QWidget {

  private:
    QStyleOptionTitleBar _option;
    //QString _text;

  public:
    explicit TitleBar(
      const QString &text = QString(), QWidget *pQParent = nullptr);

  protected:
    virtual QSize sizeHint() const;
    virtual void resizeEvent(QResizeEvent *pQEvent);
    virtual void paintEvent(QPaintEvent *pQEvent);
};

int main(int argc, char **argv)
{
  qDebug() << "Qt Version: " << QT_VERSION_STR;
  // main application
#undef qApp // undef macro qApp out of the way
  QApplication qApp(argc, argv);
  // setup of GUI
  QWidget qWin;
  QVBoxLayout qBox;
  // a boring label
  QLabel qLbl1(QString::fromUtf8("Rather boring"));
  qLbl1.setAlignment(Qt::AlignCenter);
  qBox.addWidget(&qLbl1);
  // a label with frame
  QLabel qLbl2(QString::fromUtf8("Label with Frame"));
  qLbl2.setFrameStyle(QLabel::Panel | QLabel::Raised);
  qLbl2.setLineWidth(2);
  qLbl2.setAlignment(Qt::AlignCenter);
  qBox.addWidget(&qLbl2);
  // a label with rich-text
  QLabel qLbl3(
    QString::fromUtf8(
      "<body bgcolor='#28f'>" // doesn't have the effect
        "<font size='+2' color='#f8e' face='Old English Text MT'>"
          "Label <i>with</i> <b>Rich-Text</b>"
        "</font>"
      "</body>")); // background is set by style-sheet instead
  qLbl3.setTextFormat(Qt::RichText); // might be auto-detected...
  qLbl3.setStyleSheet("QLabel { background-color: #28f; }");
  qLbl3.setAlignment(Qt::AlignCenter);
  qLbl3.show();
  qBox.addWidget(&qLbl3);
  // a home-brew title bar
  TitleBar qTitle("A Home-Brew Title Bar");
  qBox.addWidget(&qTitle);
  // finish setup of GUI
  qWin.setLayout(&qBox);
  qWin.show();
  // run application
  return qApp.exec();
}

TitleBar::TitleBar(const QString &text, QWidget *pQParent):
  QWidget(pQParent)
{
  _option.initFrom(this);
  _option.titleBarFlags = Qt::Window;
  _option.text = text;
}

QSize TitleBar::sizeHint() const
{
#if 0 // does not provide the expected result
  return _option.rect.size();
#elif 0 // does not provide the expected result
  return style()->proxy()->subControlRect(QStyle::CC_TitleBar,
    &_option, QStyle::SC_TitleBarLabel).size();
#else
  return QSize(0,
    style()->proxy()->pixelMetric(QStyle::PM_TitleBarHeight,
      &_option, this));
#endif // 0
}

void TitleBar::resizeEvent(QResizeEvent *pQEvent)
{
  _option.rect = QRect(_option.rect.topLeft(), pQEvent->size());
}

void TitleBar::paintEvent(QPaintEvent *pQEvent)
{
  QPainter qPainter(this);
  style()->proxy()->drawComplexControl(QStyle::CC_TitleBar,
    &_option, &qPainter, this);
}
</code>```

I compiled and tested it in VS2013 on Windows 10 (64 bit). Below a snapshot:

Body:
I prepared an MCVE to demonstrate the options I suggested in my comments.

Changing style of QLabel is rather simple and straight forward.

Using the QStylePainter doesn't quite match what I actually expected. I left in the sample code what I got so far. (May be, somebody could leave a helpful hint.) I will investigate in this topic later and edit this answer as soon as I got some satisfying progress on this topic.

The sample code:

#include <QtWidgets>

class TitleBar: public QWidget {

  private:
    QStyleOptionTitleBar _option;
    //QString _text;

  public:
    explicit TitleBar(
      const QString &text = QString(), QWidget *pQParent = nullptr);

  protected:
    virtual QSize sizeHint() const;
    virtual void resizeEvent(QResizeEvent *pQEvent);
    virtual void paintEvent(QPaintEvent *pQEvent);
};

int main(int argc, char **argv)
{
  qDebug() << "Qt Version: " << QT_VERSION_STR;
  // main application
#undef qApp // undef macro qApp out of the way
  QApplication qApp(argc, argv);
  // setup of GUI
  QWidget qWin;
  QVBoxLayout qBox;
  // a boring label
  QLabel qLbl1(QString::fromUtf8("Rather boring"));
  qLbl1.setAlignment(Qt::AlignCenter);
  qBox.addWidget(&qLbl1);
  // a label with frame
  QLabel qLbl2(QString::fromUtf8("Label with Frame"));
  qLbl2.setFrameStyle(QLabel::Panel | QLabel::Raised);
  qLbl2.setLineWidth(2);
  qLbl2.setAlignment(Qt::AlignCenter);
  qBox.addWidget(&qLbl2);
  // a label with rich-text
  QLabel qLbl3(
    QString::fromUtf8(
      "<body bgcolor='#28f'>" // doesn't have the effect
        "<font size='+2' color='#f8e' face='Old English Text MT'>"
          "Label <i>with</i> <b>Rich-Text</b>"
        "</font>"
      "</body>")); // background is set by style-sheet instead
  qLbl3.setTextFormat(Qt::RichText); // might be auto-detected...
  qLbl3.setStyleSheet("QLabel { background-color: #28f; }");
  qLbl3.setAlignment(Qt::AlignCenter);
  qLbl3.show();
  qBox.addWidget(&qLbl3);
  // a home-brew title bar
  TitleBar qTitle("A Home-Brew Title Bar");
  qBox.addWidget(&qTitle);
  // finish setup of GUI
  qWin.setLayout(&qBox);
  qWin.show();
  // run application
  return qApp.exec();
}

TitleBar::TitleBar(const QString &text, QWidget *pQParent):
  QWidget(pQParent)
{
  _option.initFrom(this);
  _option.titleBarFlags = Qt::Window;
  _option.text = text;
}

QSize TitleBar::sizeHint() const
{
#if 0 // does not provide the expected result
  return _option.rect.size();
#elif 0 // does not provide the expected result
  return style()->proxy()->subControlRect(QStyle::CC_TitleBar,
    &_option, QStyle::SC_TitleBarLabel).size();
#else
  return QSize(0,
    style()->proxy()->pixelMetric(QStyle::PM_TitleBarHeight,
      &_option, this));
#endif // 0
}

void TitleBar::resizeEvent(QResizeEvent *pQEvent)
{
  _option.rect = QRect(_option.rect.topLeft(), pQEvent->size());
}

void TitleBar::paintEvent(QPaintEvent *pQEvent)
{
  QPainter qPainter(this);
  style()->proxy()->drawComplexControl(QStyle::CC_TitleBar,
    &_option, &qPainter, this);
}

I compiled and tested it in VS2013 on Windows 10 (64 bit). Below a snapshot:


问:
Contains table not working
I have a full text on a Column Called SearchTerm in a table called Lease.

I tried doing something like:-

```<code>SELECT * FROM CONTAINSTABLE(Lease, SearchTerm, 'Canterbury*')
</code>```

No Records are returned. I do see a record with a SearchTerm equal to - '3 Canterbury Green||Imaging Technology Group'. Yet the record doesn't show up. Can anyone tell me what is going on.

答:
It performs a SQL Server full-text search on full-text indexed columns
  containing character-based data types.

CONTAINSTABLE

```<code>CREATE TABLE Flags (Country nvarchar(30) NOT NULL, FlagColors varchar(200));
CREATE UNIQUE CLUSTERED INDEX FlagKey ON Flags(Country);
INSERT Flags VALUES ('France', 'Blue and White and Red');
INSERT Flags VALUES ('Italy', 'Green and White and Red');
INSERT Flags VALUES ('Tanzania', 'Green and Yellow and Black and Yellow and Blue');
INSERT Flags VALUES ('US', '3 Canterbury Green||Imaging Technology Group');
SELECT * FROM Flags;
GO

CREATE FULLTEXT CATALOG TestFTCat;
CREATE FULLTEXT INDEX ON Flags(FlagColors) KEY INDEX FlagKey ON TestFTCat;
GO

SELECT * FROM Flags;
SELECT * FROM CONTAINSTABLE (Flags, FlagColors, 'Canterbury')
SELECT * FROM CONTAINSTABLE (Flags, FlagColors, '"Canterbury*"')
</code>```

You may have to enclose the '"Canterbury*"' in double quotes as @Richard specified.

It's not necessary to specify the * though as you see the above select gives same results.

Title: Contains table not working

Body:
I have a full text on a Column Called SearchTerm in a table called Lease.

I tried doing something like:-

SELECT * FROM CONTAINSTABLE(Lease, SearchTerm, 'Canterbury*')

No Records are returned. I do see a record with a SearchTerm equal to - '3 Canterbury Green||Imaging Technology Group'. Yet the record doesn't show up. Can anyone tell me what is going on.

Body:
It performs a SQL Server full-text search on full-text indexed columns
  containing character-based data types.

CONTAINSTABLE

CREATE TABLE Flags (Country nvarchar(30) NOT NULL, FlagColors varchar(200));
CREATE UNIQUE CLUSTERED INDEX FlagKey ON Flags(Country);
INSERT Flags VALUES ('France', 'Blue and White and Red');
INSERT Flags VALUES ('Italy', 'Green and White and Red');
INSERT Flags VALUES ('Tanzania', 'Green and Yellow and Black and Yellow and Blue');
INSERT Flags VALUES ('US', '3 Canterbury Green||Imaging Technology Group');
SELECT * FROM Flags;
GO

CREATE FULLTEXT CATALOG TestFTCat;
CREATE FULLTEXT INDEX ON Flags(FlagColors) KEY INDEX FlagKey ON TestFTCat;
GO

SELECT * FROM Flags;
SELECT * FROM CONTAINSTABLE (Flags, FlagColors, 'Canterbury')
SELECT * FROM CONTAINSTABLE (Flags, FlagColors, '"Canterbury*"')

You may have to enclose the '"Canterbury*"' in double quotes as @Richard specified.

It's not necessary to specify the * though as you see the above select gives same results.


问:
SQL Update query is causing two rows in a trigger
I use SQL Server 2005 and have the below question:

On a table A, I have a trigger which tracks any insert/update/delete to it. The tracked records are inserted in an audit table (aAudit). When I run an update on A, I am seeing two rows in the audit table for each update, which is not what I expect. Here is the trigger that I have defined:

```<code>ALTER TRIGGER [ATrigger] ON [dbo].[A]
FOR INSERT, UPDATE, DELETE
AS
INSERT INTO [dbo].[aAudit]
([BusinessDate], [DataTypeId], [BookId], [Version], [DelFlag], [AuditDate], [ExtStatus])
SELECT [BusinessDate], [DataTypeId], [BookId], [Version], 'N', getDate(), 0
FROM inserted

INSERT INTO [dbo].[aAudit]
([BusinessDate], [DataTypeId], [BookId], [Version], [DelFlag], [AuditDate], [ExtStatus])
SELECT [BusinessDate], [DataTypeId], [BookId], [Version], 'Y', getDate(), 0
FROM deleted
</code>```

Why is the above trigger resulting in one row with DelFlag = 'Y' and one row with DelFalg = 'N' in the audit table?

Thanks for taking a look at my question.

Vikram

答:
Behind the scenes, an UPDATE is treated as DELETE the old row and INSERT a new row. So when you do an update, both the INSERTED and DELETED recordsets contain data.

That's why two rows are coming into your audit table from an UPDATE statement.

Body:
I use SQL Server 2005 and have the below question:

On a table A, I have a trigger which tracks any insert/update/delete to it. The tracked records are inserted in an audit table (aAudit). When I run an update on A, I am seeing two rows in the audit table for each update, which is not what I expect. Here is the trigger that I have defined:

ALTER TRIGGER [ATrigger] ON [dbo].[A]
FOR INSERT, UPDATE, DELETE
AS
INSERT INTO [dbo].[aAudit]
([BusinessDate], [DataTypeId], [BookId], [Version], [DelFlag], [AuditDate], [ExtStatus])
SELECT [BusinessDate], [DataTypeId], [BookId], [Version], 'N', getDate(), 0
FROM inserted

INSERT INTO [dbo].[aAudit]
([BusinessDate], [DataTypeId], [BookId], [Version], [DelFlag], [AuditDate], [ExtStatus])
SELECT [BusinessDate], [DataTypeId], [BookId], [Version], 'Y', getDate(), 0
FROM deleted

Why is the above trigger resulting in one row with DelFlag = 'Y' and one row with DelFalg = 'N' in the audit table?

Thanks for taking a look at my question.

Vikram


问:
ng-if inside ng-repeat is not filtering my array
Hy evryone, im trying to display tabs with a value inside my types array wchich has

```<code>[{"label":"wlan1","type":"wlan1"},
 {"label":"br-wlan","type":"br-wlan"},
 {"label":"tun_cas","type":"tun_cas"},
 {"label":"nfacct_bytes","type":"nfacct_bytes"},
 {"label":"wlan0","type":"wlan0"},
 {"label":"lte0","type":"lte0"},
 {"label":"nfacct_packets","type":"nfacct_packets"}]
</code>```

In my view I dont want to display the types nfacct_bytes and nfacct_packets and for that I was doing:

```<code><tab ng-if="type.label !== 'nfacct_bytes' || type.label !== 'nfacct_packets'"
     ng-repeat="type in dataGraph.network.types" heading="{{type.label}}"
     select="changeSubTab(type.type)" disable="!tabClick" >
</code>```

Solution:

```<code><tab ng-if="type.label !== 'nfacct_bytes' && type.label !== 'nfacct_packets'"
     ng-repeat="type in dataGraph.network.types" heading="{{type.label}}"
     select="changeSubTab(type.type)" disable="!tabClick" >
</code>```

答:
Use filter function of angularJS. It Selects a subset of items from array and returns it as a new array.

In filter the expression could be of string,object or function. Here I have used expression as object.

Let the controller be like this

```<code>  app.controller('MainCtrl', function($scope) {
    $scope.Values =
     [{"label":"wlan1","type":"wlan1"},
     {"label":"br-wlan","type":"br-wlan"},
     {"label":"tun_cas","type":"tun_cas"},
     {"label":"nfacct_bytes","type":"nfacct_bytes"},
     {"label":"wlan0","type":"wlan0"},
     {"label":"lte0","type":"lte0"},
    {"label":"nfacct_packets","type":"nfacct_packets"}];
});
</code>```

The required HTML

```<code>  <div ng-repeat="value in Values |filter: {type: '!nfacct_bytes'}">
      {{value.label}}
  </div>
</code>```

Working plunker https://plnkr.co/edit/IUvaZbzHdV0M1s9TRzAq?p=preview

Body:
Hy evryone, im trying to display tabs with a value inside my types array wchich has

[{"label":"wlan1","type":"wlan1"},
 {"label":"br-wlan","type":"br-wlan"},
 {"label":"tun_cas","type":"tun_cas"},
 {"label":"nfacct_bytes","type":"nfacct_bytes"},
 {"label":"wlan0","type":"wlan0"},
 {"label":"lte0","type":"lte0"},
 {"label":"nfacct_packets","type":"nfacct_packets"}]

In my view I dont want to display the types nfacct_bytes and nfacct_packets and for that I was doing:

<tab ng-if="type.label !== 'nfacct_bytes' || type.label !== 'nfacct_packets'"
     ng-repeat="type in dataGraph.network.types" heading="{{type.label}}"
     select="changeSubTab(type.type)" disable="!tabClick" >

Solution:

<tab ng-if="type.label !== 'nfacct_bytes' && type.label !== 'nfacct_packets'"
     ng-repeat="type in dataGraph.network.types" heading="{{type.label}}"
     select="changeSubTab(type.type)" disable="!tabClick" >

Body:
Use filter function of angularJS. It Selects a subset of items from array and returns it as a new array.

In filter the expression could be of string,object or function. Here I have used expression as object.

Let the controller be like this

  app.controller('MainCtrl', function($scope) {
    $scope.Values =
     [{"label":"wlan1","type":"wlan1"},
     {"label":"br-wlan","type":"br-wlan"},
     {"label":"tun_cas","type":"tun_cas"},
     {"label":"nfacct_bytes","type":"nfacct_bytes"},
     {"label":"wlan0","type":"wlan0"},
     {"label":"lte0","type":"lte0"},
    {"label":"nfacct_packets","type":"nfacct_packets"}];
});

The required HTML

  <div ng-repeat="value in Values |filter: {type: '!nfacct_bytes'}">
      {{value.label}}
  </div>

Working plunker https://plnkr.co/edit/IUvaZbzHdV0M1s9TRzAq?p=preview


问:
How to install pydot_ng and graphviz for Windows 64, Python 3.6?
I'm trying to install pydot_ng and graphviz through Anaconda Navigator but I keep getting this error for pydot_ng (1.0.0.15):

```<code>UnsatisfiableError: The following specifications were found to be in conflict:
  - pydot-ng -> python 2.7*
  - python 3.6*
Use "conda info <package>" to see the dependencies for each package.
</code>```

How do I proceed?
I cannot use Keras visualization tools without pydot.
I have installed pydot plus but Keras seems to reject it with this error in iPython notebook.

```<code>  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\utils\vis_utils.py", line 131, in plot_model
    dot = model_to_dot(model, show_shapes, show_layer_names, rankdir)

  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\utils\vis_utils.py", line 52, in model_to_dot
    _check_pydot()

  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\utils\vis_utils.py", line 27, in _check_pydot
    raise ImportError('Failed to import pydot. You must install pydot'

ImportError: Failed to import pydot. You must install pydot and graphviz for `pydotprint` to work.
</code>```

答:
You are trying to install a Python 2.7 package in a Python 3.5 environment.

Maybe this helps:
How can I use conda to install pydot?

Body:
I'm trying to install pydot_ng and graphviz through Anaconda Navigator but I keep getting this error for pydot_ng (1.0.0.15):

UnsatisfiableError: The following specifications were found to be in conflict:
  - pydot-ng -> python 2.7*
  - python 3.6*
Use "conda info <package>" to see the dependencies for each package.

How do I proceed?
I cannot use Keras visualization tools without pydot.
I have installed pydot plus but Keras seems to reject it with this error in iPython notebook.

  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\utils\vis_utils.py", line 131, in plot_model
    dot = model_to_dot(model, show_shapes, show_layer_names, rankdir)

  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\utils\vis_utils.py", line 52, in model_to_dot
    _check_pydot()

  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\utils\vis_utils.py", line 27, in _check_pydot
    raise ImportError('Failed to import pydot. You must install pydot'

ImportError: Failed to import pydot. You must install pydot and graphviz for `pydotprint` to work.


问:
ASP.NET MVC Set Views folder on controller
If you have created a controller like:

```<code>public class ProjectLoginController : Controller
{
    /// <summary>
    /// GET: /login
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    [AllowAnonymous]
    public ActionResult Login()
    {
        return View();
    }
}
</code>```

It will search for the login view in the ProjectLogin or the Shared folder.

Is it possible to tell MVC for this controller to search in the views folder Account under Viewsinstead of doing:

```<code>return View("~/Views/Account/Login.cshtml");
</code>```

or:

```<code>return View("../Account/Login");
</code>```

答:
You can use RedirectToAction() method for this. For example,

```<code>return RedirectToAction("LogIn", "Account");
</code>```

Or-else, do like this,

```<code>return View("../Account/Login");
</code>```

Hoe it helps :)

Body:
If you have created a controller like:

public class ProjectLoginController : Controller
{
    ///
    /// GET: /login
    ///
    /// <returns></returns>
    [HttpGet]
    [AllowAnonymous]
    public ActionResult Login()
    {
        return View();
    }
}

It will search for the login view in the ProjectLogin or the Shared folder.

Is it possible to tell MVC for this controller to search in the views folder Account under Viewsinstead of doing:

return View("~/Views/Account/Login.cshtml");

or:

return View("../Account/Login");

Body:
You can use RedirectToAction() method for this. For example,

return RedirectToAction("LogIn", "Account");

Or-else, do like this,

return View("../Account/Login");

Hoe it helps :)


问:
If checkmark is on - add object to the array [SWIFT]
Here is my code, but it doesn't saving user name into array

```<code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    // тут проверяем если ячейка уже выбрана то удаляем из массива и убираем чекмарк
    // если не выбрана то добавляем в массив и ставим чекмарк
    if tableView.cellForRow(at: indexPath)?.accessoryType == .checkmark {
        let cell = UITableViewCell()
        usersInGame.add(cell.textLabel?.text)
    } else {

        tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
    }
    tableView.deselectRow(at: indexPath, animated: false) //убираем выделение ячейки если не нужно обратное
    let usersInGame: NSMutableArray = []
}
</code>```

I understood that it doesn't work, because when i turn on checkmark code doesn't work. Please help!

答:
Look like you are creating a new cell and try to retrieve the text. Also, the local usersInGame is not needed as pointed out by @Samarth Kejriwal

```<code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if let cell = tableView.cellForRow(at: indexPath), cell.accessoryType == .checkmark {
        usersInGame.add(cell.textLabel?.text)
    } else {
        tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
    }
    tableView.deselectRow(at: indexPath, animated: false)
}
</code>```

Try this instead. Also, set a breakpoint to ensure that it go into usersInGame. Might have some syntax error, I am working on a laptop without XCode.

Body:
Here is my code, but it doesn't saving user name into array

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    // тут проверяем если ячейка уже выбрана то удаляем из массива и убираем чекмарк
    // если не выбрана то добавляем в массив и ставим чекмарк
    if tableView.cellForRow(at: indexPath)?.accessoryType == .checkmark {
        let cell = UITableViewCell()
        usersInGame.add(cell.textLabel?.text)
    } else {

        tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
    }
    tableView.deselectRow(at: indexPath, animated: false) //убираем выделение ячейки если не нужно обратное
    let usersInGame: NSMutableArray = []
}

I understood that it doesn't work, because when i turn on checkmark code doesn't work. Please help!

Body:
Look like you are creating a new cell and try to retrieve the text. Also, the local usersInGame is not needed as pointed out by @Samarth Kejriwal

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if let cell = tableView.cellForRow(at: indexPath), cell.accessoryType == .checkmark {
        usersInGame.add(cell.textLabel?.text)
    } else {
        tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
    }
    tableView.deselectRow(at: indexPath, animated: false)
}

Try this instead. Also, set a breakpoint to ensure that it go into usersInGame. Might have some syntax error, I am working on a laptop without XCode.


问:
Xcode 8 App installation failed, unknown error occured

The following error occurred when I tried to run a project on my iOS device. Running it on a simulator works fine.

The other weird thing is that I am able to run my other projects on my device, only this particular project that is giving me this error.

I tried all the solutions I'm able to find:

Cleaning the project, deleting derived data

Restarting Xcode, my Mac, and my iOS device

Deselect 'Automatically manage signing' in the testing Target.

I couldn't delete the app from my device and re-install it because it wasn't installed on my device before.

Any help would mean alot to me! I am using Xcode 8.1 with Swift 3.0, running on a iOS 10.1.1 device.

答: Clean your the project and reattach your device </p>


问:
opencv2.framework/opencv2(shapedescr.o)' does not contain bitcode. You must rebuild it with bitcode enabled (Xcode setting ENABLE_BITCODE)
Ld /Users/XXXXX/Library/Developer/Xcode/DerivedData/MMCamScanner-ayaaebcalydwgeeenncrtqxmthsh/Build/Products/Debug-iphoneos/MMCamScanner.app/MMCamScanner normal arm64
    cd /Users/XXXXXX/Desktop/SwiftDemo/MMCamScanner
    export IPHONEOS_DEPLOYMENT_TARGET=10.3
    export PATH="/Users/XXXXXXX/Downloads/Xcode

2.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Users/XXXXXXX/Downloads/Xcode 2.app/Contents/Developer/usr/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
    /Users/XXXXXXX/Downloads/Xcode\ 2.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang++ -arch arm64 -isysroot /Users/sravanthigumma/Downloads/Xcode\ 2.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS10.3.sdk -L/Users/XXXXXXXX/Library/Developer/Xcode/DerivedData/MMCamScanner-ayaaebcalydwgeeenncrtqxmthsh/Build/Products/Debug-iphoneos -F/Users/XXXXXXX/Library/Developer/Xcode/DerivedData/MMCamScanner-ayaaebcalydwgeeenncrtqxmthsh/Build/Products/Debug-iphoneos -F/Users/XXXX/Desktop/SwiftDemo/MMCamScanner -filelist /Users/XXXX/Library/Developer/Xcode/DerivedData/MMCamScanner-ayaaebcalydwgeeenncrtqxmthsh/Build/Intermediates/MMCamScanner.build/Debug-iphoneos/MMCamScanner.build/Objects-normal/arm64/MMCamScanner.LinkFileList -Xlinker -rpath -Xlinker @executable_path/Frameworks -miphoneos-version-min=10.3 -dead_strip -Xlinker -object_path_lto -Xlinker /Users/XXXXX/Library/Developer/Xcode/DerivedData/MMCamScanner-ayaaebcalydwgeeenncrtqxmthsh/Build/Intermediates/MMCamScanner.build/Debug-iphoneos/MMCamScanner.build/Objects-normal/arm64/MMCamScanner_lto.o -Xlinker -export_dynamic -Xlinker -no_deduplicate -fembed-bitcode-marker -fobjc-arc -fobjc-link-runtime -stdlib=libc++ -framework opencv2 -framework TesseractOCR -framework AVFoundation -framework CoreGraphics -framework AssetsLibrary -framework CoreImage -lstdc++ -framework CoreTelephony -framework MobileCoreServices -Xlinker -dependency_info -Xlinker /Users/XXXX/Library/Developer/Xcode/DerivedData/MMCamScanner-ayaaebcalydwgeeenncrtqxmthsh/Build/Intermediates/MMCamScanner.build/Debug-iphoneos/MMCamScanner.build/Objects-normal/arm64/MMCamScanner_dependency_info.dat -o /Users/XXXXXXX/Library/Developer/Xcode/DerivedData/MMCamScanner-ayaaebcalydwgeeenncrtqxmthsh/Build/Products/Debug-iphoneos/MMCamScanner.app/MMCamScanner

答: Go to Build Settings > Choose Enable Bitcode and Set it value to YES.</p>


问:
SQLite Database Locked exception
I am getting Database is locked exception from SQLite for some queries only.

Below is my code:
When I execute any select statement it works fine.

When I am executing any write statement on Jobs Table it also works fine.

This works fine:

```<code>ExecuteNonQuery("DELETE FROM Jobs WHERE id=1");
</code>```

But the same way if I am executing queries for Employees table it is throwing an exception that database is locked.

This throws Exception:

```<code>ExecuteNonQuery("DELETE FROM Employees WHERE id=1");
</code>```

Below are my functions:

```<code>public bool OpenConnection()
{
    if (Con == null)
    {
        Con = new SQLiteConnection(ConnectionString);
    }
    if (Con.State == ConnectionState.Closed)
    {
        Con.Open();
        //Cmd = new SQLiteCommand("PRAGMA FOREIGN_KEYS=ON", Con);
        //Cmd.ExecuteNonQuery();
        //Cmd.Dispose();
        //Cmd=null;
        return true;
    }
    if (IsConnectionBusy())
    {
        Msg.Log(new Exception("Connection busy"));
    }
    return false;
}

public Boolean CloseConnection()
{
    if (Con != null && Con.State == ConnectionState.Open)
    {
        if (Cmd != null) Cmd.Dispose();
        Cmd = null;
        Con.Close();
        return true;
    }

    return false;
}

public Boolean ExecuteNonQuery(string sql)
{
    if (sql == null) return false;
    try
    {
        if (!OpenConnection())
            return false;
        else
        {
            //Tx = Con.BeginTransaction(IsolationLevel.ReadCommitted);
            Cmd = new SQLiteCommand(sql, Con);
            Cmd.ExecuteNonQuery();
            //Tx.Commit();
            return true;
        }
    }
    catch (Exception exception)
    {
        //Tx.Rollback();
        Msg.Log(exception);
        return false;
    }
    finally
    {
        CloseConnection();
    }
}
</code>```

This is the Exception:
At line 103 : Cmd.ExecuteNonQuery();

Exception Found:
        Type: System.Data.SQLite.SQLiteException
       Message: database is locked
      database is locked
       Source: System.Data.SQLite

Stacktrace:    at System.Data.SQLite.SQLite3.Step(SQLiteStatement stmt)
         at System.Data.SQLite.SQLiteDataReader.NextResult()
         at System.Data.SQLite.SQLiteDataReader..ctor(SQLiteCommand cmd, CommandBehavior behave)
         at System.Data.SQLite.SQLiteCommand.ExecuteReader(CommandBehavior behavior)
         at System.Data.SQLite.SQLiteCommand.ExecuteNonQuery()
         at TimeSheet6.DbOp.ExecuteNonQuery(String sql) in d:\Projects\C# Applications\Completed Projects\TimeSheet6\TimeSheet6\DbOp.cs:line 103

答:
I was also getting the same error here:

```<code>if (new basics.HindiMessageBox(HMsg, HTitle).ShowDialog()==true)
{
    SQLiteConnection m_dbConnection = new SQLiteConnection(MainWindow.con);
    m_dbConnection.Open();
    sql = "DELETE FROM `users`  WHERE `id`=" + SelectedUser.Id;
    command = new SQLiteCommand(sql, m_dbConnection);
    command.ExecuteNonQuery();
    m_dbConnection.Close();
    LoadUserDG();
}
</code>```

but when I just changed SQLiteConnection declaration location

```<code>public partial class User : Window
{
    SQLiteCommand command;
    string sql;
    AddUser AddUserObj;
    List<basics.users> usersList;
    basics.users SelectedUser;
    SQLiteConnection m_dbConnection;

    // ...

    private void DeleteBtn_Click(object sender, RoutedEventArgs e)
    {
        // ...
        if (new basics.HindiMessageBox(HMsg, HTitle).ShowDialog()==true)
        {
            m_dbConnection = new SQLiteConnection(MainWindow.con);
            m_dbConnection.Open();
            sql = "DELETE FROM `users`  WHERE `id`=" + SelectedUser.Id;
            command = new SQLiteCommand(sql, m_dbConnection);
            command.ExecuteNonQuery();
            m_dbConnection.Close();
            LoadUserDG();
        }
}
</code>```

Everything is fine now.
I hope this may work for you, too.
If someone can say how this happened, I would like to know the details to improve my knowledge, please.

Title: SQLite Database Locked exception

Body:
I am getting Database is locked exception from SQLite for some queries only.

Below is my code:
When I execute any select statement it works fine.

When I am executing any write statement on Jobs Table it also works fine.

This works fine:

ExecuteNonQuery("DELETE FROM Jobs WHERE id=1");

But the same way if I am executing queries for Employees table it is throwing an exception that database is locked.

This throws Exception:

ExecuteNonQuery("DELETE FROM Employees WHERE id=1");

Below are my functions:

public bool OpenConnection()
{
    if (Con == null)
    {
        Con = new SQLiteConnection(ConnectionString);
    }
    if (Con.State == ConnectionState.Closed)
    {
        Con.Open();
        //Cmd = new SQLiteCommand("PRAGMA FOREIGN_KEYS=ON", Con);
        //Cmd.ExecuteNonQuery();
        //Cmd.Dispose();
        //Cmd=null;
        return true;
    }
    if (IsConnectionBusy())
    {
        Msg.Log(new Exception("Connection busy"));
    }
    return false;
}

public Boolean CloseConnection()
{
    if (Con != null && Con.State == ConnectionState.Open)
    {
        if (Cmd != null) Cmd.Dispose();
        Cmd = null;
        Con.Close();
        return true;
    }

    return false;
}

public Boolean ExecuteNonQuery(string sql)
{
    if (sql == null) return false;
    try
    {
        if (!OpenConnection())
            return false;
        else
        {
            //Tx = Con.BeginTransaction(IsolationLevel.ReadCommitted);
            Cmd = new SQLiteCommand(sql, Con);
            Cmd.ExecuteNonQuery();
            //Tx.Commit();
            return true;
        }
    }
    catch (Exception exception)
    {
        //Tx.Rollback();
        Msg.Log(exception);
        return false;
    }
    finally
    {
        CloseConnection();
    }
}

This is the Exception:
At line 103 : Cmd.ExecuteNonQuery();

Exception Found:
        Type: System.Data.SQLite.SQLiteException
       Message: database is locked
      database is locked
       Source: System.Data.SQLite

Stacktrace:    at System.Data.SQLite.SQLite3.Step(SQLiteStatement stmt)
         at System.Data.SQLite.SQLiteDataReader.NextResult()
         at System.Data.SQLite.SQLiteDataReader..ctor(SQLiteCommand cmd, CommandBehavior behave)
         at System.Data.SQLite.SQLiteCommand.ExecuteReader(CommandBehavior behavior)
         at System.Data.SQLite.SQLiteCommand.ExecuteNonQuery()
         at TimeSheet6.DbOp.ExecuteNonQuery(String sql) in d:\Projects\C# Applications\Completed Projects\TimeSheet6\TimeSheet6\DbOp.cs:line 103

Body:
I was also getting the same error here:

if (new basics.HindiMessageBox(HMsg, HTitle).ShowDialog()==true)
{
    SQLiteConnection m_dbConnection = new SQLiteConnection(MainWindow.con);
    m_dbConnection.Open();
    sql = "DELETE FROM `users`  WHERE `id`=" + SelectedUser.Id;
    command = new SQLiteCommand(sql, m_dbConnection);
    command.ExecuteNonQuery();
    m_dbConnection.Close();
    LoadUserDG();
}

but when I just changed SQLiteConnection declaration location

public partial class User : Window
{
    SQLiteCommand command;
    string sql;
    AddUser AddUserObj;
    List<basics.users> usersList;
    basics.users SelectedUser;
    SQLiteConnection m_dbConnection;

    // ...

    private void DeleteBtn_Click(object sender, RoutedEventArgs e)
    {
        // ...
        if (new basics.HindiMessageBox(HMsg, HTitle).ShowDialog()==true)
        {
            m_dbConnection = new SQLiteConnection(MainWindow.con);
            m_dbConnection.Open();
            sql = "DELETE FROM `users`  WHERE `id`=" + SelectedUser.Id;
            command = new SQLiteCommand(sql, m_dbConnection);
            command.ExecuteNonQuery();
            m_dbConnection.Close();
            LoadUserDG();
        }
}

Everything is fine now.
I hope this may work for you, too.
If someone can say how this happened, I would like to know the details to improve my knowledge, please.


问:
How can I prevent users from entering data into DataGridViewComboBoxCells?
I have a project that uses a number of DataGridView controls.  Most of the cells are of the  DataGridViewTextBoxCell persuasion.  I declare my controls like so:

```<code>Dim MyCell as DataGridViewCell
</code>```

Later I specify whether they are DataGridViewTextBoxControls or DataGridViewComboBoxCells like so:

```<code>MyCell = New DataGridViewTextBoxCell   ...or...
MyCell = New DataGridViewComboBoxCell
</code>```

None of the places in my code require the ability for the users to enter their own values in the Combo Boxes.  That is, they are either hard-coded or the values are gathered from other data within the application.

Currently, users can highlight a combo box control defined as shown above and begin typing anything they like.  For example, I have one combo box that offers the user a selection of integers between 1 and 9.  I can highlight the combo box cell and enter "Hello, World!" if I'd like.

What does it take to disable this ability?  I'm sure there's a property, but I have yet to find it.  I have searched the Internet, and have found only the ability to have user-entered values added to the list and a stream of data-binding tutorials.

Thank you in advance!
C

答:
Check here

EDIT

I probably should have put more information up, but I'm tired and feeling a little sick so I felt like being lazy ... but no you have to ruin my laziness and force me to type some more. (LOL just joking).

Essentially the comboxbox that you see in a comboboxcell is acutally a combobox control (Tired = Bad Engrish).

From what I can recall, you should be able to get at the control used in the cell by using the EditingControlShowing event of the datagridview. Once there you just set the dropdownstyle.

Like:

```<code>Private Sub datagridview_EditingControlShowing(ByVal sender As Object, ByVal e As DataGridViewEditingControlShowingEventArgs)

    Dim c As ComboBox = e.Control

    If Not c Is Nothing Then

        c.DropDownStyle = ComboBoxStyle.DropDownList

    End If

End Sub
</code>```

Body:
I have a project that uses a number of DataGridView controls.  Most of the cells are of the  DataGridViewTextBoxCell persuasion.  I declare my controls like so:

Dim MyCell as DataGridViewCell

Later I specify whether they are DataGridViewTextBoxControls or DataGridViewComboBoxCells like so:

MyCell = New DataGridViewTextBoxCell   ...or...
MyCell = New DataGridViewComboBoxCell

None of the places in my code require the ability for the users to enter their own values in the Combo Boxes.  That is, they are either hard-coded or the values are gathered from other data within the application.

Currently, users can highlight a combo box control defined as shown above and begin typing anything they like.  For example, I have one combo box that offers the user a selection of integers between 1 and 9.  I can highlight the combo box cell and enter "Hello, World!" if I'd like.

What does it take to disable this ability?  I'm sure there's a property, but I have yet to find it.  I have searched the Internet, and have found only the ability to have user-entered values added to the list and a stream of data-binding tutorials.

Thank you in advance!
C

Body:
Check here

EDIT

I probably should have put more information up, but I'm tired and feeling a little sick so I felt like being lazy ... but no you have to ruin my laziness and force me to type some more. (LOL just joking).

Essentially the comboxbox that you see in a comboboxcell is acutally a combobox control (Tired = Bad Engrish).

From what I can recall, you should be able to get at the control used in the cell by using the EditingControlShowing event of the datagridview. Once there you just set the dropdownstyle.

Like:

Private Sub datagridview_EditingControlShowing(ByVal sender As Object, ByVal e As DataGridViewEditingControlShowingEventArgs)

    Dim c As ComboBox = e.Control

    If Not c Is Nothing Then

        c.DropDownStyle = ComboBoxStyle.DropDownList

    End If

End Sub


问:
Enable Stepped lines in Chart.Js
I am trying to enable stepped lines in ChartJs 2.6.0

```<code>var chartJsObj = {
        data: {
            labels: ["January", "February", "March", "April", "May", "June", "July"],
            datasets: [{
                label: "My First dataset",
                data: [2, 23, 15, 16, 24, 21, 17, 13],
                borderColor: 'rgb(54, 162, 235)',
                fill: false,
                steppedLine: true
            }],
        },

    }
</code>```

But it draws a normal curved line. Any suggestions?

答:
Check out the examples of Chartjs on Github, multiple stepped line chart examples included - https://github.com/chartjs/Chart.js/blob/master/samples/charts/line/stepped.html

The example from there recreated on Codepen - https://codepen.io/Inlesco/pen/yXEvOz

The configs for steppedLine on each chart in the Codepen example are defined in small chunks such as:

```<code>{
    steppedLine: true,
    label: 'No Step Interpolation',
    color: window.chartColors.red
}
</code>```

Title: Enable Stepped lines in Chart.Js

Body:
I am trying to enable stepped lines in ChartJs 2.6.0

var chartJsObj = {
        data: {
            labels: ["January", "February", "March", "April", "May", "June", "July"],
            datasets: [{
                label: "My First dataset",
                data: [2, 23, 15, 16, 24, 21, 17, 13],
                borderColor: 'rgb(54, 162, 235)',
                fill: false,
                steppedLine: true
            }],
        },

    }

But it draws a normal curved line. Any suggestions?

Body:
Check out the examples of Chartjs on Github, multiple stepped line chart examples included - https://github.com/chartjs/Chart.js/blob/master/samples/charts/line/stepped.html

The example from there recreated on Codepen - https://codepen.io/Inlesco/pen/yXEvOz

The configs for steppedLine on each chart in the Codepen example are defined in small chunks such as:

{
    steppedLine: true,
    label: 'No Step Interpolation',
    color: window.chartColors.red
}


问:
Using pointers and structs
Hello i'm not sure if I'm understand the following piece of code. I would glad if someone could read my explanations and correct me if I'm wrong.

 So first of all I'm declaring a struct with three arrays of char and an integer.

```<code>struct Employee
{
    char last[16];
    char first[11];
    char title[16];
    int salary;
};
</code>```

 After that I declare a function which takes three pointers to char and an integer value. This function uses malloc() and sizeof() to create a struct on the heap. Now this creations of the object on the heap is not really clear to me. When I use struct Employee* p = malloc(sizeof(struct Employee)), what happens there exactly?
 What happens when I use the function struct Employee* createEmployee (char* last, char* first, char* title, int salary) several times with different input. I know that I will get back a pointer p but isn't that the same pointer to the same struct on the heap. So do I rewrite the information on the heap, when I use the function several times? Or does it always create a new object in a different memory space?

```<code>struct Employee* createEmployee(char*, char*, char*, int);

struct Employee* createEmployee(char* last, char* first, char* title, int salary)
{
    struct Employee* p = malloc(sizeof(struct Employee));
    if (p != NULL)
    {
        strcpy(p->last, last);
        strcpy(p->first, first);
        strcpy(p->title, title);
        p->salary = salary;
    }
    return p;
}
</code>```

I would be glad if someone could explain it to me. Thank you very much.

答:
The malloc function allocates some new bytes on the heap and returns the pointer.

So the createEmployee function allocates new memory every time it's called, then fills it with some data (in an unsafe way - consider using strncpy instead) and returns the pointer to that memory. It will return a different pointer every time it's called.

Each instance you create with this function will exist as long as you don't call free on its pointer.

Title: Using pointers and structs

Body:
Hello i'm not sure if I'm understand the following piece of code. I would glad if someone could read my explanations and correct me if I'm wrong.

 So first of all I'm declaring a struct with three arrays of char and an integer.

struct Employee
{
    char last[16];
    char first[11];
    char title[16];
    int salary;
};

 After that I declare a function which takes three pointers to char and an integer value. This function uses malloc() and sizeof() to create a struct on the heap. Now this creations of the object on the heap is not really clear to me. When I use struct Employee* p = malloc(sizeof(struct Employee)), what happens there exactly?
 What happens when I use the function struct Employee* createEmployee (char* last, char* first, char* title, int salary) several times with different input. I know that I will get back a pointer p but isn't that the same pointer to the same struct on the heap. So do I rewrite the information on the heap, when I use the function several times? Or does it always create a new object in a different memory space?

struct Employee* createEmployee(char*, char*, char*, int);

struct Employee* createEmployee(char* last, char* first, char* title, int salary)
{
    struct Employee* p = malloc(sizeof(struct Employee));
    if (p != NULL)
    {
        strcpy(p->last, last);
        strcpy(p->first, first);
        strcpy(p->title, title);
        p->salary = salary;
    }
    return p;
}

I would be glad if someone could explain it to me. Thank you very much.


问:
using sed to search and replace the first word(string is divide by whitespace) in a string
An input string: "a-random_name /this/is/a/path_to-file 0"

An output string: "arandomname /this/is/a/path_to-file 0"

using sed only replace the first word. word is a random string.

答:
Try this simple awk method

```<code>awk  '{gsub(/-|_/,"",$1); print}' <<< '"a-random_name /this/is/a/path_to-file 0"'
</code>```

Output :

```<code>"arandomname /this/is/a/path_to-file 0"
</code>```

Explanation:

Extract first column based on default space delimiter and remove - and _ using gsub function

Sed version :

I am not sure this is the effective method or not but it will help you

```<code>sed -e 's/-\|_//1' -e  's/-\|_//1' <<< '"a-random_name /this/is/a/path_to-file 0"'
</code>```

Body:
Try this simple awk method

awk  '{gsub(/-|_/,"",$1); print}' <<< '"a-random_name /this/is/a/path_to-file 0"'

Output :

"arandomname /this/is/a/path_to-file 0"

Explanation:

Extract first column based on default space delimiter and remove - and _ using gsub function

Sed version :

I am not sure this is the effective method or not but it will help you

sed -e 's/-\|_//1' -e  's/-\|_//1' <<< '"a-random_name /this/is/a/path_to-file 0"'


问:
Smart Table not refreshing on setTimeout
The code related to table generation is not working in the below function

```<code>function populateDataTable(repo_contributor,repo_langauges){
    $scope.rowCollection = [
        {firstName: 'Laurent', lastName: 'Renard', birthDate: new Date('1987-05-21'), balance: 102, email: 'whatever@gmail.com'},
        {firstName: 'Blandine', lastName: 'Faivre', birthDate: new Date('1987-04-25'), balance: -2323.22, email: 'oufblandou@gmail.com'},
        {firstName: 'Francoise', lastName: 'Frere', birthDate: new Date('1955-08-27'), balance: 42343, email: 'raymondef@gmail.com'}
    ];

 for (var key in repo_contributor){
    console.log(repo_contributor[key]);
    var repo_table_data = {};
    repo_table_data['repo_name'] = key;
    repo_table_data['contributors'] = repo_contributor[key].toString();
    repo_table_data['languages'] = repo_langauges[key].toString();
     console.log(repo_table_data);
    $scope.repo_info_list.push(repo_table_data);
}
    console.log("here now");
    console.log($scope.repo_info_list.length);

}
</code>```

the populateDataTable is being populated by the below code

```<code>setTimeout(populateDataTable,4000,$scope.repo_contributor,$scope.repo_languages);
</code>```

$scope.rowCollection is being set but not being displayed on table( table is empty).

However if $scope.rowCollection is placed outside the populateDataTable, the table is populated with correct values.

Your help is greatly appreciated.

答:
As mentioned by Hadi, setTimeout did not work but $timeout with function parameters worked.

i.e

```<code>$timeout(populateDataTable, 4000,true,$scope.repo_contributor,$scope.repo_languages)
</code>```

Body:
The code related to table generation is not working in the below function

function populateDataTable(repo_contributor,repo_langauges){
    $scope.rowCollection = [
        {firstName: 'Laurent', lastName: 'Renard', birthDate: new Date('1987-05-21'), balance: 102, email: 'whatever@gmail.com'},
        {firstName: 'Blandine', lastName: 'Faivre', birthDate: new Date('1987-04-25'), balance: -2323.22, email: 'oufblandou@gmail.com'},
        {firstName: 'Francoise', lastName: 'Frere', birthDate: new Date('1955-08-27'), balance: 42343, email: 'raymondef@gmail.com'}
    ];

 for (var key in repo_contributor){
    console.log(repo_contributor[key]);
    var repo_table_data = {};
    repo_table_data['repo_name'] = key;
    repo_table_data['contributors'] = repo_contributor[key].toString();
    repo_table_data['languages'] = repo_langauges[key].toString();
     console.log(repo_table_data);
    $scope.repo_info_list.push(repo_table_data);
}
    console.log("here now");
    console.log($scope.repo_info_list.length);

}

the populateDataTable is being populated by the below code

setTimeout(populateDataTable,4000,$scope.repo_contributor,$scope.repo_languages);

$scope.rowCollection is being set but not being displayed on table( table is empty).

However if $scope.rowCollection is placed outside the populateDataTable, the table is populated with correct values.

Your help is greatly appreciated.

Body:
As mentioned by Hadi, setTimeout did not work but $timeout with function parameters worked.

i.e

$timeout(populateDataTable, 4000,true,$scope.repo_contributor,$scope.repo_languages)


问:
When should I use nil and NULL in Objective-C?
This is sample code:

```<code>NSDictionary *myDictionary = [NSDictionary dictionary];
NSNumber *myNumber = [myDictionary valueForKey: @"MyNumber"];
NSLog(@"myNumber = %@", myNumber); // output myNumber = (null)

if (myNumber == nil)
    NSLog(@"test 1 myNumber == nil");

if (myNumber == NULL)
    NSLog(@"test 2 myNumber == NULL");

if ([myNumber isEqual:[NSNull null]])
    NSLog(@"test 3 myNumber == [NSNull null]");
</code>```

When should I use nil, NULL and [NSNull null]?

答:
This will help you to understand the difference between nil, NIL and null.

The below link may help you in some way:

http://nshipster.com/nil/

nil -> literal null value for Objective-C objects.

Nil -> literal null value for Objective-C classes.

NULL -> literal null value for C pointers.

NSNULL -> singleton object used to represent null.

Body:
This is sample code:

NSDictionary *myDictionary = [NSDictionary dictionary];
NSNumber *myNumber = [myDictionary valueForKey: @"MyNumber"];
NSLog(@"myNumber = %@", myNumber); // output myNumber = (null)

if (myNumber == nil)
    NSLog(@"test 1 myNumber == nil");

if (myNumber == NULL)
    NSLog(@"test 2 myNumber == NULL");

if ([myNumber isEqual:[NSNull null]])
    NSLog(@"test 3 myNumber == [NSNull null]");

When should I use nil, NULL and [NSNull null]?


问:
retrieving number of observations with non missing values
I would like to compute the number of observations (Persons in my following example) that have non-missing values.

```<code>unbal <- data.frame(PERSON=c(rep('Frank',5),rep('Tony',5),rep('Edward',5)), YEAR=c(2001,2002,2003,2004,2005,2001,2002,2003,2004,2005,2001,2002,2003,2004,2005), Y=c(21,22,23,24,25,5,6,NA,7,8,31,32,33,34,35), X=c(1:15))
unbal

   PERSON YEAR  Y  X
1   Frank 2001 21  1
2   Frank 2002 22  2
3   Frank 2003 23  3
4   Frank 2004 24  4
5   Frank 2005 25  5
6    Tony 2001  5  6
7    Tony 2002  6  7
8    Tony 2003 NA  8
9    Tony 2004  7  9
10   Tony 2005  8 10
11 Edward 2001 31 11
12 Edward 2002 32 12
13 Edward 2003 33 13
14 Edward 2004 34 14
15 Edward 2005 35 15
</code>```

In this case will be 2, since only two persons (Frank and Edward) have all the data.

答:
I would do it like this :</p>

```<code>cp = 0

for (i in unique(unbal$PERSON)){
  new_data = unbal[which(unbal$PERSON == i),]
  if (anyNA(new_data) == FALSE){
    cp = cp+1
  }else{
    cp = cp
  }
}

cp
</code>```

Body:
I would like to compute the number of observations (Persons in my following example) that have non-missing values.

unbal <- data.frame(PERSON=c(rep('Frank',5),rep('Tony',5),rep('Edward',5)), YEAR=c(2001,2002,2003,2004,2005,2001,2002,2003,2004,2005,2001,2002,2003,2004,2005), Y=c(21,22,23,24,25,5,6,NA,7,8,31,32,33,34,35), X=c(1:15))
unbal

   PERSON YEAR  Y  X
1   Frank 2001 21  1
2   Frank 2002 22  2
3   Frank 2003 23  3
4   Frank 2004 24  4
5   Frank 2005 25  5
6    Tony 2001  5  6
7    Tony 2002  6  7
8    Tony 2003 NA  8
9    Tony 2004  7  9
10   Tony 2005  8 10
11 Edward 2001 31 11
12 Edward 2002 32 12
13 Edward 2003 33 13
14 Edward 2004 34 14
15 Edward 2005 35 15

In this case will be 2, since only two persons (Frank and Edward) have all the data.

Body:
I would do it like this :

cp = 0

for (i in unique(unbal$PERSON)){
  new_data = unbal[which(unbal$PERSON == i),]
  if (anyNA(new_data) == FALSE){
    cp = cp+1
  }else{
    cp = cp
  }
}

cp


问:
What is the point of this line of code?
I found this line of code in the Virtuemart plugin for Joomla on line 2136 in administrator/components/com_virtuemart/classes/ps_product.php</p>

```<code>eval ("\$text_including_tax = \"$text_including_tax\";");
</code>```

答:
No, it's doing this:

Say $text_including_tax = "flat".  This code evaluates the line:

$flat = "flat";

It isn't necessarily good, but I did use a technique like this once to suck all the MySQL variables in an array like this:

```<code>    while ($row = mysql_fetch_assoc($result)) {
        $var = $row["Variable_name"];
        $$var = $row["Value"];
    }
</code>```

OwnerDisplayName: mk

Title: What is the point of this line of code?

Body:
I found this line of code in the Virtuemart plugin for Joomla on line 2136 in administrator/components/com_virtuemart/classes/ps_product.php

eval ("\$text_including_tax = \"$text_including_tax\";");

Body:
No, it's doing this:

Say $text_including_tax = "flat".  This code evaluates the line:

$flat = "flat";

It isn't necessarily good, but I did use a technique like this once to suck all the MySQL variables in an array like this:

    while ($row = mysql_fetch_assoc($result)) {
        $var = $row["Variable_name"];
        $$var = $row["Value"];
    }


问:
Making Clean URLs in this situation
this question is really hard to search as I don't even know what keywords to use, altho ive tried but i still cant find the answer.

I have a database driven website: www.abc.com and every page will look like this

```<code> www.abc.com/?page=somepage
 www.abc.com/?page=another_page
 www.abc.com/?page=yet_another_page
</code>```

I use index.php to read the value of "?page" and then load the required page according to the value of "?page"

since "?page" is common how can i simplify my urls to look like

```<code>www.abc.com/somepage
www.abc.com/another_page
www.abc.com/yet_another_page
</code>```

Thanks

EDITED

On further thinking, I want to be a bit more specific about it... the problem is...

How to make it in a way that when an address like www.abc.com/somepage is typed in to the address bar, it should process that address as if it was  www.abc.com/?page=somepage and not go direct to /somepage as if it was a folder

答:
try this :

```<code> # Rewrite URLs of the form 'x' to the form 'index.php?q=x'.
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^(.*)$ index.php?page=$1 [L,QSA]
</code>```

Code from the drupal .htaccess (I replaced q by page)

Title: Making Clean URLs in this situation

Body:
this question is really hard to search as I don't even know what keywords to use, altho ive tried but i still cant find the answer.

I have a database driven website: www.abc.com and every page will look like this

 www.abc.com/?page=somepage
 www.abc.com/?page=another_page
 www.abc.com/?page=yet_another_page

I use index.php to read the value of "?page" and then load the required page according to the value of "?page"

since "?page" is common how can i simplify my urls to look like

www.abc.com/somepage
www.abc.com/another_page
www.abc.com/yet_another_page

Thanks

EDITED

On further thinking, I want to be a bit more specific about it... the problem is...

How to make it in a way that when an address like www.abc.com/somepage is typed in to the address bar, it should process that address as if it was  www.abc.com/?page=somepage and not go direct to /somepage as if it was a folder

Body:
try this :

 # Rewrite URLs of the form 'x' to the form 'index.php?q=x'.
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^(.*)$ index.php?page=$1 [L,QSA]

Code from the drupal .htaccess (I replaced q by page)