问:
Is it legal to use \\ in // C++ comment? (LaTeX equation in C++ comment)
For documentation purpose I need to add some LaTeX equations in my C++ comments, by example:

```<code>//
// \begin{eqnarray*}
//   y_1 &=& x_1 \\
//   y_2 &=& x_2
// \end{eqnarray*}
//
int main() {}
</code>```

With clang++ (version 9.0.1-10) I can compile my code without problem:

```<code>clang++ -Wall prog.cpp
</code>```

but with g++ (version 9.2.1)

```<code>g++ -Wall prog.cpp
</code>```

I get this warning:

```<code>prog.cpp:3:1: warning: multi-line comment [-Wcomment]
    3 | //   y_1 &=& x_1 \\
      | ^
</code>```

My question: which compiler is right? Can I legally use \\ inside C++ // comment?

答:
According to cpp reference

C++-style comments tell the compiler to ignore all content between // and a new line.

So your comment should be legal. Notice that g++ is only giving a warning, not an error.

g++ is warning about the escaped newline

Warn whenever a comment-start sequence ‘/’ appears in a ‘/’ comment, or whenever a backslash-newline appears in a ‘//’ comment. This warning is enabled by -Wall

Body:
For documentation purpose I need to add some LaTeX equations in my C++ comments, by example:

//
// \begin{eqnarray*}
//   y_1 &=& x_1 \\
//   y_2 &=& x_2
// \end{eqnarray*}
//
int main() {}

With clang++ (version 9.0.1-10) I can compile my code without problem:

clang++ -Wall prog.cpp

but with g++ (version 9.2.1)

g++ -Wall prog.cpp

I get this warning:

prog.cpp:3:1: warning: multi-line comment [-Wcomment]
    3 | //   y_1 &=& x_1 \\
      | ^

My question: which compiler is right? Can I legally use \\ inside C++ // comment?


来源: stackexchange

问:
Fine tuning in CNN using Tensor Flow - 2.0
I am currently working defect classification problem in solar panel. It's a multi class classification problem. Currently its 3 class. I have done the coding part but my accuracy is very low. How to improve my accuracy?

Total training images - 900
Testing/validation - 300
Class - 3

My code is given below -

```<code>import tensorflow as tf
import keras_preprocessing
from keras_preprocessing import image
from keras_preprocessing.image import ImageDataGenerator

TRAINING_DIR = "/content/drive/My Drive/solar_images/solar_images/train/"
training_datagen = ImageDataGenerator(
      rescale = 1./255,
        rotation_range=40,
      width_shift_range=0.2,
      height_shift_range=0.2,
      shear_range=0.2,
      zoom_range=0.2,
      horizontal_flip=True,
      fill_mode='nearest')

VALIDATION_DIR = "/content/drive/My Drive/solar_images/solar_images/test/"
validation_datagen = ImageDataGenerator(rescale = 1./255)

train_generator = training_datagen.flow_from_directory(
    TRAINING_DIR,
    target_size=(150,150),
    class_mode='categorical',
  batch_size=64
)

validation_generator = validation_datagen.flow_from_directory(
    VALIDATION_DIR,
    target_size=(150,150),
    class_mode='categorical',
  batch_size=64
)

model = tf.keras.models.Sequential([
    # Note the input shape is the desired size of the image 150x150 with 3 bytes color
    # This is the first convolution
    tf.keras.layers.Conv2D(64, (3,3), activation='relu', input_shape=(150, 150, 3)),
    tf.keras.layers.MaxPooling2D(2, 2),
    # The second convolution
    tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    # The third convolution
    tf.keras.layers.Conv2D(128, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    # The fourth convolution
    tf.keras.layers.Conv2D(128, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    # Flatten the results to feed into a DNN
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dropout(0.5),
    # 512 neuron hidden layer
    tf.keras.layers.Dense(512, activation='relu'),
    tf.keras.layers.Dense(3, activation='softmax')
])

model.summary()

model.compile(loss = 'categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
batch_size=64

history = model.fit(train_generator,
                    epochs=20,
                    steps_per_epoch=int(894/batch_size),
                    validation_data = validation_generator,
                    verbose = 1,
                    validation_steps=int(289/batch_size))

model.save("solar_images_weight.h5")
</code>```

My accuracy is -

```<code>Epoch 1/20
13/13 [==============================] - 1107s 85s/step - loss: 1.2893 - accuracy: 0.3470 - val_loss: 1.0926 - val_accuracy: 0.3594
Epoch 2/20
13/13 [==============================] - 1239s 95s/step - loss: 1.1037 - accuracy: 0.3566 - val_loss: 1.0954 - val_accuracy: 0.3125
Epoch 3/20
13/13 [==============================] - 1203s 93s/step - loss: 1.0964 - accuracy: 0.3904 - val_loss: 1.0841 - val_accuracy: 0.5625
Epoch 4/20
13/13 [==============================] - 1182s 91s/step - loss: 1.0980 - accuracy: 0.3750 - val_loss: 1.0894 - val_accuracy: 0.3633
Epoch 5/20
13/13 [==============================] - 1218s 94s/step - loss: 1.1086 - accuracy: 0.3386 - val_loss: 1.0874 - val_accuracy: 0.3125
Epoch 6/20
13/13 [==============================] - 1214s 93s/step - loss: 1.0953 - accuracy: 0.3257 - val_loss: 1.0763 - val_accuracy: 0.6094
Epoch 7/20
13/13 [==============================] - 1136s 87s/step - loss: 1.0851 - accuracy: 0.3831 - val_loss: 1.0754 - val_accuracy: 0.3164
Epoch 8/20
13/13 [==============================] - 1170s 90s/step - loss: 1.1005 - accuracy: 0.3940 - val_loss: 1.0545 - val_accuracy: 0.5039
Epoch 9/20
13/13 [==============================] - 1138s 88s/step - loss: 1.1294 - accuracy: 0.4337 - val_loss: 1.0130 - val_accuracy: 0.5703
Epoch 10/20
13/13 [==============================] - 1131s 87s/step - loss: 1.0250 - accuracy: 0.4531 - val_loss: 0.8911 - val_accuracy: 0.6055
Epoch 11/20
13/13 [==============================] - 1162s 89s/step - loss: 1.0243 - accuracy: 0.4735 - val_loss: 0.9160 - val_accuracy: 0.4727
Epoch 12/20
13/13 [==============================] - 1153s 89s/step - loss: 0.9978 - accuracy: 0.4783 - val_loss: 0.7754 - val_accuracy: 0.6406
Epoch 13/20
13/13 [==============================] - 1187s 91s/step - loss: 1.0080 - accuracy: 0.4687 - val_loss: 0.7701 - val_accuracy: 0.6602
Epoch 14/20
13/13 [==============================] - 1204s 93s/step - loss: 0.9851 - accuracy: 0.5048 - val_loss: 0.7450 - val_accuracy: 0.6367
Epoch 15/20
13/13 [==============================] - 1181s 91s/step - loss: 0.9699 - accuracy: 0.4892 - val_loss: 0.7409 - val_accuracy: 0.6289
Epoch 16/20
13/13 [==============================] - 1187s 91s/step - loss: 0.8884 - accuracy: 0.5241 - val_loss: 0.7169 - val_accuracy: 0.6133
Epoch 17/20
13/13 [==============================] - 1197s 92s/step - loss: 0.9372 - accuracy: 0.5084 - val_loss: 0.7464 - val_accuracy: 0.5859
Epoch 18/20
13/13 [==============================] - 1224s 94s/step - loss: 0.9230 - accuracy: 0.5229 - val_loss: 0.9198 - val_accuracy: 0.5156
Epoch 19/20
13/13 [==============================] - 1270s 98s/step - loss: 0.9161 - accuracy: 0.5192 - val_loss: 0.6785 - val_accuracy: 0.6289
Epoch 20/20
13/13 [==============================] - 1173s 90s/step - loss: 0.8728 - accuracy: 0.5193 - val_loss: 0.6674 - val_accuracy: 0.5781
</code>```

Training and validation accuracy plot is given below -

答: You could use transfer learning. Using a pre-trained model such as mobilenet or inception to train on your dataset. This would significantly improve your accuracy.  </p>

ContentLicense: CC BY-SA 4.0

Body:
I am currently working defect classification problem in solar panel. It's a multi class classification problem. Currently its 3 class. I have done the coding part but my accuracy is very low. How to improve my accuracy?

Total training images - 900
Testing/validation - 300
Class - 3

My code is given below -

import tensorflow as tf
import keras_preprocessing
from keras_preprocessing import image
from keras_preprocessing.image import ImageDataGenerator

TRAINING_DIR = "/content/drive/My Drive/solar_images/solar_images/train/"
training_datagen = ImageDataGenerator(
      rescale = 1./255,
        rotation_range=40,
      width_shift_range=0.2,
      height_shift_range=0.2,
      shear_range=0.2,
      zoom_range=0.2,
      horizontal_flip=True,
      fill_mode='nearest')

VALIDATION_DIR = "/content/drive/My Drive/solar_images/solar_images/test/"
validation_datagen = ImageDataGenerator(rescale = 1./255)

train_generator = training_datagen.flow_from_directory(
    TRAINING_DIR,
    target_size=(150,150),
    class_mode='categorical',
  batch_size=64
)

validation_generator = validation_datagen.flow_from_directory(
    VALIDATION_DIR,
    target_size=(150,150),
    class_mode='categorical',
  batch_size=64
)

model = tf.keras.models.Sequential([
    # Note the input shape is the desired size of the image 150x150 with 3 bytes color
    # This is the first convolution
    tf.keras.layers.Conv2D(64, (3,3), activation='relu', input_shape=(150, 150, 3)),
    tf.keras.layers.MaxPooling2D(2, 2),
    # The second convolution
    tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    # The third convolution
    tf.keras.layers.Conv2D(128, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    # The fourth convolution
    tf.keras.layers.Conv2D(128, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    # Flatten the results to feed into a DNN
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dropout(0.5),
    # 512 neuron hidden layer
    tf.keras.layers.Dense(512, activation='relu'),
    tf.keras.layers.Dense(3, activation='softmax')
])

model.summary()

model.compile(loss = 'categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
batch_size=64

history = model.fit(train_generator,
                    epochs=20,
                    steps_per_epoch=int(894/batch_size),
                    validation_data = validation_generator,
                    verbose = 1,
                    validation_steps=int(289/batch_size))

model.save("solar_images_weight.h5")

My accuracy is -

Epoch 1/20
13/13 [==============================] - 1107s 85s/step - loss: 1.2893 - accuracy: 0.3470 - val_loss: 1.0926 - val_accuracy: 0.3594
Epoch 2/20
13/13 [==============================] - 1239s 95s/step - loss: 1.1037 - accuracy: 0.3566 - val_loss: 1.0954 - val_accuracy: 0.3125
Epoch 3/20
13/13 [==============================] - 1203s 93s/step - loss: 1.0964 - accuracy: 0.3904 - val_loss: 1.0841 - val_accuracy: 0.5625
Epoch 4/20
13/13 [==============================] - 1182s 91s/step - loss: 1.0980 - accuracy: 0.3750 - val_loss: 1.0894 - val_accuracy: 0.3633
Epoch 5/20
13/13 [==============================] - 1218s 94s/step - loss: 1.1086 - accuracy: 0.3386 - val_loss: 1.0874 - val_accuracy: 0.3125
Epoch 6/20
13/13 [==============================] - 1214s 93s/step - loss: 1.0953 - accuracy: 0.3257 - val_loss: 1.0763 - val_accuracy: 0.6094
Epoch 7/20
13/13 [==============================] - 1136s 87s/step - loss: 1.0851 - accuracy: 0.3831 - val_loss: 1.0754 - val_accuracy: 0.3164
Epoch 8/20
13/13 [==============================] - 1170s 90s/step - loss: 1.1005 - accuracy: 0.3940 - val_loss: 1.0545 - val_accuracy: 0.5039
Epoch 9/20
13/13 [==============================] - 1138s 88s/step - loss: 1.1294 - accuracy: 0.4337 - val_loss: 1.0130 - val_accuracy: 0.5703
Epoch 10/20
13/13 [==============================] - 1131s 87s/step - loss: 1.0250 - accuracy: 0.4531 - val_loss: 0.8911 - val_accuracy: 0.6055
Epoch 11/20
13/13 [==============================] - 1162s 89s/step - loss: 1.0243 - accuracy: 0.4735 - val_loss: 0.9160 - val_accuracy: 0.4727
Epoch 12/20
13/13 [==============================] - 1153s 89s/step - loss: 0.9978 - accuracy: 0.4783 - val_loss: 0.7754 - val_accuracy: 0.6406
Epoch 13/20
13/13 [==============================] - 1187s 91s/step - loss: 1.0080 - accuracy: 0.4687 - val_loss: 0.7701 - val_accuracy: 0.6602
Epoch 14/20
13/13 [==============================] - 1204s 93s/step - loss: 0.9851 - accuracy: 0.5048 - val_loss: 0.7450 - val_accuracy: 0.6367
Epoch 15/20
13/13 [==============================] - 1181s 91s/step - loss: 0.9699 - accuracy: 0.4892 - val_loss: 0.7409 - val_accuracy: 0.6289
Epoch 16/20
13/13 [==============================] - 1187s 91s/step - loss: 0.8884 - accuracy: 0.5241 - val_loss: 0.7169 - val_accuracy: 0.6133
Epoch 17/20
13/13 [==============================] - 1197s 92s/step - loss: 0.9372 - accuracy: 0.5084 - val_loss: 0.7464 - val_accuracy: 0.5859
Epoch 18/20
13/13 [==============================] - 1224s 94s/step - loss: 0.9230 - accuracy: 0.5229 - val_loss: 0.9198 - val_accuracy: 0.5156
Epoch 19/20
13/13 [==============================] - 1270s 98s/step - loss: 0.9161 - accuracy: 0.5192 - val_loss: 0.6785 - val_accuracy: 0.6289
Epoch 20/20
13/13 [==============================] - 1173s 90s/step - loss: 0.8728 - accuracy: 0.5193 - val_loss: 0.6674 - val_accuracy: 0.5781

Training and validation accuracy plot is given below -


问:
static methods can not run in a non-static context
I'm trying to simulate a game of Yahtzee by using various methods to roll, compare, and sum up dice.

This is an assignment and I'm required to use these three static methods to do all of my work in.

When I try to run my code however I get this error

```<code>exit status 1
Main.java:6: error: non-static method rollDice(int[]) cannot be referenced from a static context
   rollDice(dice);
   ^
Main.java:7: error: non-static method rollDice(int[]) cannot be referenced from a static context
   dice= rollDice(dice);
         ^
2 errors
</code>```

I tried running the methods before assigning the values they return to variables but that didn't seem to work. Here is my complete code:

```<code>class Main {
  public static void main(String[] args) {
  // int array to hold 5 dice

   int dice[] = new int[5];
   rollDice(dice);
   dice= rollDice(dice);

   fiveOfaKind(dice);
   int points = fiveOfaKind(dice);

   getChance(dice,points);
   int printpoint = getChance(dice,points);
   // You may roll the dice up to 3 times to try to get 5 of a Kind
   // If you get 5 of a Kind, stop if not keep trying.
   // If you do not get 5 of a Kind after the 3rd roll, you must take the
   // CHANCE score.

   System.out.println("Your score is " + printpoint);

  }// end of main method

  public int[] rollDice(int dice[]){
    // generate 5 random numbers / update dice array
     for (int i = 0; i < dice.length; i++) {
      dice[i] = (int)(Math.random() * 6 + 1);
     }
    return dice;

  }// end of rollDice - rolls 5 dice and puts them in an array
   // All 5 dice must be rolled each time

  public static int fiveOfaKind(int dice[]){
     int pts = 0;
     int rNum=0;

    for(int i=0; rNum<3; rNum++){
    if(dice[0]==dice[1]&&dice[1]==dice[2]&&dice[2]==dice[3]&&dice[3]==dice[4]&&dice[4]==dice[5]&&dice[5]==dice[6]){
      pts=50;
    }
    else if(rNum==3){
      pts=0;
    }
    else{
      int[] rollDice;
    }

    }//end of forloop

    // use Array dice - evaluate if all elements are equal
    // if true = pts = 50
    // if false - pts = 0

    return pts;

  }// end of fiveOfaKind - evaluates the dice roll to see if all 5 are equal
   // Returns 50 points if they do

  public static int getChance(int dice[], int points){

    if(points<50){
       points=0;
      for (int i = 0; i < dice.length; i++) {
         points+=dice[i];
      }
    }
    // use Array dice - sum the elements of the Array
    // pys = calculated value of the sum

    int p = points;

    return p;

  }// end of getChance - adds the total value of the dice
    // Returns the total points calculated

}// end of  class
</code>```

答:
You need to make rollDice() method as static.
Non static method cannot be called from static Method. If you want to call non static method , you have to use the instance of the class to call that method.

Body:
I'm trying to simulate a game of Yahtzee by using various methods to roll, compare, and sum up dice.

This is an assignment and I'm required to use these three static methods to do all of my work in.

When I try to run my code however I get this error

exit status 1
Main.java:6: error: non-static method rollDice(int[]) cannot be referenced from a static context
   rollDice(dice);
   ^
Main.java:7: error: non-static method rollDice(int[]) cannot be referenced from a static context
   dice= rollDice(dice);
         ^
2 errors

I tried running the methods before assigning the values they return to variables but that didn't seem to work. Here is my complete code:

class Main {
  public static void main(String[] args) {
  // int array to hold 5 dice

   int dice[] = new int[5];
   rollDice(dice);
   dice= rollDice(dice);

   fiveOfaKind(dice);
   int points = fiveOfaKind(dice);

   getChance(dice,points);
   int printpoint = getChance(dice,points);
   // You may roll the dice up to 3 times to try to get 5 of a Kind
   // If you get 5 of a Kind, stop if not keep trying.
   // If you do not get 5 of a Kind after the 3rd roll, you must take the
   // CHANCE score.

   System.out.println("Your score is " + printpoint);

  }// end of main method

  public int[] rollDice(int dice[]){
    // generate 5 random numbers / update dice array
     for (int i = 0; i < dice.length; i++) {
      dice[i] = (int)(Math.random() * 6 + 1);
     }
    return dice;

  }// end of rollDice - rolls 5 dice and puts them in an array
   // All 5 dice must be rolled each time

  public static int fiveOfaKind(int dice[]){
     int pts = 0;
     int rNum=0;

    for(int i=0; rNum<3; rNum++){
    if(dice[0]==dice[1]&&dice[1]==dice[2]&&dice[2]==dice[3]&&dice[3]==dice[4]&&dice[4]==dice[5]&&dice[5]==dice[6]){
      pts=50;
    }
    else if(rNum==3){
      pts=0;
    }
    else{
      int[] rollDice;
    }

    }//end of forloop

    // use Array dice - evaluate if all elements are equal
    // if true = pts = 50
    // if false - pts = 0

    return pts;

  }// end of fiveOfaKind - evaluates the dice roll to see if all 5 are equal
   // Returns 50 points if they do

  public static int getChance(int dice[], int points){

    if(points<50){
       points=0;
      for (int i = 0; i < dice.length; i++) {
         points+=dice[i];
      }
    }
    // use Array dice - sum the elements of the Array
    // pys = calculated value of the sum

    int p = points;

    return p;

  }// end of getChance - adds the total value of the dice
    // Returns the total points calculated

}// end of  class


问:
Github actions error An action could not be found
I have a simple nodejs app on GitHub and I want to build a docker image and push to AWS ECR with GitHub actions.

aws.yml:-

```<code>name: foo-bar CI

on:
  pull_request:
    branches:
    - sandbox
  push:
    branches:
    - sandbox

env:
  AWS_REPOSITORY_URL: ${{ secrets.AWS_REPOSITORY_URL }}
  AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
  AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}

jobs:
  build-and-push:
    name: Build and push image to AWS ECR
    runs-on: ubuntu-latest
    steps:

    - name: Checkout
      uses: actions/checkout@master

    - name: Check REPO url
      run: echo $AWS_REPOSITORY_URL

    - name: Setup ECR
      run: $( aws ecr get-login --no-include-email --region ap-south-1)

    - name: Build and tag the image
      run: docker build -t $AWS_REPOSITORY_URL .

    - name: Push
      run: docker push $AWS_REPOSITORY_URL
</code>```

I have added AWS_REPOSITORY_URL, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY in the repository-home>settings>secrets.

I am sure I have entered the correct values, I am also using these values in gitlab-ci and it's working.

When I pushed to sandbox branch, the CI job started and it gave the following error -

```<code>Current runner version: '2.263.0'
Operating System
  Ubuntu
  18.04.4
  LTS
Virtual Environment
  Environment: ubuntu-18.04
  Version: 20200525.2
  Included Software: https://github.com/actions/virtual-environments/blob/ubuntu18/20200525.2/images/linux/Ubuntu1804-README.md
Prepare workflow directory
Prepare all required actions
Download action repository 'actions/checkout@sandbox'
##[error]An action could not be found at the URI 'https://api.github.com/repos/actions/checkout/tarball/sandbox'
</code>```

What am I doing wrong? Does my YML file have errors?

Judging by the logs, the job fails at Checkout step. It's trying to download something from https://api.github.com/repos/actions/checkout/tarball/sandbox which gives 404 (I tried to open the URL in the browser). I think it should have tried to download from https://api.github.com/repos/actions/checkout/tarball/master. I am not sure though why it's behaving this way.

答:
For some reason GitHub misinterpreting Checkout step.

It was using actions/checkout@sandbox instead of actions/checkout@master at the time of execution. Probably it's a bug in https://github.com/aws-actions/ with the master branch. I tried v2 tag instead and it worked.

So the updated Checkout step is -

```<code>- name: Checkout
  uses: actions/checkout@v2
</code>```

Body:
I have a simple nodejs app on GitHub and I want to build a docker image and push to AWS ECR with GitHub actions.

aws.yml:-

name: foo-bar CI

on:
  pull_request:
    branches:
    - sandbox
  push:
    branches:
    - sandbox

env:
  AWS_REPOSITORY_URL: ${{ secrets.AWS_REPOSITORY_URL }}
  AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
  AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}

jobs:
  build-and-push:
    name: Build and push image to AWS ECR
    runs-on: ubuntu-latest
    steps:

    - name: Checkout
      uses: actions/checkout@master

    - name: Check REPO url
      run: echo $AWS_REPOSITORY_URL

    - name: Setup ECR
      run: $( aws ecr get-login --no-include-email --region ap-south-1)

    - name: Build and tag the image
      run: docker build -t $AWS_REPOSITORY_URL .

    - name: Push
      run: docker push $AWS_REPOSITORY_URL

I have added AWS_REPOSITORY_URL, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY in the repository-home>settings>secrets.

I am sure I have entered the correct values, I am also using these values in gitlab-ci and it's working.

When I pushed to sandbox branch, the CI job started and it gave the following error -

Current runner version: '2.263.0'
Operating System
  Ubuntu
  18.04.4
  LTS
Virtual Environment
  Environment: ubuntu-18.04
  Version: 20200525.2
  Included Software: https://github.com/actions/virtual-environments/blob/ubuntu18/20200525.2/images/linux/Ubuntu1804-README.md
Prepare workflow directory
Prepare all required actions
Download action repository 'actions/checkout@sandbox'
##[error]An action could not be found at the URI 'https://api.github.com/repos/actions/checkout/tarball/sandbox'

What am I doing wrong? Does my YML file have errors?

Judging by the logs, the job fails at Checkout step. It's trying to download something from https://api.github.com/repos/actions/checkout/tarball/sandbox which gives 404 (I tried to open the URL in the browser). I think it should have tried to download from https://api.github.com/repos/actions/checkout/tarball/master. I am not sure though why it's behaving this way.

Body:
For some reason GitHub misinterpreting Checkout step.

It was using actions/checkout@sandbox instead of actions/checkout@master at the time of execution. Probably it's a bug in https://github.com/aws-actions/ with the master branch. I tried v2 tag instead and it worked.

So the updated Checkout step is -

- name: Checkout
  uses: actions/checkout@v2


问:
what is wrong in my solution? help me to impove it or any other solution?
A classroom has several students, half of whom are boys and half of whom are girls. You need to arrange all of them in a line for the morning assembly such that the following conditions are satisfied:

The students must be in the order of non-decreasing height.
Two boys or two girls must not be adjacent to each other.
You have been given the heights of the boys in the array and the heights of the girls in the array. Find out whether you can arrange them in an order which satisfies the given conditions. Print "YES" if it is possible, or "NO" if it is not.
This one is mine but I am getting the wrong answer in 3 testcases.
here, a is the array of boys height and b is the array of girls.

```<code>a=sorted(a)
b=sorted(b)
i=0
n=len(a)
j=0
x=""

while i<n and j<n:
    if a[i]<b[j]:
        x+="b"
        i+=1
    elif a[i]==b[j]:
        if len(x)==0:
            x+="b"
            i+=1
        elif x[-1]=="b":
            x+="g"
            j+=1
        else:
            x+="b"
            i+=1

    else:
        x+="g"
        j+=1

while i<n:
    x+="b"
    i+=1
while j<n:
    x+="g"
    j+=1

p=re.findall(r"[g]{2,}(?=[b]{2})",x)
q=re.findall(r"[b]{2,}(?=[g]{2})",x)
if q or p:
    return "NO"
else:
    return "YES"
</code>```

答:
I saw your code. So the mistake is in the part where you check for 2 boys and 2 girls.

The condition that you wrote is:

```<code>p=re.findall(r"[g]{2,}(?=[b]{2})",x)
q=re.findall(r"[b]{2,}(?=[g]{2})",x)
</code>```

Note that '?=' is lookahead before which means it will only give true if you have 2 girls before 2 boys or 2 boys before 2 girls. This logic will fail when the case is such that the string comes out to be -> GBBG or BGGB or GBBGBG or BGGBGB

I would suggest using a flag system instead because you just need to keep track of the last entry in the line. Let flag be '0' for boy and '1' for girl

```<code>flag=2
success = "Yes";
while i<n and j<n:
    if(a[i]<b[j]):
        if(flag==2):
            flag = 0
        elif(flag == 0):
            success="No"
            break;
        else:
            flag=0
    elif(a[i]==b[j])
        if(flag==2):
            flag=0
        elif(flag==0):
            flag=1
        else:
            flag=0
    else:
        if(flag==2):
            flag=1
        elif(flag==1):
            success="No"
            break;
        else:
            flag=1

print(success)
</code>```

Body:
A classroom has several students, half of whom are boys and half of whom are girls. You need to arrange all of them in a line for the morning assembly such that the following conditions are satisfied:

The students must be in the order of non-decreasing height.
Two boys or two girls must not be adjacent to each other.
You have been given the heights of the boys in the array and the heights of the girls in the array. Find out whether you can arrange them in an order which satisfies the given conditions. Print "YES" if it is possible, or "NO" if it is not.
This one is mine but I am getting the wrong answer in 3 testcases.
here, a is the array of boys height and b is the array of girls.

a=sorted(a)
b=sorted(b)
i=0
n=len(a)
j=0
x=""

while i<n and j<n:
    if a[i]<b[j]:
        x+="b"
        i+=1
    elif a[i]==b[j]:
        if len(x)==0:
            x+="b"
            i+=1
        elif x[-1]=="b":
            x+="g"
            j+=1
        else:
            x+="b"
            i+=1

    else:
        x+="g"
        j+=1

while i<n:
    x+="b"
    i+=1
while j<n:
    x+="g"
    j+=1

p=re.findall(r"[g]{2,}(?=[b]{2})",x)
q=re.findall(r"[b]{2,}(?=[g]{2})",x)
if q or p:
    return "NO"
else:
    return "YES"

Body:
I saw your code. So the mistake is in the part where you check for 2 boys and 2 girls.

The condition that you wrote is:

p=re.findall(r"[g]{2,}(?=[b]{2})",x)
q=re.findall(r"[b]{2,}(?=[g]{2})",x)

Note that '?=' is lookahead before which means it will only give true if you have 2 girls before 2 boys or 2 boys before 2 girls. This logic will fail when the case is such that the string comes out to be -> GBBG or BGGB or GBBGBG or BGGBGB

I would suggest using a flag system instead because you just need to keep track of the last entry in the line. Let flag be '0' for boy and '1' for girl

flag=2
success = "Yes";
while i<n and j<n:
    if(a[i]<b[j]):
        if(flag==2):
            flag = 0
        elif(flag == 0):
            success="No"
            break;
        else:
            flag=0
    elif(a[i]==b[j])
        if(flag==2):
            flag=0
        elif(flag==0):
            flag=1
        else:
            flag=0
    else:
        if(flag==2):
            flag=1
        elif(flag==1):
            success="No"
            break;
        else:
            flag=1

print(success)


问:
Using GSON to parse array with multiple types
I wish to use GSON to parse the following json:

```<code>[
    [
        "hello",
        1,
        [2]
    ],
    [
        "world",
        3,
        [2]
    ]
]
</code>```

So, that's 1 array, containing 2 arrays.  The 2 inner arrays are themselves arrays, comprised of String, int, array types.

I'm unsure how I can using Java classes to model the array which has 3 different types (String, int, array).  I start with:

```<code>// String json just contains the aforementioned json string.

ArrayList<ArrayList<XXX>> data = new ArrayList<ArrayList<XXX>>();

Type arrayListType = new TypeToken<ArrayList<ArrayList<XXX>>>(){}.getType();

data = gson.fromJson(json, arrayListType);
</code>```

But what should be where the 'XXX' are?  I think it should be an array, but it should be an array with 3 different data types.  So how can I use Java to model this?

Can any help?
Thank you.

答:
Gson has special handling for deserializing some single-component arrays into a non-array type.  For example, int data = gson.fromJson("[3]", int.class); would assign the int value 3 to data.

Of course, deserializing a single-component array into a non-array type is not required.  For example, the previous example could be deserialized as int[] data = gson.fromJson("[3]", int[].class);.

Gson will also often deserialize a non-String value into a String, when asked.  Applying this to the first example, String data = gson.fromJson("[3]", String.class); works just as well.

Note that it does not work to tell Gson to deserialize the first example as type Object.  Object data = gson.fromJson("[3]", Object.class); results in a parse exception complaining that [3] is not a primitive.

Applied to the example in the original question above, if it's acceptable to treat all of the values as Strings, then deserialization becomes simple.

```<code>// output:
// hello 1 2
// world 3 2

public class Foo
{
  static String jsonInput =
    "[" +
      "[\"hello\",1,[2]]," +
      "[\"world\",3,[2]]" +
    "]";

  public static void main(String[] args)
  {
    Gson gson = new Gson();
    String[][] data = gson.fromJson(jsonInput, String[][].class);
    for (String[] data2 : data)
    {
      for (String data3 : data2)
      {
        System.out.print(data3);
        System.out.print(" ");
      }
      System.out.println();
    }
  }
}
</code>```

Unfortunately, with Gson I've not been able to figure out a simple deserialization approach that would allow for "better" binding to more specific and mixed types in an array, since Java doesn't provide a syntax for defining a mixed type array.  For example, the preferred type of the collection in the original question might be List<List<String, int, List<int>>>, but that's not possible to define in Java.  So, you gotta be content with List<List<String>> (or String[][]), or turn to an approach with more "manual" parsing.

(Yes, Java allows a type declaration of List<List<Object>>, but Object is not a specific enough type to meaningfully deserialize to.  Also, as discussed, attempting to deserialize [3] to Object results in a parse exception.)

Small Update: I recently had to deserialize some sloppy JSON that included a structure not too dissimilar from that in the original question.  I ended up just using a custom deserializer to create a object from the messy JSON array.  Similar to the following example.

```<code>// output:
// [{MyThreeThings: first=hello, second=1, third=[2]},
//  {MyThreeThings: first=world, second=3, third=[4, 5]}]

import java.lang.reflect.Type;
import java.util.Arrays;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;

public class FooToo
{
  static String jsonInput =
      "[" +
          "[\"hello\",1,[2]]," +
          "[\"world\",3,[4,5]]" +
      "]";

  public static void main(String[] args)
  {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(MyThreeThings.class, new MyThreeThingsDeserializer());
    Gson gson = gsonBuilder.create();
    MyThreeThings[] things = gson.fromJson(jsonInput, MyThreeThings[].class);
    System.out.println(Arrays.toString(things));
  }
}

class MyThreeThings
{
  String first;
  int second;
  int[] third;

  MyThreeThings(String first, int second, int[] third)
  {
    this.first = first;
    this.second = second;
    this.third = third;
  }

  @Override
  public String toString()
  {
    return String.format(
        "{MyThreeThings: first=%s, second=%d, third=%s}",
        first, second, Arrays.toString(third));
  }
}

class MyThreeThingsDeserializer implements JsonDeserializer<MyThreeThings>
{
  @Override
  public MyThreeThings deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
      throws JsonParseException
  {
    JsonArray jsonArray = json.getAsJsonArray();
    String first = jsonArray.get(0).getAsString();
    int second = jsonArray.get(1).getAsInt();
    JsonArray jsonArray2 = jsonArray.get(2).getAsJsonArray();
    int length = jsonArray2.size();
    int[] third = new int[length];
    for (int i = 0; i < length; i++)
    {
      int n = jsonArray2.get(i).getAsInt();
      third[i] = n;
    }
    return new MyThreeThings(first, second, third);
  }
}
</code>```

The Gson user guide does cover handling deserialization of collections of mixed types with a similar example as this in the "Serializing and Deserializing Collection with Objects of Arbitrary Types" section.

ContentLicense: CC BY-SA 2.5

Body:
I wish to use GSON to parse the following json:

[
    [
        "hello",
        1,
        [2]
    ],
    [
        "world",
        3,
        [2]
    ]
]

So, that's 1 array, containing 2 arrays.  The 2 inner arrays are themselves arrays, comprised of String, int, array types.

I'm unsure how I can using Java classes to model the array which has 3 different types (String, int, array).  I start with:

// String json just contains the aforementioned json string.

ArrayList<ArrayList<XXX>> data = new ArrayList<ArrayList<XXX>>();

Type arrayListType = new TypeToken<ArrayList<ArrayList<XXX>>>(){}.getType();

data = gson.fromJson(json, arrayListType);

But what should be where the 'XXX' are?  I think it should be an array, but it should be an array with 3 different data types.  So how can I use Java to model this?

Can any help?
Thank you.

Body:
Gson has special handling for deserializing some single-component arrays into a non-array type.  For example, int data = gson.fromJson("[3]", int.class); would assign the int value 3 to data.

Of course, deserializing a single-component array into a non-array type is not required.  For example, the previous example could be deserialized as int[] data = gson.fromJson("[3]", int[].class);.

Gson will also often deserialize a non-String value into a String, when asked.  Applying this to the first example, String data = gson.fromJson("[3]", String.class); works just as well.

Note that it does not work to tell Gson to deserialize the first example as type Object.  Object data = gson.fromJson("[3]", Object.class); results in a parse exception complaining that [3] is not a primitive.

Applied to the example in the original question above, if it's acceptable to treat all of the values as Strings, then deserialization becomes simple.

// output:
// hello 1 2
// world 3 2

public class Foo
{
  static String jsonInput =
    "[" +
      "[\"hello\",1,[2]]," +
      "[\"world\",3,[2]]" +
    "]";

  public static void main(String[] args)
  {
    Gson gson = new Gson();
    String[][] data = gson.fromJson(jsonInput, String[][].class);
    for (String[] data2 : data)
    {
      for (String data3 : data2)
      {
        System.out.print(data3);
        System.out.print(" ");
      }
      System.out.println();
    }
  }
}

Unfortunately, with Gson I've not been able to figure out a simple deserialization approach that would allow for "better" binding to more specific and mixed types in an array, since Java doesn't provide a syntax for defining a mixed type array.  For example, the preferred type of the collection in the original question might be List<List<String, int, List<int>>>, but that's not possible to define in Java.  So, you gotta be content with List<List<String>> (or String[][]), or turn to an approach with more "manual" parsing.

(Yes, Java allows a type declaration of List<List<Object>>, but Object is not a specific enough type to meaningfully deserialize to.  Also, as discussed, attempting to deserialize [3] to Object results in a parse exception.)

Small Update: I recently had to deserialize some sloppy JSON that included a structure not too dissimilar from that in the original question.  I ended up just using a custom deserializer to create a object from the messy JSON array.  Similar to the following example.

// output:
// [{MyThreeThings: first=hello, second=1, third=[2]},
//  {MyThreeThings: first=world, second=3, third=[4, 5]}]

import java.lang.reflect.Type;
import java.util.Arrays;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;

public class FooToo
{
  static String jsonInput =
      "[" +
          "[\"hello\",1,[2]]," +
          "[\"world\",3,[4,5]]" +
      "]";

  public static void main(String[] args)
  {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(MyThreeThings.class, new MyThreeThingsDeserializer());
    Gson gson = gsonBuilder.create();
    MyThreeThings[] things = gson.fromJson(jsonInput, MyThreeThings[].class);
    System.out.println(Arrays.toString(things));
  }
}

class MyThreeThings
{
  String first;
  int second;
  int[] third;

  MyThreeThings(String first, int second, int[] third)
  {
    this.first = first;
    this.second = second;
    this.third = third;
  }

  @Override
  public String toString()
  {
    return String.format(
        "{MyThreeThings: first=%s, second=%d, third=%s}",
        first, second, Arrays.toString(third));
  }
}

class MyThreeThingsDeserializer implements JsonDeserializer<MyThreeThings>
{
  @Override
  public MyThreeThings deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
      throws JsonParseException
  {
    JsonArray jsonArray = json.getAsJsonArray();
    String first = jsonArray.get(0).getAsString();
    int second = jsonArray.get(1).getAsInt();
    JsonArray jsonArray2 = jsonArray.get(2).getAsJsonArray();
    int length = jsonArray2.size();
    int[] third = new int[length];
    for (int i = 0; i < length; i++)
    {
      int n = jsonArray2.get(i).getAsInt();
      third[i] = n;
    }
    return new MyThreeThings(first, second, third);
  }
}

The Gson user guide does cover handling deserialization of collections of mixed types with a similar example as this in the "Serializing and Deserializing Collection with Objects of Arbitrary Types" section.

ContentLicense: CC BY-SA 3.0


问:
Can an Activity access a Fragment to know if a button has been pressed?
The Objective: I'm trying to make a notepad application. What my app does is, a button is pressed to create a new note. This pops up a fragment in which the user types his note. Within the same fragment, I have another button that signifies when the user is done typing.

Question 1: Is there a way by which pressing the other button in the Fragment could trigger a method in my Activity?

Question 2: Would this cause the app to become too bloated? Should I keep the button within my activity itself?

Thank you for your help.

答:
There is an easy way of doing this as your fragments have access to activity (Kotlin) | getActivity() (Java) and by casting it you can use it.
But this is not the proper way of doing this because it affects the modularity of fragments.

The proper way of doing this:

Your activity wants to listen to Fragments events without any overhead:

In Fragment

```<code>class MyFragment : Fragment() {

    override fun onAttach(context: Context) {
        super.onAttach(context)
        if (context is MyFragment.Listener) {
            listener = context
        } else {
            throw ClassCastException(context.toString() + " You need to implement MyFragment.Listener")
        }
    }

    interface Listener {
        fun onSomethingHappened()
    }

    private var listener: MyFragment.Listener? = null

    fun aMethodInsideFragmentThatHandlesButtonEvents() {
        listener?.onSomethingHappened()
    }
}
</code>```

And in your activity:

```<code>class MyActivity : AppCompatActivity(), MyFragment.Listener {
    override void onSomethingHappened() {
        // do your work here
    }

    ...
}
</code>```

Body:
There is an easy way of doing this as your fragments have access to activity (Kotlin) | getActivity() (Java) and by casting it you can use it.
But this is not the proper way of doing this because it affects the modularity of fragments.

The proper way of doing this:

Your activity wants to listen to Fragments events without any overhead:

In Fragment

class MyFragment : Fragment() {

    override fun onAttach(context: Context) {
        super.onAttach(context)
        if (context is MyFragment.Listener) {
            listener = context
        } else {
            throw ClassCastException(context.toString() + " You need to implement MyFragment.Listener")
        }
    }

    interface Listener {
        fun onSomethingHappened()
    }

    private var listener: MyFragment.Listener? = null

    fun aMethodInsideFragmentThatHandlesButtonEvents() {
        listener?.onSomethingHappened()
    }
}

And in your activity:

class MyActivity : AppCompatActivity(), MyFragment.Listener {
    override void onSomethingHappened() {
        // do your work here
    }

    ...
}


问:
Dynamic TapGestureRecognizer on StackLayout in XamarinForms
I have the code below, which I'm basically looping a list and using the properties of that list as values:

```<code>SLTData.g_RecentLoans.ForEach(x => {
    colorCode = loanHistoryViewModel.GetStatusColor(x.ActivityListID);
    principal = utilities.FormatCurrency(x.PAMT);
    formattedDate = loanHistoryViewModel.ConvertDate(x.DateRequested);

    stackRecentList.Children.Add(
             new Frame {
                BackgroundColor = Color.White,
                Margin = new Thickness(30, 20, 30, 0),
                Padding = new Thickness(10),
                CornerRadius = 5,
                HasShadow = true,
                Content = new StackLayout {
                    Orientation = StackOrientation.Horizontal,
                    Spacing = 0,
                    Children = {
                        // Content here
                        // The 'x' variables are used inside this StackLayout
                    }
                }
            }
        );
});
</code>```

The thing is, I want to add a TapGestureRecognizer in each iteration of the StackLayout in the loop. I have tried adding .GestureRecognizers.Add(tapGestureRecognizer) at the closing bracket of the StackLayout but it says Cannot implicitly convert type 'void' to 'Xamarin.Forms.View'

What I basically want to do is to add an argument to the function that handles the tap, and that argument is the keyword that gets passed to the API.

答:
I want to add a TapGestureRecognizer in each iteration of the StackLayout in the loop.

Maybe you have some problems when add tapGestureRecognizer for StackLayout, I provide some code that you can take a look:

```<code>  private  void loadtap()
    {
        for(int i=0;i<5;i++)
        {
            Frame f = new Frame()
            {
                BackgroundColor = Color.White,
                Margin = new Thickness(30, 20, 30, 0),
                Padding = new Thickness(10),
                CornerRadius = 5,
                HasShadow = true,

            };

            StackLayout stack = new StackLayout()
            {
                Orientation = StackOrientation.Horizontal,
                Spacing = 0,
                Children = { new Label(){Text="this is test"}

                }
            };

            var tapGestureRecognizer = new TapGestureRecognizer();
            tapGestureRecognizer.Tapped += (s, e) => {
              DisplayAlert("Alert", "You have been click tap", "OK");
            };

            stack.GestureRecognizers.Add(tapGestureRecognizer);
            f.Content = stack;

            stacklist.Children.Add(f);
        }
    }
</code>```

Body:
I have the code below, which I'm basically looping a list and using the properties of that list as values:

SLTData.g_RecentLoans.ForEach(x => {
    colorCode = loanHistoryViewModel.GetStatusColor(x.ActivityListID);
    principal = utilities.FormatCurrency(x.PAMT);
    formattedDate = loanHistoryViewModel.ConvertDate(x.DateRequested);

    stackRecentList.Children.Add(
             new Frame {
                BackgroundColor = Color.White,
                Margin = new Thickness(30, 20, 30, 0),
                Padding = new Thickness(10),
                CornerRadius = 5,
                HasShadow = true,
                Content = new StackLayout {
                    Orientation = StackOrientation.Horizontal,
                    Spacing = 0,
                    Children = {
                        // Content here
                        // The 'x' variables are used inside this StackLayout
                    }
                }
            }
        );
});

The thing is, I want to add a TapGestureRecognizer in each iteration of the StackLayout in the loop. I have tried adding .GestureRecognizers.Add(tapGestureRecognizer) at the closing bracket of the StackLayout but it says Cannot implicitly convert type 'void' to 'Xamarin.Forms.View'

What I basically want to do is to add an argument to the function that handles the tap, and that argument is the keyword that gets passed to the API.

Body:
I want to add a TapGestureRecognizer in each iteration of the StackLayout in the loop.

Maybe you have some problems when add tapGestureRecognizer for StackLayout, I provide some code that you can take a look:

  private  void loadtap()
    {
        for(int i=0;i<5;i++)
        {
            Frame f = new Frame()
            {
                BackgroundColor = Color.White,
                Margin = new Thickness(30, 20, 30, 0),
                Padding = new Thickness(10),
                CornerRadius = 5,
                HasShadow = true,

            };

            StackLayout stack = new StackLayout()
            {
                Orientation = StackOrientation.Horizontal,
                Spacing = 0,
                Children = { new Label(){Text="this is test"}

                }
            };

            var tapGestureRecognizer = new TapGestureRecognizer();
            tapGestureRecognizer.Tapped += (s, e) => {
              DisplayAlert("Alert", "You have been click tap", "OK");
            };

            stack.GestureRecognizers.Add(tapGestureRecognizer);
            f.Content = stack;

            stacklist.Children.Add(f);
        }
    }


问:
Django model relationship with circular relationship
I am new to Django and trying to understand the model relationships, here is my use case:

I have a Creator object which can create multiple Listing under a Category. Category can have multiple Listings from multiple Creators.

Creator -- Creates a Listing about a service -- under a Category or multiple Category

I am trying to find the thought process behind picking the correct relationship while defining this kind circular  relationship.  Which one of the model should go first? Is it Category which is first and Creator second and Listing at the end, is Creator, Category and Listing all belong to a Many to Many relationship, if then how are they linked?

答:
In Django Models there are three types of relationships.

one to one - when one entity is unique to other entity
Example: A user model can be in one to one relationship to customer model.
Every customer is unique user

many to many - When one entity can has relationship with many other entities and vice versa.
Example : pizza and toppings,
pizza can have many toppings, and same topping can be applied on various pizza

one to many - also called foreign key in Django  when a single entity is related to many other entities but vice versa is not true.

Example: your Use case applies here.
A creator can create multiple listings but a single listing can be mapped to single creator only, not multiple creator.


问:
python multi-threading lock is not working as expected when doing number change
I am learning python3 multi-threading now and trying to test the following code. what the code does is to use multiple thread to modify a global number balance  (initial value = 0) in a function named test_change by first adding and then substracting a same number, and using a thread lock to ensure the balance variable will be changed by one thread at a time. And I am looping it for 100000 or more times to check weather the expected value 0 is displayed, however, quite disappointedly, 0 is not always the answer i can get. Here is the code below. And the editor I am using is Vscode.

balance = 0
def test_change(n):
    global balance
    balance += n
    balance -= n
    # print("in {}, balance is {}".format(threading.current_thread().name, balance))

class MyThread(threading.Thread):
    """ self-defined threading class """
    def __init__(self, target_fun, fun_args, loop=False):
        threading.Thread.__init__(self)
        self.target_fun = target_fun
        self.fun_args = fun_args
        self.loop = loop
        self.threadLock = threading.Lock()

    def run(self):  # overwrite parent run function
        if not self.loop:
            self.target_fun(*self.fun_args)
        elif self.loop:
            # with self.threadLock:  # balance [15]
                # for i in range(1000000):
                    # self.target_fun(self.fun_args)
            for i in range(100000):
                self.threadLock.acquire()
                self.target_fun(self.fun_args)
                self.threadLock.release()

nums = [5, 12]
thread_list = []
for i in range(2):  # create 2 thread object
    t = MyThread(target_fun=test_change, fun_args=nums[i], loop=True)
    thread_list.append(t)

for i in range(len(thread_list)):  # start thread object
    thread_list[i].start()

for i in range(len(thread_list)):  # stop main thread till subthread finishes
    thread_list[i].join()

print("balance [{}]".format(balance))  # expected to be 0 always
print("subthread finishes")

```

<p>and here is part of the execution result that displayed, you can see the last output.</p>

```(face36) D:\P_project_SRS\face_cumstom_dual_cam_0506> cd d:\P_project_SRS\face_cumstom_dual_cam_0506 &ython.exe c:\Users\lijin\.vscode\extensions\ms-python.python-2020.5.80290\pythonFiles\lib\python\debugface_cumstom_dual_cam_0506\threading_producer_consumer.py "
balance [0]
subthread finishes

(face36) D:\P_project_SRS\face_cumstom_dual_cam_0506> cd d:\P_project_SRS\face_cumstom_dual_cam_0506 &ython.exe c:\Users\lijin\.vscode\extensions\ms-python.python-2020.5.80290\pythonFiles\lib\python\debugface_cumstom_dual_cam_0506\threading_producer_consumer.py "
balance [0]
(face36) D:\P_project_SRS\face_cumstom_dual_cam_0506> cd d:\P_project_SRS\face_cumstom_dual_cam_0506 && cmd /C "C:\LeeSRSPrgoramFile\A_anaconda\envs\face36\python.exe c:\Users\lijin\.vscode\extensions\ms-python.python-2020.5.80290\pythonFiles\lib\python\debugpy\no_wheels\debugpy\launcher 2863 -- d:\P_project_SRS\face_cumstom_dual_cam_0506\threading_producer_consumer.py "
balance [0]
subthread finishes

(face36) D:\P_project_SRS\face_cumstom_dual_cam_0506> cd d:\P_project_SRS\face_cumstom_dual_cam_0506 && cmd /C "C:\LeeSRSPrgoramFile\A_anaconda\envs\face36\python.exe c:\Users\lijin\.vscode\extensions\ms-python.python-2020.5.80290\pythonFiles\lib\python\debugpy\no_wheels\debugpy\launcher 2870 -- d:\P_project_SRS\face_cumstom_dual_cam_0506\threading_producer_consumer.py "
balance [0]
subthread finishes

(face36) D:\P_project_SRS\face_cumstom_dual_cam_0506> cd d:\P_project_SRS\face_cumstom_dual_cam_0506 && cmd /C "C:\LeeSRSPrgoramFile\A_anaconda\envs\face36\python.exe c:\Users\lijin\.vscode\extensions\ms-python.python-2020.5.80290\pythonFiles\lib\python\debugpy\no_wheels\debugpy\launcher 3383 -- d:\P_project_SRS\face_cumstom_dual_cam_0506\threading_producer_consumer.py "
balance [0]
subthread finishes

(face36) D:\P_project_SRS\face_cumstom_dual_cam_0506> cd d:\P_project_SRS\face_cumstom_dual_cam_0506 && cmd /C "C:\LeeSRSPrgoramFile\A_anaconda\envs\face36\python.exe c:\Users\lijin\.vscode\extensions\ms-python.python-2020.5.80290\pythonFiles\lib\python\debugpy\no_wheels\debugpy\launcher 3389 -- d:\P_project_SRS\face_cumstom_dual_cam_0506\threading_producer_consumer.py "
balance [0]
subthread finishes

(face36) D:\P_project_SRS\face_cumstom_dual_cam_0506> cd d:\P_project_SRS\face_cumstom_dual_cam_0506 && cmd /C "C:\LeeSRSPrgoramFile\A_anaconda\envs\face36\python.exe c:\Users\lijin\.vscode\extensions\ms-python.python-2020.5.80290\pythonFiles\lib\python\debugpy\no_wheels\debugpy\launcher 3394 -- d:\P_project_SRS\face_cumstom_dual_cam_0506\threading_producer_consumer.py "
balance [0]
subthread finishes

(face36) D:\P_project_SRS\face_cumstom_dual_cam_0506> cd d:\P_project_SRS\face_cumstom_dual_cam_0506 && cmd /C "C:\LeeSRSPrgoramFile\A_anaconda\envs\face36\python.exe c:\Users\lijin\.vscode\extensions\ms-python.python-2020.5.80290\pythonFiles\lib\python\debugpy\no_wheels\debugpy\launcher 3401 -- d:\P_project_SRS\face_cumstom_dual_cam_0506\threading_producer_consumer.py "
balance [0]
subthread finishes

(face36) D:\P_project_SRS\face_cumstom_dual_cam_0506> cd d:\P_project_SRS\face_cumstom_dual_cam_0506 && cmd /C "C:\LeeSRSPrgoramFile\A_anaconda\envs\face36\python.exe c:\Users\lijin\.vscode\extensions\ms-python.python-2020.5.80290\pythonFiles\lib\python\debugpy\no_wheels\debugpy\launcher 3406 -- d:\P_project_SRS\face_cumstom_dual_cam_0506\threading_producer_consumer.py "
balance [0]
subthread finishes

(face36) D:\P_project_SRS\face_cumstom_dual_cam_0506> cd d:\P_project_SRS\face_cumstom_dual_cam_0506 && cmd /C "C:\LeeSRSPrgoramFile\A_anaconda\envs\face36\python.exe c:\Users\lijin\.vscode\extensions\ms-python.python-2020.5.80290\pythonFiles\lib\python\debugpy\no_wheels\debugpy\launcher 3414 -- d:\P_project_SRS\face_cumstom_dual_cam_0506\threading_producer_consumer.py "
balance [12]  --> this is the result should never happened when using a lock.
subthread finishes

```

I have tried two python grammar for enable a lock which are with self.threadLock: (see the commented out part inside the class run function) and self.threadLock.acquire(), self.threadLock.release(), is there anyone can help to explain this oddity.

答:
by following @Tim Peters suggestion, I have the code modified as follows.

import time
import threading

from threading import Thread

balance = 0
def test_change(n):
    global balance
    balance += n
    balance -= n
    print("in {}, balance is {}".format(threading.current_thread().name, balance))

class MyThread(threading.Thread):
    """ self-defined threading class """
    def __init__(self, lock, target_fun, fun_args, loop=False):  # added a shared lock parameter
        threading.Thread.__init__(self)
        self.target_fun = target_fun
        self.fun_args = fun_args
        self.loop = loop
        self.lock = lock  # this is the shared lock

    def run(self):  # overwrite parent run function
        if not self.loop:
            self.target_fun(*self.fun_args)
        elif self.loop:
            for i in range(100):
                with self.lock:  # "with" after "for" so that both thread change the "balance" variable alternatively
                    self.target_fun(self.fun_args)

nums = [5, 12]
thread_list = []
thread_muduleLock = threading.Lock()  # added a shared lock

start = time.perf_counter()
for i in range(2):
    t = MyThread(thread_muduleLock, target_fun=test_change, fun_args=nums[i], loop=True)  # passing the shared lock to the thread constructor
    thread_list.append(t)

for i in range(len(thread_list)):
    thread_list[i].start()

for i in range(len(thread_list)):
    thread_list[i].join()
end = time.perf_counter()
total = end - start
print("balance [{}], total time [{}]".format(balance, total))
print("subthread finishes")
```

<p>here is the execution result:</p>

```in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
balance [0], total time [0.1192338]
subthread finishes
```

<p>In addition to those above, I have tried to compare the efficiency between <code>with</code> and <code>acquire(), release()</code> statement, found that the former is a bit faster than the latter, here's the result for 100 loops as below.</p>

```"""with"""
for i in range(100):  # with after for,
    with self.lock:
        self.target_fun(self.fun_args)

###### result ######
balance [0], total time [0.0022132000000000002]
subthread finishes

"""acquire & release """
for i in range(100):
    self.lock.acquire()
    self.target_fun(self.fun_args)
    self.lock.release()

###### result ######
balance [0], total time [0.0035131000000000003]
subthread finishes
```

Body:
I am learning python3 multi-threading now and trying to test the following code. what the code does is to use multiple thread to modify a global number balance  (initial value = 0) in a function named test_change by first adding and then substracting a same number, and using a thread lock to ensure the balance variable will be changed by one thread at a time. And I am looping it for 100000 or more times to check weather the expected value 0 is displayed, however, quite disappointedly, 0 is not always the answer i can get. Here is the code below. And the editor I am using is Vscode.

balance = 0
def test_change(n):
    global balance
    balance += n
    balance -= n
    # print("in {}, balance is {}".format(threading.current_thread().name, balance))

class MyThread(threading.Thread):
    """ self-defined threading class """
    def __init__(self, target_fun, fun_args, loop=False):
        threading.Thread.__init__(self)
        self.target_fun = target_fun
        self.fun_args = fun_args
        self.loop = loop
        self.threadLock = threading.Lock()

    def run(self):  # overwrite parent run function
        if not self.loop:
            self.target_fun(*self.fun_args)
        elif self.loop:
            # with self.threadLock:  # balance [15]
                # for i in range(1000000):
                    # self.target_fun(self.fun_args)
            for i in range(100000):
                self.threadLock.acquire()
                self.target_fun(self.fun_args)
                self.threadLock.release()

nums = [5, 12]
thread_list = []
for i in range(2):  # create 2 thread object
    t = MyThread(target_fun=test_change, fun_args=nums[i], loop=True)
    thread_list.append(t)

for i in range(len(thread_list)):  # start thread object
    thread_list[i].start()

for i in range(len(thread_list)):  # stop main thread till subthread finishes
    thread_list[i].join()

print("balance [{}]".format(balance))  # expected to be 0 always
print("subthread finishes")

and here is part of the execution result that displayed, you can see the last output.

(face36) D:\P_project_SRS\face_cumstom_dual_cam_0506> cd d:\P_project_SRS\face_cumstom_dual_cam_0506 &ython.exe c:\Users\lijin\.vscode\extensions\ms-python.python-2020.5.80290\pythonFiles\lib\python\debugface_cumstom_dual_cam_0506\threading_producer_consumer.py "
balance [0]
subthread finishes

(face36) D:\P_project_SRS\face_cumstom_dual_cam_0506> cd d:\P_project_SRS\face_cumstom_dual_cam_0506 &ython.exe c:\Users\lijin\.vscode\extensions\ms-python.python-2020.5.80290\pythonFiles\lib\python\debugface_cumstom_dual_cam_0506\threading_producer_consumer.py "
balance [0]
(face36) D:\P_project_SRS\face_cumstom_dual_cam_0506> cd d:\P_project_SRS\face_cumstom_dual_cam_0506 && cmd /C "C:\LeeSRSPrgoramFile\A_anaconda\envs\face36\python.exe c:\Users\lijin\.vscode\extensions\ms-python.python-2020.5.80290\pythonFiles\lib\python\debugpy\no_wheels\debugpy\launcher 2863 -- d:\P_project_SRS\face_cumstom_dual_cam_0506\threading_producer_consumer.py "
balance [0]
subthread finishes

(face36) D:\P_project_SRS\face_cumstom_dual_cam_0506> cd d:\P_project_SRS\face_cumstom_dual_cam_0506 && cmd /C "C:\LeeSRSPrgoramFile\A_anaconda\envs\face36\python.exe c:\Users\lijin\.vscode\extensions\ms-python.python-2020.5.80290\pythonFiles\lib\python\debugpy\no_wheels\debugpy\launcher 2870 -- d:\P_project_SRS\face_cumstom_dual_cam_0506\threading_producer_consumer.py "
balance [0]
subthread finishes

(face36) D:\P_project_SRS\face_cumstom_dual_cam_0506> cd d:\P_project_SRS\face_cumstom_dual_cam_0506 && cmd /C "C:\LeeSRSPrgoramFile\A_anaconda\envs\face36\python.exe c:\Users\lijin\.vscode\extensions\ms-python.python-2020.5.80290\pythonFiles\lib\python\debugpy\no_wheels\debugpy\launcher 3383 -- d:\P_project_SRS\face_cumstom_dual_cam_0506\threading_producer_consumer.py "
balance [0]
subthread finishes

(face36) D:\P_project_SRS\face_cumstom_dual_cam_0506> cd d:\P_project_SRS\face_cumstom_dual_cam_0506 && cmd /C "C:\LeeSRSPrgoramFile\A_anaconda\envs\face36\python.exe c:\Users\lijin\.vscode\extensions\ms-python.python-2020.5.80290\pythonFiles\lib\python\debugpy\no_wheels\debugpy\launcher 3389 -- d:\P_project_SRS\face_cumstom_dual_cam_0506\threading_producer_consumer.py "
balance [0]
subthread finishes

(face36) D:\P_project_SRS\face_cumstom_dual_cam_0506> cd d:\P_project_SRS\face_cumstom_dual_cam_0506 && cmd /C "C:\LeeSRSPrgoramFile\A_anaconda\envs\face36\python.exe c:\Users\lijin\.vscode\extensions\ms-python.python-2020.5.80290\pythonFiles\lib\python\debugpy\no_wheels\debugpy\launcher 3394 -- d:\P_project_SRS\face_cumstom_dual_cam_0506\threading_producer_consumer.py "
balance [0]
subthread finishes

(face36) D:\P_project_SRS\face_cumstom_dual_cam_0506> cd d:\P_project_SRS\face_cumstom_dual_cam_0506 && cmd /C "C:\LeeSRSPrgoramFile\A_anaconda\envs\face36\python.exe c:\Users\lijin\.vscode\extensions\ms-python.python-2020.5.80290\pythonFiles\lib\python\debugpy\no_wheels\debugpy\launcher 3401 -- d:\P_project_SRS\face_cumstom_dual_cam_0506\threading_producer_consumer.py "
balance [0]
subthread finishes

(face36) D:\P_project_SRS\face_cumstom_dual_cam_0506> cd d:\P_project_SRS\face_cumstom_dual_cam_0506 && cmd /C "C:\LeeSRSPrgoramFile\A_anaconda\envs\face36\python.exe c:\Users\lijin\.vscode\extensions\ms-python.python-2020.5.80290\pythonFiles\lib\python\debugpy\no_wheels\debugpy\launcher 3406 -- d:\P_project_SRS\face_cumstom_dual_cam_0506\threading_producer_consumer.py "
balance [0]
subthread finishes

(face36) D:\P_project_SRS\face_cumstom_dual_cam_0506> cd d:\P_project_SRS\face_cumstom_dual_cam_0506 && cmd /C "C:\LeeSRSPrgoramFile\A_anaconda\envs\face36\python.exe c:\Users\lijin\.vscode\extensions\ms-python.python-2020.5.80290\pythonFiles\lib\python\debugpy\no_wheels\debugpy\launcher 3414 -- d:\P_project_SRS\face_cumstom_dual_cam_0506\threading_producer_consumer.py "
balance [12]  --> this is the result should never happened when using a lock.
subthread finishes

I have tried two python grammar for enable a lock which are with self.threadLock: (see the commented out part inside the class run function) and self.threadLock.acquire(), self.threadLock.release(), is there anyone can help to explain this oddity.

Body:
by following @Tim Peters suggestion, I have the code modified as follows.

import time
import threading

from threading import Thread

balance = 0
def test_change(n):
    global balance
    balance += n
    balance -= n
    print("in {}, balance is {}".format(threading.current_thread().name, balance))

class MyThread(threading.Thread):
    """ self-defined threading class """
    def __init__(self, lock, target_fun, fun_args, loop=False):  # added a shared lock parameter
        threading.Thread.__init__(self)
        self.target_fun = target_fun
        self.fun_args = fun_args
        self.loop = loop
        self.lock = lock  # this is the shared lock

    def run(self):  # overwrite parent run function
        if not self.loop:
            self.target_fun(*self.fun_args)
        elif self.loop:
            for i in range(100):
                with self.lock:  # "with" after "for" so that both thread change the "balance" variable alternatively
                    self.target_fun(self.fun_args)

nums = [5, 12]
thread_list = []
thread_muduleLock = threading.Lock()  # added a shared lock

start = time.perf_counter()
for i in range(2):
    t = MyThread(thread_muduleLock, target_fun=test_change, fun_args=nums[i], loop=True)  # passing the shared lock to the thread constructor
    thread_list.append(t)

for i in range(len(thread_list)):
    thread_list[i].start()

for i in range(len(thread_list)):
    thread_list[i].join()
end = time.perf_counter()
total = end - start
print("balance [{}], total time [{}]".format(balance, total))
print("subthread finishes")

here is the execution result:

in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-7, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
in Thread-6, balance is 0
balance [0], total time [0.1192338]
subthread finishes

In addition to those above, I have tried to compare the efficiency between with and acquire(), release() statement, found that the former is a bit faster than the latter, here's the result for 100 loops as below.

"""with"""
for i in range(100):  # with after for,
    with self.lock:
        self.target_fun(self.fun_args)

###### result ######
balance [0], total time [0.0022132000000000002]
subthread finishes

"""acquire & release """
for i in range(100):
    self.lock.acquire()
    self.target_fun(self.fun_args)
    self.lock.release()

###### result ######
balance [0], total time [0.0035131000000000003]
subthread finishes


问:
System.NullReferenceException: Object reference not set to an instance of an object

Possible Duplicates:
  What is a NullReferenceException in .NET?
  System.NullReferenceException: Object reference not set to an instance of an object

I am using the following code.

```<code>public partial class SectionControls_SingleBanners : SectionControlBaseClass
{
    private SingleBanners _section;

    protected void Page_PreRender(object sender, EventArgs e) {
        updateViews();

        if (RssCapable(this._section.GetType()) && _section.BannersEntries.Rows.Count > 0)  {
</code>```

So here on this code I am getting the error

```<code>this._section.GetType();
</code>```

How can this problem be fixed?

答:
You can't execute a non-static method on a object that wasn't instantiated.

Try this:

```<code>private SingleBanners _section = new SingleBanners();
</code>```

Body:
Possible Duplicates:
  What is a NullReferenceException in .NET?
  System.NullReferenceException: Object reference not set to an instance of an object

I am using the following code.

public partial class SectionControls_SingleBanners : SectionControlBaseClass
{
    private SingleBanners _section;

    protected void Page_PreRender(object sender, EventArgs e) {
        updateViews();

        if (RssCapable(this._section.GetType()) && _section.BannersEntries.Rows.Count > 0)  {

So here on this code I am getting the error

this._section.GetType();

How can this problem be fixed?

Body:
You can't execute a non-static method on a object that wasn't instantiated.

Try this:

private SingleBanners _section = new SingleBanners();


问:
JSON always returning "client_id not specified"
I'm trying to get a token from the ArcGIS Online service using a Javascript. However, it's always returning an error which indicates the client_id isn't specified.

Am I doing everything right here?

```<code><script type="text/javascript">
    var MyJSONText = '{"client_id":"<<MY_CLIENT_ID>>","client_secret":"<<MY_CLIENT_SECRET>>","grant_type":"client_credentials","expiration":"1440","f":"json"}';
    var MyJSON = JSON.parse(MyJSONText);
    xhr = new XMLHttpRequest();
    xhr.open("POST", "https://www.arcgis.com/sharing/rest/oauth2/token/");
    xhr.send(MyJSON);
    xhr.onreadystatechange = function ()
    {
        if (xhr.readyState == 4 && xhr.status == 200)
        {
            alert(xhr.responseText);
        }
    }

</script>
</code>```

Edit - full error is:

```<code>{"error":{"code":400,"error":"invalid_request","error_description":"client_id not specified","message":"client_id not specified","details":[]}}
</code>```

答:
Access Token Generation Url =>https://www.arcgis.com/sharing/rest/oauth2/token

Headers
enter image description here

For the Case of body in Post man select 'x-www-form-urlencoded'

enter image description here

After that you will get the respective expected result with token

```<code>{"access_token":"S-z3mxAqsZBeihx8NgFmNGsZAUGfzKZWCYVV2TiQO422u9XDLTCTZAkpoecyxx_LAc71I_tPkeeOlo2Pzkapv01bBOA03SzMRjRMOm-h3ljTl-pb3XdffoyYjCflE4F8LD377DbpjDWkupkdTaxJpg..","expires_in":7200}
</code>```

Body:
I'm trying to get a token from the ArcGIS Online service using a Javascript. However, it's always returning an error which indicates the client_id isn't specified.

Am I doing everything right here?

Edit - full error is:

{"error":{"code":400,"error":"invalid_request","error_description":"client_id not specified","message":"client_id not specified","details":[]}}

Body:
Access Token Generation Url =>https://www.arcgis.com/sharing/rest/oauth2/token

Headers
enter image description here

For the Case of body in Post man select 'x-www-form-urlencoded'

enter image description here

After that you will get the respective expected result with token

{"access_token":"S-z3mxAqsZBeihx8NgFmNGsZAUGfzKZWCYVV2TiQO422u9XDLTCTZAkpoecyxx_LAc71I_tPkeeOlo2Pzkapv01bBOA03SzMRjRMOm-h3ljTl-pb3XdffoyYjCflE4F8LD377DbpjDWkupkdTaxJpg..","expires_in":7200}


问:
What kind of encoding is this: \x3Cb\x3E\x3C?
I'm receiving data from an AJAX request, and it's really weird. I thought it was unicode, but unicode's codes are like \u00E7 (ç).

```<code>\x3Cb\x3E\x3C
</code>```

What do you think this is? And how can I convert it to normal text with Java?

答: It might be plain ASCII. \x3Cb\x3E\x3C decodes to <.

Body:
I'm receiving data from an AJAX request, and it's really weird. I thought it was unicode, but unicode's codes are like \u00E7 (ç).

\x3Cb\x3E\x3C

What do you think this is? And how can I convert it to normal text with Java?

Body: It might be plain ASCII. \x3Cb\x3E\x3C decodes to <b><.


问:
Release configuration for asp.net forms website
In .net web applications we have at least two build configurations which allows us to build for debug and build for release.

There is only debug build configuration in website project. I have read the Microsoft explanation of website are not complied, so they do not need a release configuration.

But still there are some specific configurations to be added when deploying to the production,

eg:- We have to set debug to false under compilation.

Is there a way to pre configure build/publish. So we do not need any manual config change when deploying for production?

答:
No other way to change it.

Generally, we sets two environments for application, one is for debugging, one is for production.


问:
How check time overlaps in rails
I created a model: Lecture(start_time, end_time, location). I want to write validation functions to check wether the new lecture's time overlapping with saved lectures in database. So that I can find out if the location is occupied in that time. My function is:

```<code>class Lecture < ActiveRecord::Base

validates :title, :position, presence: true

validates :start_time, :end_time, format: { with: /([01][0-9]|2[0-3]):([0-5][0-9])/,
         message: "Incorrect time format" }

validate: time_overlap

def time_overlap
    Lecture.all.each do |user|
       if (user.start_time - end_time) * (start_time - user.end_time) >= 0
       errors.add(:Base, "time overlaps")
       end
     end
end

end
</code>```

The error message: NoMethodError in LecturesController#create
undefined method `-@' for nil:NilClass. How to write this function in right format?

答:
Lets say you have two slots of time, as:

```<code>start_time_a
end_time_a
start_time_b
end_time_b
</code>```

There are three possible cases where there can be an overlap between the two time slots.

1) start_time_b >= start_time_a && start_time_b =< end_time_a ( i.e, slot b starts somewhere in the middle of slot a )

2) end_time_b >= start_time_a && end_time_b <= end_time_a ( i.e, slot b ends somewhere between slot a )

3) start_time_b <= start_time_a && end_time_b >= end_time_a ( i.e, slot b is larger than slot a, and completely covers it.

If you check for these three conditions, you can determine if there's an overlap between two time slots.

Conditions 1 & 2 can be simplified using start_time_b.between?(start_time_a, end_time_a).

Title: How check time overlaps in rails

Body:
I created a model: Lecture(start_time, end_time, location). I want to write validation functions to check wether the new lecture's time overlapping with saved lectures in database. So that I can find out if the location is occupied in that time. My function is:

class Lecture < ActiveRecord::Base

validates :title, :position, presence: true

validates :start_time, :end_time, format: { with: /([01][0-9]|2[0-3]):([0-5][0-9])/,
         message: "Incorrect time format" }

validate: time_overlap

def time_overlap
    Lecture.all.each do |user|
       if (user.start_time - end_time) * (start_time - user.end_time) >= 0
       errors.add(:Base, "time overlaps")
       end
     end
end

end

The error message: NoMethodError in LecturesController#create
undefined method `-@' for nil:NilClass. How to write this function in right format?

Body:
Lets say you have two slots of time, as:

start_time_a
end_time_a
start_time_b
end_time_b

There are three possible cases where there can be an overlap between the two time slots.

1) start_time_b >= start_time_a && start_time_b =< end_time_a ( i.e, slot b starts somewhere in the middle of slot a )

2) end_time_b >= start_time_a && end_time_b <= end_time_a ( i.e, slot b ends somewhere between slot a )

3) start_time_b <= start_time_a && end_time_b >= end_time_a ( i.e, slot b is larger than slot a, and completely covers it.

If you check for these three conditions, you can determine if there's an overlap between two time slots.

Conditions 1 & 2 can be simplified using start_time_b.between?(start_time_a, end_time_a).


问:
Detecting unused functions at build time in Haskell
I'm trying to get the GHC to warn me whenever I write a new function and forget to use it anywhere. I've added the following function in my Main.hs:

```<code>unused :: () -> ()
unused _ = ()
</code>```

and of course not used it.

I have the following in my *.cabal file:

```<code> ghc-options:
    -W
    -Wall
    -Werror
    -Wcompat
    -Wincomplete-uni-patterns
    -Wincomplete-record-updates
    -Wredundant-constraints
    -Wpartial-fields
    -Wunused-binds
</code>```

I've specifically added -Wunused-binds to try to force the compiler to fail on this but it does not report any warning about an unused function.

Any idea what am I doing wrong here?

EDIT

Just to give a bigger picture, here is the beggining of the main file:

```<code>
{-# LANGUAGE OverloadedStrings          #-}
{-# LANGUAGE DataKinds                  #-}
{-# LANGUAGE FlexibleContexts           #-}
{-# LANGUAGE FlexibleInstances          #-}
{-# LANGUAGE MultiParamTypeClasses      #-}
{-# LANGUAGE ScopedTypeVariables        #-}
{-# LANGUAGE TemplateHaskell            #-}
{-# LANGUAGE TypeApplications           #-}
{-# LANGUAGE TypeFamilies               #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}

module Main where

import           Apecs
import           Linear                         ( V2(..) )
import           Control.Monad
import           Control.Monad.IO.Class
import           Control.Monad.Catch
import qualified System.Terminal               as T
import           System.Terminal.Internal
import qualified Data.Map                      as M
import           System.Random
</code>```

答:
Exporting only main function from module fixed the issue:

```<code>module Main(main) where
</code>```

EDIT

Just for reference, this flag is already contained in -Wall so it would be enough to have this in cabal to catch it:

```<code>  ghc-options:
    -Wall
    -Werror
</code>```

Body:
I'm trying to get the GHC to warn me whenever I write a new function and forget to use it anywhere. I've added the following function in my Main.hs:

unused :: () -> ()
unused _ = ()

and of course not used it.

I have the following in my *.cabal file:

 ghc-options:
    -W
    -Wall
    -Werror
    -Wcompat
    -Wincomplete-uni-patterns
    -Wincomplete-record-updates
    -Wredundant-constraints
    -Wpartial-fields
    -Wunused-binds

I've specifically added -Wunused-binds to try to force the compiler to fail on this but it does not report any warning about an unused function.

Any idea what am I doing wrong here?

EDIT

Just to give a bigger picture, here is the beggining of the main file:

{-# LANGUAGE OverloadedStrings          #-}
{-# LANGUAGE DataKinds                  #-}
{-# LANGUAGE FlexibleContexts           #-}
{-# LANGUAGE FlexibleInstances          #-}
{-# LANGUAGE MultiParamTypeClasses      #-}
{-# LANGUAGE ScopedTypeVariables        #-}
{-# LANGUAGE TemplateHaskell            #-}
{-# LANGUAGE TypeApplications           #-}
{-# LANGUAGE TypeFamilies               #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}

module Main where

import           Apecs
import           Linear                         ( V2(..) )
import           Control.Monad
import           Control.Monad.IO.Class
import           Control.Monad.Catch
import qualified System.Terminal               as T
import           System.Terminal.Internal
import qualified Data.Map                      as M
import           System.Random

Body:
Exporting only main function from module fixed the issue:

module Main(main) where

EDIT

Just for reference, this flag is already contained in -Wall so it would be enough to have this in cabal to catch it:

  ghc-options:
    -Wall
    -Werror


问:
how to store two field value in one mysql field in wordpress custom
this is my array code to store value in the data table.
I want to store four fields value in one MySQL field

i need to store answer1, answer2, answer3, answer4 in answer row

it's shown an error:- wpdb::prepare was called incorrectly. Unsupported value type (array). Please see Debugging in WordPress for more information. (This message was added in version 4.8.2.)

this is my array code

```<code>    if(isset($_POST['submit'])){
    $answer1=$_POST['answer1'];
    $answer2=$_POST['answer2'];
    $answer3=$_POST['answer3'];
    $answer4=$_POST['answer4'];
    $table_name2 = $wpdb->prefix . 'pte_quiz';
    $wpdb->insert(
      $table_name2,
      array(
        'answer' => array('answer1' =>$answer1, 'answer2' =>$answer2, 'answer3' =>$answer3, 'answer4' =>$answer4),
        'uid' => $uid,
        'user' => $user )
        );
        echo "Your answer successfully submited!!!";?><br>
        Your Answer is <?php echo $answer;
exit;
}
</code>```

答:
Give it a try

```<code>   if(isset($_POST['submit'])){
    $answer1=$_POST['answer1'];
    $answer2=$_POST['answer2'];
    $answer3=$_POST['answer3'];
    $answer4=$_POST['answer4'];
    $table_name2 = $wpdb->prefix . 'pte_quiz';
    $wpdb->insert(
      $table_name2,
      array(
        'answer' => json_encode(array('answer1' =>$answer1, 'answer2' =>$answer2, 'answer3' =>$answer3, 'answer4' =>$answer4)),
        'uid' => $uid,
        'user' => $user )
        );
        echo "Your answer successfully submited!!!";?><br>
        Your Answer is <?php echo json_decode($answer,true);
exit;
}
</code>```

We can simply convert the answers array into a JSON string and store that into database. Later when we need to use the stored value, we can simply json_decode() it and get the desired array.

Body:
this is my array code to store value in the data table.
I want to store four fields value in one MySQL field

i need to store answer1, answer2, answer3, answer4 in answer row

it's shown an error:- wpdb::prepare was called incorrectly. Unsupported value type (array). Please see Debugging in WordPress for more information. (This message was added in version 4.8.2.)

this is my array code

    if(isset($_POST['submit'])){
    $answer1=$_POST['answer1'];
    $answer2=$_POST['answer2'];
    $answer3=$_POST['answer3'];
    $answer4=$_POST['answer4'];
    $table_name2 = $wpdb->prefix . 'pte_quiz';
    $wpdb->insert(
      $table_name2,
      array(
        'answer' => array('answer1' =>$answer1, 'answer2' =>$answer2, 'answer3' =>$answer3, 'answer4' =>$answer4),
        'uid' => $uid,
        'user' => $user )
        );
        echo "Your answer successfully submited!!!";?>

        Your Answer is <?php echo $answer;
exit;
}

Body:
Give it a try

   if(isset($_POST['submit'])){
    $answer1=$_POST['answer1'];
    $answer2=$_POST['answer2'];
    $answer3=$_POST['answer3'];
    $answer4=$_POST['answer4'];
    $table_name2 = $wpdb->prefix . 'pte_quiz';
    $wpdb->insert(
      $table_name2,
      array(
        'answer' => json_encode(array('answer1' =>$answer1, 'answer2' =>$answer2, 'answer3' =>$answer3, 'answer4' =>$answer4)),
        'uid' => $uid,
        'user' => $user )
        );
        echo "Your answer successfully submited!!!";?><br>
        Your Answer is <?php echo json_decode($answer,true);
exit;
}

We can simply convert the answers array into a JSON string and store that into database. Later when we need to use the stored value, we can simply json_decode() it and get the desired array.


问:
IDE for pyglet?
I'm starting to code with pyglet in Windows. I usually rely on Spyder as an IDE, but it seems not to like pyglet. So what would be a convenient way to code / run pyglet in Windows? What is your minimal development setup? Short of obvious minimal setups such as running code on Console2 or using IDLE.

答: pycharm, I would highly recommend. The free version has all you need, and is very highly organised. I use it all the time. You'll need to copy your pyglet file into every project tho. Still, it's easy to use and functional, and comes with a lot of good tools.</p>

Title: IDE for pyglet?


问:
Reference to all JSP files in web.xml
I have all the jsp files used by a webapp in a separate folder named jsp. I tried reference all the jsp files in the web.xml by the following way. But doesn't work. What could be the problem?

**

```<code><servlet>
<servlet-name>Jsps</servlet-name>
<jsp-file>/jsp/path/</jsp-file>
</servlet>

<servlet-mapping>
<servlet-name>Jsps</servlet-name>
<url-pattern>/*.jsp<url-pattern>
</servlet-mapping>
</code>```

**

答:
You cannot group jsps together under one servlet. If jsp is to be declared as a servlet, Each jsp should be defined as one servlet. For ex:

```<code><servlet>
<servlet-name>Jsp1</servlet-name>
<jsp-file>/jsp/path/myjsp.jsp</jsp-file>
</servlet>

<servlet-mapping>
<servlet-name>Jsp1</servlet-name>
<url-pattern>/myjsp.jsp<url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>Jsp2</servlet-name>
<jsp-file>/jsp/path/myjsp2.jsp</jsp-file>
</servlet>

<servlet-mapping>
<servlet-name>Jsp2</servlet-name>
<url-pattern>/myjsp2.jsp<url-pattern>
</servlet-mapping>
</code>```

If your requirement if just to access jsps , you do not need any  servlet definitions or servlet mappings. Access it directly using /jsp/path/myjsp.jsp path

Title: Reference to all JSP files in web.xml

Body:
I have all the jsp files used by a webapp in a separate folder named jsp. I tried reference all the jsp files in the web.xml by the following way. But doesn't work. What could be the problem?

**

<servlet>
<servlet-name>Jsps</servlet-name>
<jsp-file>/jsp/path/</jsp-file>
</servlet>

<servlet-mapping>
<servlet-name>Jsps</servlet-name>
<url-pattern>/*.jsp<url-pattern>
</servlet-mapping>

**

Body:
You cannot group jsps together under one servlet. If jsp is to be declared as a servlet, Each jsp should be defined as one servlet. For ex:

<servlet>
<servlet-name>Jsp1</servlet-name>
<jsp-file>/jsp/path/myjsp.jsp</jsp-file>
</servlet>

<servlet-mapping>
<servlet-name>Jsp1</servlet-name>
<url-pattern>/myjsp.jsp<url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>Jsp2</servlet-name>
<jsp-file>/jsp/path/myjsp2.jsp</jsp-file>
</servlet>

<servlet-mapping>
<servlet-name>Jsp2</servlet-name>
<url-pattern>/myjsp2.jsp<url-pattern>
</servlet-mapping>

If your requirement if just to access jsps , you do not need any  servlet definitions or servlet mappings. Access it directly using /jsp/path/myjsp.jsp path


问:
How to extract Month and Year from column in PowerBI powerquery
I have a column (monthyear) in the image below. I want to extract the Month and year from the column to put it in the new column. Note: In my dataset this information goes for every day of the year

So the new column would look like:
01/2020
01/2020
01/2020
etc.

答:
In Power Query, use some of the date functions.

To get the year it will be

```<code>Date.Year([monthyear])
</code>```

For the month, it will depend on how you want to format it. Using the month of June as an example:

To get 'Jun'

```<code>Date.ToText([monthyear],"MMM")
</code>```

To get the month number in the format 06

```<code>Number.ToText(Date.Month([monthyear]), "00")
</code>```

Just to get the number 6 it will be:

```<code>Date.Month([monthyear])
</code>```

In DAX use the date functions

For year the calculated column will be:

```<code>YEAR([monthyear])
</code>```

For the month:

```<code>MONTH([monthyear])
</code>```

I would always do a much data transformation in Power Query when you can before it gets to the data model.

Body:
In Power Query, use some of the date functions.

To get the year it will be

Date.Year([monthyear])

For the month, it will depend on how you want to format it. Using the month of June as an example:

To get 'Jun'

Date.ToText([monthyear],"MMM")

To get the month number in the format 06

Number.ToText(Date.Month([monthyear]), "00")

Just to get the number 6 it will be:

Date.Month([monthyear])

In DAX use the date functions

For year the calculated column will be:

YEAR([monthyear])

For the month:

MONTH([monthyear])

I would always do a much data transformation in Power Query when you can before it gets to the data model.


问:
Saving h5 model by relative path - Keras tensorflow
Hey to my beloved community.

How do we save a model to a relative file path using tensorflow embedded keras?

```<code>    model.save('/models/model.h5')
</code>```

I tried:

```<code>'./models/'
'/models/'
'models/'
</code>```

Neither seems to work and I always end up with:

```<code>InvalidArgumentError (see above for traceback): Failed to create a NewWriteableFile:
</code>```

I don't want to provide an absolute path as it might change dynamically.

答:
Here is a simple example of a function that responds to the question. If the folder does not exist create a new one else use the existing folder.</p>

```<code>def save_model(path, model):
    if not os.path.exists(path):
        print('save directories...', flush=True)
        os.makedirs(path)
    model.save(path + '/handrecognition_model.h5')
</code>```

Body:
Hey to my beloved community.

How do we save a model to a relative file path using tensorflow embedded keras?

    model.save('/models/model.h5')

I tried:

'./models/'
'/models/'
'models/'

Neither seems to work and I always end up with:

InvalidArgumentError (see above for traceback): Failed to create a NewWriteableFile:

I don't want to provide an absolute path as it might change dynamically.

Body:
Here is a simple example of a function that responds to the question. If the folder does not exist create a new one else use the existing folder.

def save_model(path, model):
    if not os.path.exists(path):
        print('save directories...', flush=True)
        os.makedirs(path)
    model.save(path + '/handrecognition_model.h5')


问:
What does the localhost: 3000 server created by express mean?
What is it that you access when you type in "localhost: 3000" onto your browser? What does that represent? </p>

答:
localhost is a special domain name that always refers to your local computer.

3000 is a tcp port. When you open a url such as:

```<code>http://localhost:3000/
</code>```

Then a connection will get opened to port 3000.

When you specify a url like:

```<code>http://localhost/
</code>```

Then you will open port 80, because the default HTTP port is 80

Body:
localhost is a special domain name that always refers to your local computer.

3000 is a tcp port. When you open a url such as:

http://localhost:3000/

Then a connection will get opened to port 3000.

When you specify a url like:

http://localhost/

Then you will open port 80, because the default HTTP port is 80